@aislop-inc/opencode-mem 0.0.0-stage → 2.41.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 (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,386 @@
1
+ import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { basename, join, relative, resolve } from "node:path";
3
+ import { CONFIG } from "../config.js";
4
+ import { extractScopeFromContainerTag } from "./memory-scope.js";
5
+ import { getProjectTagInfo } from "./tags.js";
6
+ import { ensureTursoReady } from "./turso/ready.js";
7
+ import { acquireTursoOperationLock, isTursoLockOwnershipLostError, } from "./turso/operation-lock.js";
8
+ import { tursoShardManager } from "./turso/shard-manager.js";
9
+ import { tursoConnectionManager } from "./turso/connection-manager.js";
10
+ import { tursoVectorSearch } from "./turso/vector-search.js";
11
+ import { withSqliteFileLockRetry, renameSqliteDatabase, removeSqliteDatabase, copySqliteDatabase, } from "./turso/sqlite-handle-release.js";
12
+ import { log } from "./logger.js";
13
+ import { shardInventoryService, } from "./shard-inventory-service.js";
14
+ import { userPromptManager } from "./user-prompt/user-prompt-manager.js";
15
+ function swapStatePath() {
16
+ return join(CONFIG.storagePath, ".path-migrate-swap.json");
17
+ }
18
+ function writeSwapState(path, state) {
19
+ writeFileSync(path, JSON.stringify(state), "utf-8");
20
+ }
21
+ function assertRecoveryPathInsideStorage(path) {
22
+ const rel = relative(resolve(CONFIG.storagePath), resolve(path));
23
+ if (rel === "" || rel.startsWith("..") || rel.includes("\0")) {
24
+ throw new Error(`Path-migrate recovery path escapes storage: ${path}`);
25
+ }
26
+ }
27
+ async function countLiveMemories(dbPath) {
28
+ if (!existsSync(dbPath))
29
+ return 0;
30
+ const db = await tursoConnectionManager.getConnection(dbPath);
31
+ return tursoVectorSearch.countAllVectors(db);
32
+ }
33
+ async function removeFile(path) {
34
+ await tursoConnectionManager.closeConnection(path);
35
+ if (existsSync(path)) {
36
+ await withSqliteFileLockRetry(() => removeSqliteDatabase(path));
37
+ }
38
+ }
39
+ export class ShardPathMigrationService {
40
+ async migrate(options) {
41
+ await ensureTursoReady();
42
+ const target = getProjectTagInfo(options.currentDirectory);
43
+ const newHash = extractScopeFromContainerTag(target.tag).hash;
44
+ const resolveResult = await shardInventoryService.resolveMigrationSource(options.currentDirectory, { fromPath: options.fromPath, fromHash: options.fromHash });
45
+ if (!resolveResult.success || !resolveResult.source) {
46
+ return {
47
+ success: false,
48
+ dryRun: Boolean(options.dryRun),
49
+ error: resolveResult.error,
50
+ candidates: resolveResult.candidates,
51
+ };
52
+ }
53
+ const source = resolveResult.source;
54
+ const oldHash = source.scopeHash;
55
+ const resultBase = {
56
+ dryRun: Boolean(options.dryRun),
57
+ oldHash,
58
+ newHash,
59
+ oldPath: source.group.projectPath,
60
+ newPath: target.projectPath,
61
+ matchedBy: source.matchedBy,
62
+ };
63
+ if (oldHash === newHash) {
64
+ return {
65
+ success: true,
66
+ ...resultBase,
67
+ migratedShards: 0,
68
+ migratedMemories: 0,
69
+ actions: [],
70
+ };
71
+ }
72
+ if (source.group.pathExists && !options.allowLinkedSource) {
73
+ return {
74
+ success: false,
75
+ ...resultBase,
76
+ error: `Migration refused: source project path still exists (${source.group.projectPath}). ` +
77
+ "Set allowLinkedSource: true only after confirming that this active project should be reassociated.",
78
+ };
79
+ }
80
+ // Inventory may discover a valid shard added after startup reconciliation.
81
+ // Register it so list-shards and migrate operate on the same set.
82
+ for (const descriptor of source.group.shards) {
83
+ if (descriptor.shardId === null && descriptor.fileExists) {
84
+ await tursoShardManager.registerExistingShard("project", oldHash, descriptor.shardIndex, descriptor.dbPath, descriptor.memoryCount, descriptor.isActive);
85
+ }
86
+ }
87
+ const sourceShards = await tursoShardManager.getAllShards("project", oldHash);
88
+ if (sourceShards.length === 0) {
89
+ return {
90
+ success: false,
91
+ ...resultBase,
92
+ error: `No usable shards found for source hash ${oldHash}`,
93
+ };
94
+ }
95
+ // Strict conflict policy: any non-empty target aborts unchanged.
96
+ const targetShards = await tursoShardManager.getAllShards("project", newHash);
97
+ for (const shard of targetShards) {
98
+ const liveCount = await countLiveMemories(shard.dbPath);
99
+ if (liveCount > 0 || shard.vectorCount > 0) {
100
+ return {
101
+ success: false,
102
+ ...resultBase,
103
+ error: `Migration aborted: target project already has ${Math.max(liveCount, shard.vectorCount)} memories ` +
104
+ `(shard ${basename(shard.dbPath)}). Delete or forget those memories first, or use export/import.`,
105
+ };
106
+ }
107
+ }
108
+ const oldContainerTag = source.group.containerTag ?? `${CONFIG.containerTagPrefix}_project_${oldHash}`;
109
+ const nonce = `${process.pid}-${Date.now()}`;
110
+ const moves = sourceShards.map((shard) => {
111
+ const newPath = tursoShardManager.getShardPath("project", newHash, shard.shardIndex);
112
+ const inventoryShard = source.group.shards.find((candidate) => candidate.shardIndex === shard.shardIndex);
113
+ return {
114
+ shardId: shard.id,
115
+ shardIndex: shard.shardIndex,
116
+ oldPath: shard.dbPath,
117
+ newPath,
118
+ stagedPath: `${newPath}.path-migrate-${nonce}.tmp`,
119
+ backupPath: `${shard.dbPath}.pre-path-migrate-${nonce}.bak`,
120
+ isActive: shard.isActive,
121
+ vectorCount: inventoryShard?.memoryCount ?? shard.vectorCount,
122
+ oldContainerTag,
123
+ };
124
+ });
125
+ for (const move of moves) {
126
+ if (existsSync(move.newPath) && !targetShards.some((s) => s.dbPath === move.newPath)) {
127
+ if ((await countLiveMemories(move.newPath)) > 0) {
128
+ return {
129
+ success: false,
130
+ ...resultBase,
131
+ error: `Migration aborted: target shard file already contains memories (${basename(move.newPath)}).`,
132
+ };
133
+ }
134
+ }
135
+ }
136
+ const actions = moves.map((move) => ({
137
+ type: "rename",
138
+ detail: `${basename(move.oldPath)} -> ${basename(move.newPath)}`,
139
+ }));
140
+ for (const shard of targetShards) {
141
+ actions.push({ type: "archive-empty-target", detail: basename(shard.dbPath) });
142
+ }
143
+ const migratedMemories = (await Promise.all(moves.map((move) => countLiveMemories(move.oldPath)))).reduce((sum, count) => sum + count, 0);
144
+ actions.push({
145
+ type: "update-memories",
146
+ detail: `Remap container_tag and project metadata for ${migratedMemories} memories`,
147
+ });
148
+ if (source.group.projectPath && target.projectPath) {
149
+ actions.push({
150
+ type: "update-prompts",
151
+ detail: `${source.group.projectPath} -> ${target.projectPath}`,
152
+ });
153
+ }
154
+ if (options.dryRun) {
155
+ return {
156
+ success: true,
157
+ ...resultBase,
158
+ migratedShards: moves.length,
159
+ migratedMemories,
160
+ actions,
161
+ };
162
+ }
163
+ const releaseLock = acquireTursoOperationLock("path-migrate");
164
+ const statePath = swapStatePath();
165
+ const archivedTargets = targetShards.map((shard) => ({
166
+ shardId: shard.id,
167
+ shardIndex: shard.shardIndex,
168
+ originalPath: shard.dbPath,
169
+ archivePath: `${shard.dbPath}.pre-path-migrate-${nonce}.bak`,
170
+ isActive: shard.isActive,
171
+ vectorCount: shard.vectorCount,
172
+ }));
173
+ const state = {
174
+ operation: "path-migrate",
175
+ oldHash,
176
+ newHash,
177
+ moves,
178
+ archivedTargets,
179
+ };
180
+ try {
181
+ // Stage complete, updated copies while originals remain untouched.
182
+ // A gigantic shard's synchronous copy or single UPDATE/count can still delay a heartbeat.
183
+ for (const move of moves) {
184
+ await tursoConnectionManager.closeConnection(move.oldPath);
185
+ if (!existsSync(move.oldPath)) {
186
+ throw new Error(`Source shard file missing: ${move.oldPath}`);
187
+ }
188
+ await removeFile(move.stagedPath);
189
+ copySqliteDatabase(move.oldPath, move.stagedPath);
190
+ const stagedDb = await tursoConnectionManager.getConnection(move.stagedPath);
191
+ await tursoVectorSearch.updateProjectAssociation(stagedDb, move.oldContainerTag, {
192
+ containerTag: target.tag,
193
+ projectPath: target.projectPath,
194
+ projectName: target.projectName,
195
+ displayName: target.displayName,
196
+ gitRepoUrl: target.gitRepoUrl ?? null,
197
+ });
198
+ await stagedDb.run(`UPDATE memories SET
199
+ container_tag = ?, project_path = ?, project_name = ?,
200
+ display_name = ?, git_repo_url = ?
201
+ WHERE container_tag != ?`, [
202
+ target.tag,
203
+ target.projectPath ?? null,
204
+ target.projectName ?? null,
205
+ target.displayName ?? null,
206
+ target.gitRepoUrl ?? null,
207
+ target.tag,
208
+ ]);
209
+ const stagedCount = await tursoVectorSearch.countAllVectors(stagedDb);
210
+ if (stagedCount !== move.vectorCount) {
211
+ throw new Error(`Staged shard count mismatch for ${basename(move.oldPath)}: expected ${move.vectorCount}, got ${stagedCount}`);
212
+ }
213
+ await tursoConnectionManager.closeConnection(move.stagedPath);
214
+ releaseLock.heartbeat();
215
+ }
216
+ writeSwapState(statePath, state);
217
+ releaseLock.heartbeat();
218
+ // Empty targets remain recoverable until the complete swap succeeds.
219
+ for (let index = 0; index < targetShards.length; index++) {
220
+ await tursoShardManager.archiveShard(targetShards[index].id, "pre-path-migrate", archivedTargets[index].archivePath);
221
+ releaseLock.heartbeat();
222
+ }
223
+ for (const move of moves) {
224
+ await tursoConnectionManager.closeConnection(move.oldPath);
225
+ releaseLock.heartbeat();
226
+ await withSqliteFileLockRetry(() => renameSqliteDatabase(move.oldPath, move.backupPath));
227
+ try {
228
+ await withSqliteFileLockRetry(() => renameSqliteDatabase(move.stagedPath, move.newPath));
229
+ }
230
+ catch (error) {
231
+ await withSqliteFileLockRetry(() => renameSqliteDatabase(move.backupPath, move.oldPath));
232
+ throw error;
233
+ }
234
+ releaseLock.heartbeat();
235
+ await tursoShardManager.reassignShardScope(move.shardId, newHash, move.newPath, move.vectorCount, move.isActive);
236
+ actions.push({
237
+ type: "reassign-metadata",
238
+ detail: `shard ${move.shardId} -> ${newHash}#${move.shardIndex}`,
239
+ });
240
+ }
241
+ unlinkSync(statePath);
242
+ releaseLock.heartbeat();
243
+ // Prompt metadata is secondary and must not invalidate a completed,
244
+ // recoverable memory migration.
245
+ if (source.group.projectPath && target.projectPath) {
246
+ try {
247
+ await userPromptManager.updateProjectPath(source.group.projectPath, target.projectPath);
248
+ }
249
+ catch (error) {
250
+ log("Path migration prompt metadata update failed", { error: String(error) });
251
+ }
252
+ }
253
+ log("Path migration completed", {
254
+ oldHash,
255
+ newHash,
256
+ migratedShards: moves.length,
257
+ migratedMemories,
258
+ });
259
+ return {
260
+ success: true,
261
+ ...resultBase,
262
+ dryRun: false,
263
+ migratedShards: moves.length,
264
+ migratedMemories,
265
+ actions,
266
+ };
267
+ }
268
+ catch (error) {
269
+ const ownershipLost = isTursoLockOwnershipLostError(error);
270
+ if (ownershipLost) {
271
+ // A successor may already be writing to the migrated paths. Only fresh
272
+ // ownership at startup may recover any journal that remains.
273
+ log("WARNING: Path migration interrupted after lock ownership lost; leaving recoverable state untouched", { error: String(error), statePath });
274
+ }
275
+ else {
276
+ await this.rollbackSwap(state, statePath);
277
+ }
278
+ return {
279
+ success: false,
280
+ ...resultBase,
281
+ dryRun: false,
282
+ error: ownershipLost
283
+ ? `Path migration interrupted after lock ownership lost and may have completed; state is recoverable. ${String(error)}`
284
+ : error instanceof Error
285
+ ? error.message
286
+ : String(error),
287
+ };
288
+ }
289
+ finally {
290
+ releaseLock();
291
+ }
292
+ }
293
+ async rollbackSwap(state, statePath) {
294
+ let rollbackFailed = false;
295
+ for (const move of [...state.moves].reverse()) {
296
+ try {
297
+ await tursoConnectionManager.closeConnection(move.newPath);
298
+ await tursoConnectionManager.closeConnection(move.stagedPath);
299
+ if (existsSync(move.backupPath)) {
300
+ await removeFile(move.newPath);
301
+ await removeFile(move.oldPath);
302
+ await withSqliteFileLockRetry(() => renameSqliteDatabase(move.backupPath, move.oldPath));
303
+ }
304
+ await removeFile(move.stagedPath);
305
+ if (existsSync(move.oldPath)) {
306
+ await tursoShardManager.reassignShardScope(move.shardId, state.oldHash, move.oldPath, move.vectorCount, move.isActive);
307
+ }
308
+ }
309
+ catch (error) {
310
+ rollbackFailed = true;
311
+ log("Path migration source rollback failed", { move, error: String(error) });
312
+ }
313
+ }
314
+ for (const archived of state.archivedTargets) {
315
+ try {
316
+ if (archived.archivePath && existsSync(archived.archivePath)) {
317
+ await removeFile(archived.originalPath);
318
+ await withSqliteFileLockRetry(() => renameSqliteDatabase(archived.archivePath, archived.originalPath));
319
+ await tursoShardManager.registerExistingShard("project", state.newHash, archived.shardIndex, archived.originalPath, archived.vectorCount, archived.isActive);
320
+ }
321
+ }
322
+ catch (error) {
323
+ rollbackFailed = true;
324
+ log("Path migration target rollback failed", { archived, error: String(error) });
325
+ }
326
+ }
327
+ // Startup reconciliation may have registered a newly renamed shard before
328
+ // recovery ran. Remove only registry rows whose files no longer exist.
329
+ try {
330
+ const staleTargets = await tursoShardManager.getAllShards("project", state.newHash);
331
+ for (const shard of staleTargets) {
332
+ if (!existsSync(shard.dbPath)) {
333
+ await tursoShardManager.deleteShard(shard.id);
334
+ }
335
+ }
336
+ }
337
+ catch (error) {
338
+ rollbackFailed = true;
339
+ log("Path migration stale target cleanup failed", { error: String(error) });
340
+ }
341
+ if (!rollbackFailed && existsSync(statePath)) {
342
+ unlinkSync(statePath);
343
+ }
344
+ else if (rollbackFailed && !existsSync(statePath)) {
345
+ writeSwapState(statePath, state);
346
+ }
347
+ }
348
+ /** Roll back an interrupted staged swap before normal storage access resumes. */
349
+ async recoverInterruptedSwap() {
350
+ const statePath = swapStatePath();
351
+ if (!existsSync(statePath))
352
+ return;
353
+ try {
354
+ const state = JSON.parse(readFileSync(statePath, "utf-8"));
355
+ if (state.operation !== "path-migrate" ||
356
+ !Array.isArray(state.moves) ||
357
+ !Array.isArray(state.archivedTargets)) {
358
+ throw new Error("invalid path-migrate swap state");
359
+ }
360
+ for (const move of state.moves) {
361
+ for (const path of [move.oldPath, move.newPath, move.stagedPath, move.backupPath]) {
362
+ assertRecoveryPathInsideStorage(path);
363
+ }
364
+ }
365
+ for (const archived of state.archivedTargets) {
366
+ assertRecoveryPathInsideStorage(archived.originalPath);
367
+ if (archived.archivePath)
368
+ assertRecoveryPathInsideStorage(archived.archivePath);
369
+ }
370
+ await this.rollbackSwap(state, statePath);
371
+ if (existsSync(statePath)) {
372
+ throw new Error("rollback could not restore every shard");
373
+ }
374
+ log("Recovered interrupted path migration", {
375
+ oldHash: state.oldHash,
376
+ newHash: state.newHash,
377
+ });
378
+ }
379
+ catch (error) {
380
+ throw new Error(`Failed to recover path-migrate swap ${statePath}: ${String(error)}`, {
381
+ cause: error,
382
+ });
383
+ }
384
+ }
385
+ }
386
+ export const shardPathMigrationService = new ShardPathMigrationService();
@@ -0,0 +1,39 @@
1
+ import { type SkillInput, type SkillRecord, type SkillUpdate } from "./types.js";
2
+ type SkillChangeListener = () => void;
3
+ export declare function onSkillsChanged(listener: SkillChangeListener): () => void;
4
+ export declare class SkillsManager {
5
+ private db;
6
+ private dbPath;
7
+ private initPromise;
8
+ constructor();
9
+ reset(): void;
10
+ private initialize;
11
+ private initDatabase;
12
+ private getDb;
13
+ /** Absolute SKILL.md path for OpenCode Skill.Info.path */
14
+ skillPath(id: string): string;
15
+ /** OpenCode-compatible SKILL.md (frontmatter + body). */
16
+ formatMarkdown(skill: SkillRecord): string;
17
+ private writeSkillFile;
18
+ private removeSkillFile;
19
+ list(options?: {
20
+ containerTag?: string | null;
21
+ enabledOnly?: boolean;
22
+ }): Promise<SkillRecord[]>;
23
+ get(id: string): Promise<SkillRecord | null>;
24
+ create(input: SkillInput): Promise<SkillRecord>;
25
+ update(id: string, update: SkillUpdate): Promise<SkillRecord>;
26
+ delete(id: string): Promise<boolean>;
27
+ /** Catalog payload for OpenCode HTTP skills sources (`skills: ["http://host/skills/"]`). */
28
+ toHttpCatalog(): Promise<{
29
+ skills: Array<{
30
+ name: string;
31
+ version: string;
32
+ files: string[];
33
+ }>;
34
+ }>;
35
+ toCatalogMarkdown(id: string): Promise<string | null>;
36
+ }
37
+ export declare const skillsManager: SkillsManager;
38
+ export {};
39
+ //# sourceMappingURL=skills-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skills-manager.d.ts","sourceRoot":"","sources":["../../../src/services/skills/skills-manager.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkB,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAIjG,KAAK,mBAAmB,GAAG,MAAM,IAAI,CAAC;AAItC,wBAAgB,eAAe,CAAC,QAAQ,EAAE,mBAAmB,GAAG,MAAM,IAAI,CAGzE;AA0BD,qBAAa,aAAa;IACxB,OAAO,CAAC,EAAE,CAAwB;IAClC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,WAAW,CAA8B;;IAMjD,KAAK,IAAI,IAAI;YAMC,UAAU;YAMV,YAAY;YAYZ,KAAK;IAgBnB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM;IAI7B,yDAAyD;IACzD,cAAc,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM;YAa5B,cAAc;YAMd,eAAe;IAKvB,IAAI,CAAC,OAAO,CAAC,EAAE;QACnB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC7B,WAAW,CAAC,EAAE,OAAO,CAAC;KACvB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAyBpB,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAM5C,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,CAAC;IA2C/C,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IAuC7D,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU1C,4FAA4F;IACtF,aAAa,IAAI,OAAO,CAAC;QAC7B,MAAM,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,EAAE,CAAA;SAAE,CAAC,CAAC;KACnE,CAAC;IAYI,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAK5D;AAED,eAAO,MAAM,aAAa,eAAsB,CAAC"}
@@ -0,0 +1,231 @@
1
+ import { mkdir, rm, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { tursoConnectionManager } from "../turso/connection-manager.js";
4
+ import { CONFIG } from "../../config.js";
5
+ import { log } from "../logger.js";
6
+ import { isValidSkillId } from "./types.js";
7
+ const SKILLS_DB_NAME = "skills.db";
8
+ const skillChangeListeners = new Set();
9
+ export function onSkillsChanged(listener) {
10
+ skillChangeListeners.add(listener);
11
+ return () => skillChangeListeners.delete(listener);
12
+ }
13
+ function notifySkillsChanged() {
14
+ for (const listener of skillChangeListeners) {
15
+ try {
16
+ listener();
17
+ }
18
+ catch (error) {
19
+ log("skills change listener failed", { error: String(error) });
20
+ }
21
+ }
22
+ }
23
+ function rowToSkill(row) {
24
+ return {
25
+ id: String(row.id),
26
+ name: String(row.name),
27
+ description: String(row.description ?? ""),
28
+ content: String(row.content ?? ""),
29
+ autoinvoke: Number(row.autoinvoke ?? 1) === 1,
30
+ enabled: Number(row.enabled ?? 1) === 1,
31
+ containerTag: row.container_tag == null ? null : String(row.container_tag),
32
+ createdAt: Number(row.created_at),
33
+ updatedAt: Number(row.updated_at),
34
+ };
35
+ }
36
+ export class SkillsManager {
37
+ db = null;
38
+ dbPath;
39
+ initPromise = null;
40
+ constructor() {
41
+ this.dbPath = join(CONFIG.storagePath || "", SKILLS_DB_NAME);
42
+ }
43
+ reset() {
44
+ this.db = null;
45
+ this.initPromise = null;
46
+ this.dbPath = join(CONFIG.storagePath || "", SKILLS_DB_NAME);
47
+ }
48
+ async initialize() {
49
+ if (this.initPromise)
50
+ return this.initPromise;
51
+ this.initPromise = this.initDatabase();
52
+ return this.initPromise;
53
+ }
54
+ async initDatabase() {
55
+ this.dbPath = join(CONFIG.storagePath || "", SKILLS_DB_NAME);
56
+ const db = await tursoConnectionManager.getConnection(this.dbPath);
57
+ const { applySchemaMigrations, SKILLS_MIGRATIONS } = await import("../turso/schema-migrations.js");
58
+ await applySchemaMigrations(db, SKILLS_MIGRATIONS, {
59
+ dbPath: this.dbPath,
60
+ label: "skills",
61
+ });
62
+ this.db = db;
63
+ }
64
+ async getDb() {
65
+ await this.initialize();
66
+ // Connection manager is authoritative: boot migrators may close/replace
67
+ // skills.db underneath a cached TursoDb handle (encryption/engine rewrite).
68
+ if (this.db) {
69
+ const current = await tursoConnectionManager.getConnection(this.dbPath);
70
+ if (current === this.db) {
71
+ return this.db;
72
+ }
73
+ this.reset();
74
+ await this.initialize();
75
+ }
76
+ if (!this.db)
77
+ throw new Error("Skills database not initialized");
78
+ return this.db;
79
+ }
80
+ /** Absolute SKILL.md path for OpenCode Skill.Info.path */
81
+ skillPath(id) {
82
+ return join(this.dbPath.replace(/skills\.db$/, "skills-content"), id, "SKILL.md");
83
+ }
84
+ /** OpenCode-compatible SKILL.md (frontmatter + body). */
85
+ formatMarkdown(skill) {
86
+ return [
87
+ "---",
88
+ `name: ${JSON.stringify(skill.name)}`,
89
+ `description: ${JSON.stringify(skill.description)}`,
90
+ "metadata:",
91
+ ` opencode/autoinvoke: ${skill.autoinvoke ? '"true"' : '"false"'}`,
92
+ "---",
93
+ "",
94
+ skill.content,
95
+ ].join("\n");
96
+ }
97
+ async writeSkillFile(skill) {
98
+ const filePath = this.skillPath(skill.id);
99
+ await mkdir(dirname(filePath), { recursive: true });
100
+ await writeFile(filePath, this.formatMarkdown(skill), "utf8");
101
+ }
102
+ async removeSkillFile(id) {
103
+ const dir = dirname(this.skillPath(id));
104
+ await rm(dir, { recursive: true, force: true });
105
+ }
106
+ async list(options) {
107
+ const db = await this.getDb();
108
+ const clauses = [];
109
+ const args = [];
110
+ if (options?.enabledOnly) {
111
+ clauses.push(`enabled = 1`);
112
+ }
113
+ if (options?.containerTag !== undefined) {
114
+ if (options.containerTag === null) {
115
+ clauses.push(`container_tag IS NULL`);
116
+ }
117
+ else {
118
+ clauses.push(`(container_tag IS NULL OR container_tag = ?)`);
119
+ args.push(options.containerTag);
120
+ }
121
+ }
122
+ const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
123
+ const rows = await db.all(`SELECT * FROM skills ${where} ORDER BY updated_at DESC, id ASC`, args);
124
+ return rows.map(rowToSkill);
125
+ }
126
+ async get(id) {
127
+ const db = await this.getDb();
128
+ const row = await db.get(`SELECT * FROM skills WHERE id = ?`, [id]);
129
+ return row ? rowToSkill(row) : null;
130
+ }
131
+ async create(input) {
132
+ const id = input.id.trim();
133
+ if (!isValidSkillId(id)) {
134
+ throw new Error("Invalid skill id: use lowercase kebab-case (a-z, 0-9, single hyphens), 1–64 characters");
135
+ }
136
+ const name = input.name.trim();
137
+ if (!name)
138
+ throw new Error("Skill name is required");
139
+ const content = input.content;
140
+ if (typeof content !== "string" || !content.trim()) {
141
+ throw new Error("Skill content is required");
142
+ }
143
+ const existing = await this.get(id);
144
+ if (existing)
145
+ throw new Error(`Skill already exists: ${id}`);
146
+ const now = Date.now();
147
+ const db = await this.getDb();
148
+ await db.run(`INSERT INTO skills (
149
+ id, name, description, content, autoinvoke, enabled, container_tag, created_at, updated_at
150
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
151
+ id,
152
+ name,
153
+ (input.description ?? "").trim(),
154
+ content,
155
+ input.autoinvoke === false ? 0 : 1,
156
+ input.enabled === false ? 0 : 1,
157
+ input.containerTag ?? null,
158
+ now,
159
+ now,
160
+ ]);
161
+ const created = await this.get(id);
162
+ if (!created)
163
+ throw new Error("Failed to create skill");
164
+ if (created.enabled)
165
+ await this.writeSkillFile(created);
166
+ notifySkillsChanged();
167
+ return created;
168
+ }
169
+ async update(id, update) {
170
+ const existing = await this.get(id);
171
+ if (!existing)
172
+ throw new Error(`Skill not found: ${id}`);
173
+ const name = update.name !== undefined ? update.name.trim() : existing.name;
174
+ if (!name)
175
+ throw new Error("Skill name is required");
176
+ const content = update.content !== undefined ? update.content : existing.content;
177
+ if (typeof content !== "string" || !content.trim()) {
178
+ throw new Error("Skill content is required");
179
+ }
180
+ const description = update.description !== undefined ? update.description.trim() : existing.description;
181
+ const autoinvoke = update.autoinvoke !== undefined ? update.autoinvoke : existing.autoinvoke;
182
+ const enabled = update.enabled !== undefined ? update.enabled : existing.enabled;
183
+ const containerTag = update.containerTag !== undefined ? update.containerTag : existing.containerTag;
184
+ const now = Date.now();
185
+ const db = await this.getDb();
186
+ await db.run(`UPDATE skills SET
187
+ name = ?, description = ?, content = ?, autoinvoke = ?, enabled = ?,
188
+ container_tag = ?, updated_at = ?
189
+ WHERE id = ?`, [name, description, content, autoinvoke ? 1 : 0, enabled ? 1 : 0, containerTag, now, id]);
190
+ const updated = await this.get(id);
191
+ if (!updated)
192
+ throw new Error("Failed to update skill");
193
+ if (updated.enabled) {
194
+ await this.writeSkillFile(updated);
195
+ }
196
+ else {
197
+ await this.removeSkillFile(id);
198
+ }
199
+ notifySkillsChanged();
200
+ return updated;
201
+ }
202
+ async delete(id) {
203
+ const existing = await this.get(id);
204
+ if (!existing)
205
+ return false;
206
+ const db = await this.getDb();
207
+ await db.run(`DELETE FROM skills WHERE id = ?`, [id]);
208
+ await this.removeSkillFile(id);
209
+ notifySkillsChanged();
210
+ return true;
211
+ }
212
+ /** Catalog payload for OpenCode HTTP skills sources (`skills: ["http://host/skills/"]`). */
213
+ async toHttpCatalog() {
214
+ const enabled = await this.list({ enabledOnly: true });
215
+ return {
216
+ skills: enabled.map((skill) => ({
217
+ name: skill.id,
218
+ version: String(skill.updatedAt),
219
+ // OpenCode fetches `{base}/{name}/{file}` — named .md form → skill id = name.
220
+ files: [`${skill.id}.md`],
221
+ })),
222
+ };
223
+ }
224
+ async toCatalogMarkdown(id) {
225
+ const skill = await this.get(id);
226
+ if (!skill || !skill.enabled)
227
+ return null;
228
+ return this.formatMarkdown(skill);
229
+ }
230
+ }
231
+ export const skillsManager = new SkillsManager();