trellis 3.1.35 → 3.2.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 (287) hide show
  1. package/CHANGELOG.md +23 -5
  2. package/README.md +63 -156
  3. package/bin/trellis.mjs +2 -75
  4. package/dist/{better-sqlite-backend-ahx5p0br.js → better-sqlite-backend-2P4F6AOJ.js} +91 -29
  5. package/dist/boot-middleware-MHLHFCUC.js +9 -0
  6. package/dist/browser/index.d.ts +18 -0
  7. package/dist/browser/index.d.ts.map +1 -0
  8. package/dist/browser/index.js +95 -0
  9. package/dist/{index-53f3b8p8.js → chunk-2W3MHTMG.js} +552 -213
  10. package/dist/chunk-44FFQKQX.js +142 -0
  11. package/dist/chunk-4HYPLFJD.js +150 -0
  12. package/dist/chunk-4XIVMVHC.js +361 -0
  13. package/dist/{index-yp88he8n.js → chunk-6CTA6MCE.js} +88 -64
  14. package/dist/chunk-6GEZ6DN5.js +394 -0
  15. package/dist/chunk-7ZFRVCUE.js +211 -0
  16. package/dist/chunk-CAG4FULI.js +121 -0
  17. package/dist/chunk-FF36CQHZ.js +61 -0
  18. package/dist/{index-h32txmxe.js → chunk-FKQO5A3H.js} +6 -13
  19. package/dist/{index-nq520y6k.js → chunk-FWRS4CSC.js} +46 -32
  20. package/dist/chunk-GFZCJ4EH.js +108 -0
  21. package/dist/chunk-GLM4HGN4.js +55 -0
  22. package/dist/{index-4cdr7x2x.js → chunk-GU374KWZ.js} +182 -111
  23. package/dist/chunk-H6JB3PZ3.js +45 -0
  24. package/dist/chunk-IZX2PLIB.js +1240 -0
  25. package/dist/chunk-J2TXUFCZ.js +289 -0
  26. package/dist/chunk-J3WYZO3Q.js +211 -0
  27. package/dist/{index-xzym9w0m.js → chunk-JA7AIHRK.js} +12 -7
  28. package/dist/chunk-JHHEXEDM.js +162 -0
  29. package/dist/chunk-JUEMDWLU.js +233 -0
  30. package/dist/chunk-KFQGP6VL.js +33 -0
  31. package/dist/chunk-KIJITUZB.js +419 -0
  32. package/dist/{index-4wxa8xz4.js → chunk-KQ4A2D2P.js} +162 -23
  33. package/dist/chunk-KSU2GW22.js +958 -0
  34. package/dist/{index-rv1p47gp.js → chunk-L5N5PR2S.js} +3015 -2480
  35. package/dist/{index-h9e2efx4.js → chunk-LNUIGRDZ.js} +71 -55
  36. package/dist/{index-skhn0agf.js → chunk-MLC5BUYO.js} +19 -20
  37. package/dist/chunk-MPXUVGT3.js +104 -0
  38. package/dist/chunk-N6MYZT4O.js +68 -0
  39. package/dist/chunk-O2AV5WMN.js +48 -0
  40. package/dist/chunk-PZ4XYZ4J.js +143 -0
  41. package/dist/chunk-QB5ISE47.js +419 -0
  42. package/dist/chunk-RSWUFTO2.js +857 -0
  43. package/dist/chunk-S3XLFZ27.js +1095 -0
  44. package/dist/{index-w5wccer3.js → chunk-S6GBJ2ZB.js} +28 -12
  45. package/dist/{index-7pjz3tsy.js → chunk-SGMDTWJJ.js} +57 -15
  46. package/dist/chunk-SPSPV5BC.js +390 -0
  47. package/dist/chunk-TCKXSOBP.js +123 -0
  48. package/dist/chunk-UBGUDMUV.js +59 -0
  49. package/dist/{index-wt8rz4gn.js → chunk-UQISRW6T.js} +97 -26
  50. package/dist/chunk-USEINYUL.js +12 -0
  51. package/dist/{index-bmyt7k8n.js → chunk-UZRUP7QW.js} +12 -4
  52. package/dist/{index-xhcp6xrn.js → chunk-VBYUTRXX.js} +695 -514
  53. package/dist/{index-vkpkfwhq.js → chunk-VDAKEOML.js} +234 -194
  54. package/dist/chunk-WXSWA3MV.js +0 -0
  55. package/dist/{index-n9f2qyh5.js → chunk-X5FLTRUB.js} +55 -33
  56. package/dist/{index-h7zxhhhh.js → chunk-XMQ7G77X.js} +46 -38
  57. package/dist/{index-w7ng765c.js → chunk-YCM7ZYEZ.js} +102 -49
  58. package/dist/cli/deploy-cli.d.ts +18 -0
  59. package/dist/cli/deploy-cli.d.ts.map +1 -0
  60. package/dist/cli/errors.d.ts +6 -0
  61. package/dist/cli/errors.d.ts.map +1 -0
  62. package/dist/cli/examples.d.ts +23 -0
  63. package/dist/cli/examples.d.ts.map +1 -0
  64. package/dist/cli/index.d.ts +1 -1
  65. package/dist/cli/index.d.ts.map +1 -1
  66. package/dist/cli/index.js +2426 -6225
  67. package/dist/client/index.browser.d.ts +29 -0
  68. package/dist/client/index.browser.d.ts.map +1 -0
  69. package/dist/client/index.browser.js +64 -0
  70. package/dist/client/index.d.ts +6 -1
  71. package/dist/client/index.d.ts.map +1 -1
  72. package/dist/client/index.js +41 -21
  73. package/dist/client/live.d.ts +67 -0
  74. package/dist/client/live.d.ts.map +1 -0
  75. package/dist/client/reactive.d.ts +31 -0
  76. package/dist/client/reactive.d.ts.map +1 -0
  77. package/dist/client/sdk.browser.d.ts +104 -0
  78. package/dist/client/sdk.browser.d.ts.map +1 -0
  79. package/dist/client/sdk.browser.js +9 -0
  80. package/dist/client/sdk.d.ts +26 -2
  81. package/dist/client/sdk.d.ts.map +1 -1
  82. package/dist/client/sdk.js +9 -0
  83. package/dist/client/vcs-client.d.ts +129 -0
  84. package/dist/client/vcs-client.d.ts.map +1 -0
  85. package/dist/cms/index.js +171 -163
  86. package/dist/{config-8hczw0rs.js → config-PFTP67TR.js} +8 -9
  87. package/dist/core/computation/index.d.ts +5 -0
  88. package/dist/core/computation/index.d.ts.map +1 -0
  89. package/dist/core/computation/rollup.d.ts +18 -0
  90. package/dist/core/computation/rollup.d.ts.map +1 -0
  91. package/dist/core/index.d.ts +5 -0
  92. package/dist/core/index.d.ts.map +1 -1
  93. package/dist/core/index.js +171 -104
  94. package/dist/core/kernel/boot-middleware.d.ts +10 -0
  95. package/dist/core/kernel/boot-middleware.d.ts.map +1 -0
  96. package/dist/core/kernel/logic-middleware.d.ts +7 -1
  97. package/dist/core/kernel/logic-middleware.d.ts.map +1 -1
  98. package/dist/core/kernel/trellis-kernel.d.ts.map +1 -1
  99. package/dist/core/ontology/types.d.ts +5 -0
  100. package/dist/core/ontology/types.d.ts.map +1 -1
  101. package/dist/core/persist/better-sqlite-backend.d.ts +9 -2
  102. package/dist/core/persist/better-sqlite-backend.d.ts.map +1 -1
  103. package/dist/core/persist/factory.d.ts +6 -7
  104. package/dist/core/persist/factory.d.ts.map +1 -1
  105. package/dist/core/persist/factory.js +2 -3
  106. package/dist/core/persist/sqljs-backend.js +2 -3
  107. package/dist/db/index.d.ts +4 -1
  108. package/dist/db/index.d.ts.map +1 -1
  109. package/dist/db/index.js +67 -54
  110. package/dist/db/inspector.js +11 -19
  111. package/dist/db/trellis.css +1 -1
  112. package/dist/decisions/index.js +9 -10
  113. package/dist/deploy-LQ7GUGJ5.js +9 -0
  114. package/dist/deploy-YNVG5E4E.js +9 -0
  115. package/dist/deploy-cli-24BCHAXY.js +67 -0
  116. package/dist/deploy-cli-C35HTITO.js +67 -0
  117. package/dist/embeddings/auto-embed.d.ts +2 -2
  118. package/dist/embeddings/auto-embed.d.ts.map +1 -1
  119. package/dist/embeddings/index.js +20 -22
  120. package/dist/embeddings/search.d.ts +2 -1
  121. package/dist/embeddings/search.d.ts.map +1 -1
  122. package/dist/embeddings/store.d.ts +25 -4
  123. package/dist/embeddings/store.d.ts.map +1 -1
  124. package/dist/engine.d.ts +59 -19
  125. package/dist/engine.d.ts.map +1 -1
  126. package/dist/import-UZEKXU3B.js +10 -0
  127. package/dist/index.js +102 -93
  128. package/dist/launch-explorer-HZ4ZJA4X.js +95 -0
  129. package/dist/links/index.js +24 -26
  130. package/dist/mcp/server.d.ts.map +1 -1
  131. package/dist/plugins/agent-memory/index.js +316 -0
  132. package/dist/plugins/idea-garden/index.js +165 -0
  133. package/dist/plugins/plan-approval/index.js +579 -0
  134. package/dist/plugins/proactive-watcher/index.js +194 -0
  135. package/dist/{index-2r4jxwnb.js → query-XYLTJYSA.js} +14 -15
  136. package/dist/react/index.js +39 -70
  137. package/dist/react/realtime.js +11 -0
  138. package/dist/react/schema-hooks.js +87 -0
  139. package/dist/realtime/broadcast-channel-transport.d.ts +43 -0
  140. package/dist/realtime/broadcast-channel-transport.d.ts.map +1 -0
  141. package/dist/realtime/durable-object-relay-transport.d.ts +96 -0
  142. package/dist/realtime/durable-object-relay-transport.d.ts.map +1 -0
  143. package/dist/realtime/index.d.ts +44 -0
  144. package/dist/realtime/index.d.ts.map +1 -0
  145. package/dist/realtime/index.js +40 -0
  146. package/dist/realtime/memory-hub.d.ts +32 -0
  147. package/dist/realtime/memory-hub.d.ts.map +1 -0
  148. package/dist/realtime/persistent-channel.d.ts +105 -0
  149. package/dist/realtime/persistent-channel.d.ts.map +1 -0
  150. package/dist/realtime/presence.d.ts +73 -0
  151. package/dist/realtime/presence.d.ts.map +1 -0
  152. package/dist/realtime/relay-persistence.d.ts +37 -0
  153. package/dist/realtime/relay-persistence.d.ts.map +1 -0
  154. package/dist/realtime/relay-persistence.js +107 -0
  155. package/dist/realtime/relay-server.d.ts +103 -0
  156. package/dist/realtime/relay-server.d.ts.map +1 -0
  157. package/dist/realtime/room.d.ts +98 -0
  158. package/dist/realtime/room.d.ts.map +1 -0
  159. package/dist/realtime/text.d.ts +73 -0
  160. package/dist/realtime/text.d.ts.map +1 -0
  161. package/dist/realtime/types.d.ts +89 -0
  162. package/dist/realtime/types.d.ts.map +1 -0
  163. package/dist/realtime/websocket-relay-transport.d.ts +28 -0
  164. package/dist/realtime/websocket-relay-transport.d.ts.map +1 -0
  165. package/dist/realtime.bundle.js +1100 -0
  166. package/dist/{remote-manager-xvbg4230.js → remote-manager-ODE3T2KR.js} +25 -15
  167. package/dist/scaffold/seed.d.ts.map +1 -1
  168. package/dist/scaffold/write.d.ts +1 -1
  169. package/dist/scaffold/write.d.ts.map +1 -1
  170. package/dist/schema/define.d.ts +137 -0
  171. package/dist/schema/define.d.ts.map +1 -0
  172. package/dist/schema/entity-projection.d.ts +34 -0
  173. package/dist/schema/entity-projection.d.ts.map +1 -0
  174. package/dist/schema/eql.d.ts +46 -0
  175. package/dist/schema/eql.d.ts.map +1 -0
  176. package/dist/schema/index.d.ts +21 -0
  177. package/dist/schema/index.d.ts.map +1 -0
  178. package/dist/schema/index.js +46 -0
  179. package/dist/schema/kernel-resolve.d.ts +21 -0
  180. package/dist/schema/kernel-resolve.d.ts.map +1 -0
  181. package/dist/schema/mutations.d.ts +20 -0
  182. package/dist/schema/mutations.d.ts.map +1 -0
  183. package/dist/schema/resolve.d.ts +21 -0
  184. package/dist/schema/resolve.d.ts.map +1 -0
  185. package/dist/server/deploy-meta.d.ts +25 -0
  186. package/dist/server/deploy-meta.d.ts.map +1 -0
  187. package/dist/server/deploy.d.ts +7 -2
  188. package/dist/server/deploy.d.ts.map +1 -1
  189. package/dist/server/index.d.ts +7 -2
  190. package/dist/server/index.d.ts.map +1 -1
  191. package/dist/server/index.js +100 -58
  192. package/dist/server/node-adapter.js +5 -104
  193. package/dist/server/realtime.d.ts +14 -3
  194. package/dist/server/realtime.d.ts.map +1 -1
  195. package/dist/server/server.d.ts +8 -16
  196. package/dist/server/server.d.ts.map +1 -1
  197. package/dist/server/sprites.d.ts +18 -1
  198. package/dist/server/sprites.d.ts.map +1 -1
  199. package/dist/server/tenancy.d.ts +4 -0
  200. package/dist/server/tenancy.d.ts.map +1 -1
  201. package/dist/server/usage-meter.d.ts +53 -0
  202. package/dist/server/usage-meter.d.ts.map +1 -0
  203. package/dist/server-MB3OPSPI.js +18 -0
  204. package/dist/server-ZVWGLLRF.js +18 -0
  205. package/dist/sprites-KQGTGM6W.js +27 -0
  206. package/dist/{sprites-vc4qbrp1.js → sprites-RU3E4XQN.js} +6 -7
  207. package/dist/svelte/index.d.ts +17 -0
  208. package/dist/svelte/index.d.ts.map +1 -0
  209. package/dist/svelte/index.js +51 -0
  210. package/dist/svelte/schema-hooks.d.ts +45 -0
  211. package/dist/svelte/schema-hooks.d.ts.map +1 -0
  212. package/dist/svelte/schema-hooks.js +71 -0
  213. package/dist/svelte/stores.d.ts +78 -0
  214. package/dist/svelte/stores.d.ts.map +1 -0
  215. package/dist/sync/http-transport.d.ts +3 -3
  216. package/dist/sync/http-transport.d.ts.map +1 -1
  217. package/dist/sync/index.d.ts +15 -1
  218. package/dist/sync/index.d.ts.map +1 -1
  219. package/dist/sync/index.js +617 -0
  220. package/dist/sync/memory-room.d.ts +37 -0
  221. package/dist/sync/memory-room.d.ts.map +1 -0
  222. package/dist/sync/memory-transport.d.ts +3 -3
  223. package/dist/sync/memory-transport.d.ts.map +1 -1
  224. package/dist/sync/partykit-room.d.ts +40 -0
  225. package/dist/sync/partykit-room.d.ts.map +1 -0
  226. package/dist/sync/partykit-transport.d.ts +84 -0
  227. package/dist/sync/partykit-transport.d.ts.map +1 -0
  228. package/dist/sync/room-core.d.ts +53 -0
  229. package/dist/sync/room-core.d.ts.map +1 -0
  230. package/dist/sync/sync-engine.d.ts +40 -2
  231. package/dist/sync/sync-engine.d.ts.map +1 -1
  232. package/dist/sync/sync-room-server.d.ts +39 -0
  233. package/dist/sync/sync-room-server.d.ts.map +1 -0
  234. package/dist/sync/types.d.ts +70 -3
  235. package/dist/sync/types.d.ts.map +1 -1
  236. package/dist/sync/vcs-sync-peer.d.ts +63 -0
  237. package/dist/sync/vcs-sync-peer.d.ts.map +1 -0
  238. package/dist/sync/ws-transport.d.ts +2 -2
  239. package/dist/sync/ws-transport.d.ts.map +1 -1
  240. package/dist/tenancy-NBLLGCNJ.js +14 -0
  241. package/dist/tenancy-POMWQP6M.js +16 -0
  242. package/dist/ui/client.html +355 -67
  243. package/dist/ui/launch-explorer.d.ts +22 -0
  244. package/dist/ui/launch-explorer.d.ts.map +1 -0
  245. package/dist/ui/server.d.ts +1 -1
  246. package/dist/ui/server.d.ts.map +1 -1
  247. package/dist/vcs/blob-store.d.ts.map +1 -1
  248. package/dist/vcs/idb-op-log.d.ts +67 -0
  249. package/dist/vcs/idb-op-log.d.ts.map +1 -0
  250. package/dist/vcs/index.d.ts +1 -0
  251. package/dist/vcs/index.d.ts.map +1 -1
  252. package/dist/vcs/index.js +81 -72
  253. package/dist/vcs/issue.d.ts +22 -5
  254. package/dist/vcs/issue.d.ts.map +1 -1
  255. package/dist/vcs/lane-materialize.d.ts +5 -0
  256. package/dist/vcs/lane-materialize.d.ts.map +1 -1
  257. package/dist/vcs/op-log.d.ts +28 -2
  258. package/dist/vcs/op-log.d.ts.map +1 -1
  259. package/dist/vcs/ops.d.ts +10 -0
  260. package/dist/vcs/ops.d.ts.map +1 -1
  261. package/dist/vcs/types.d.ts +2 -0
  262. package/dist/vcs/types.d.ts.map +1 -1
  263. package/dist/{vm-config-6xhsj6b3.js → vm-config-JI4OXKDQ.js} +9 -10
  264. package/dist/vue/hooks.d.ts +64 -0
  265. package/dist/vue/hooks.d.ts.map +1 -0
  266. package/dist/vue/index.d.ts +19 -0
  267. package/dist/vue/index.d.ts.map +1 -0
  268. package/dist/vue/index.js +59 -0
  269. package/dist/vue/schema-hooks.d.ts +41 -0
  270. package/dist/vue/schema-hooks.d.ts.map +1 -0
  271. package/dist/vue/schema-hooks.js +64 -0
  272. package/package.json +130 -17
  273. package/dist/deploy-999q207z.js +0 -10
  274. package/dist/engine-y0724kjq.js +0 -8
  275. package/dist/import-s2b8e0ft.js +0 -11
  276. package/dist/index-a76rekgs.js +0 -67
  277. package/dist/index-c9h37r6h.js +0 -1
  278. package/dist/index-hr9qvv77.js +0 -860
  279. package/dist/index-k5b0xskw.js +0 -1
  280. package/dist/index-nzb3am4f.js +0 -80
  281. package/dist/index-wncptktd.js +0 -292
  282. package/dist/index-y6a4kj0p.js +0 -43
  283. package/dist/index-yhwjgfvj.js +0 -342
  284. package/dist/sdk-bepky0xs.js +0 -16
  285. package/dist/server-szdjx0nt.js +0 -13
  286. package/dist/sqlite-backend-0vsmc6qj.js +0 -8
  287. package/dist/tenancy-pjm32b4v.js +0 -14
@@ -1,860 +0,0 @@
1
- // @bun
2
- import {
3
- __esm,
4
- __export,
5
- __require
6
- } from "./index-a76rekgs.js";
7
-
8
- // src/embeddings/types.ts
9
- var DEFAULT_MODEL_CONFIG;
10
- var init_types = __esm(() => {
11
- DEFAULT_MODEL_CONFIG = {
12
- modelName: "Xenova/all-MiniLM-L6-v2",
13
- dimension: 384
14
- };
15
- });
16
-
17
- // src/embeddings/model.ts
18
- async function importTransformers() {
19
- try {
20
- return await import("@huggingface/transformers");
21
- } catch {
22
- try {
23
- return await import("@xenova/transformers");
24
- } catch {
25
- throw new Error("No transformers library found. Install @huggingface/transformers (recommended) or @xenova/transformers.");
26
- }
27
- }
28
- }
29
- async function loadModel(config = DEFAULT_MODEL_CONFIG) {
30
- if (pipeline)
31
- return pipeline;
32
- if (!loadPromise) {
33
- loadPromise = (async () => {
34
- const { pipeline: createPipeline } = await importTransformers();
35
- const opts = {};
36
- if (config.cacheDir) {
37
- opts.cache_dir = config.cacheDir;
38
- }
39
- pipeline = await createPipeline("feature-extraction", config.modelName, opts);
40
- return pipeline;
41
- })();
42
- }
43
- return loadPromise;
44
- }
45
- async function embed(text, config = DEFAULT_MODEL_CONFIG) {
46
- const pipe = await loadModel(config);
47
- const output = await pipe(text, { pooling: "mean", normalize: true });
48
- return new Float32Array(output.data);
49
- }
50
- async function embedBatch(texts, config = DEFAULT_MODEL_CONFIG) {
51
- if (texts.length === 0)
52
- return [];
53
- const pipe = await loadModel(config);
54
- const results = [];
55
- const batchSize = 32;
56
- for (let i = 0;i < texts.length; i += batchSize) {
57
- const batch = texts.slice(i, i + batchSize);
58
- for (const text of batch) {
59
- const output = await pipe(text, { pooling: "mean", normalize: true });
60
- results.push(new Float32Array(output.data));
61
- }
62
- }
63
- return results;
64
- }
65
- function resetModel() {
66
- pipeline = null;
67
- loadPromise = null;
68
- }
69
- var pipeline = null, loadPromise = null;
70
- var init_model = __esm(() => {
71
- init_types();
72
- });
73
-
74
- // src/embeddings/store.ts
75
- function loadDatabaseCtor() {
76
- if (_DatabaseCtor)
77
- return _DatabaseCtor;
78
- try {
79
- const { createRequire } = __require("module");
80
- const requireCJS = createRequire(import.meta.url);
81
- _DatabaseCtor = requireCJS("bun:sqlite").Database;
82
- return _DatabaseCtor;
83
- } catch {
84
- throw new Error("EmbeddingStore requires the Bun runtime (built-in `bun:sqlite`). " + "It is not available under Node/WebContainer.");
85
- }
86
- }
87
-
88
- class VectorStore {
89
- db;
90
- constructor(dbPath) {
91
- const DatabaseCtor = loadDatabaseCtor();
92
- this.db = new DatabaseCtor(dbPath);
93
- this.db.exec("PRAGMA journal_mode=WAL;");
94
- this.db.exec("PRAGMA foreign_keys=ON;");
95
- this.db.exec(SCHEMA_SQL);
96
- }
97
- upsert(record) {
98
- const insertChunk = this.db.prepare(`
99
- INSERT OR REPLACE INTO chunks (id, entity_id, content, chunk_type, file_path, updated_at)
100
- VALUES ($id, $entityId, $content, $chunkType, $filePath, $updatedAt)
101
- `);
102
- const insertVector = this.db.prepare(`
103
- INSERT OR REPLACE INTO vectors (id, embedding)
104
- VALUES ($id, $embedding)
105
- `);
106
- const embeddingBlob = Buffer.from(record.embedding.buffer);
107
- this.db.transaction(() => {
108
- insertChunk.run({
109
- $id: record.id,
110
- $entityId: record.entityId,
111
- $content: record.content,
112
- $chunkType: record.chunkType,
113
- $filePath: record.filePath ?? null,
114
- $updatedAt: record.updatedAt
115
- });
116
- insertVector.run({
117
- $id: record.id,
118
- $embedding: embeddingBlob
119
- });
120
- })();
121
- }
122
- upsertBatch(records) {
123
- if (records.length === 0)
124
- return;
125
- const insertChunk = this.db.prepare(`
126
- INSERT OR REPLACE INTO chunks (id, entity_id, content, chunk_type, file_path, updated_at)
127
- VALUES ($id, $entityId, $content, $chunkType, $filePath, $updatedAt)
128
- `);
129
- const insertVector = this.db.prepare(`
130
- INSERT OR REPLACE INTO vectors (id, embedding)
131
- VALUES ($id, $embedding)
132
- `);
133
- this.db.transaction(() => {
134
- for (const record of records) {
135
- const embeddingBlob = Buffer.from(record.embedding.buffer);
136
- insertChunk.run({
137
- $id: record.id,
138
- $entityId: record.entityId,
139
- $content: record.content,
140
- $chunkType: record.chunkType,
141
- $filePath: record.filePath ?? null,
142
- $updatedAt: record.updatedAt
143
- });
144
- insertVector.run({
145
- $id: record.id,
146
- $embedding: embeddingBlob
147
- });
148
- }
149
- })();
150
- }
151
- delete(id) {
152
- this.db.prepare("DELETE FROM vectors WHERE id = ?").run(id);
153
- this.db.prepare("DELETE FROM chunks WHERE id = ?").run(id);
154
- }
155
- deleteByEntity(entityId) {
156
- const ids = this.db.prepare("SELECT id FROM chunks WHERE entity_id = ?").all(entityId);
157
- if (ids.length === 0)
158
- return;
159
- this.db.transaction(() => {
160
- for (const { id } of ids) {
161
- this.db.prepare("DELETE FROM vectors WHERE id = ?").run(id);
162
- this.db.prepare("DELETE FROM chunks WHERE id = ?").run(id);
163
- }
164
- })();
165
- }
166
- deleteByFile(filePath) {
167
- const ids = this.db.prepare("SELECT id FROM chunks WHERE file_path = ?").all(filePath);
168
- if (ids.length === 0)
169
- return;
170
- this.db.transaction(() => {
171
- for (const { id } of ids) {
172
- this.db.prepare("DELETE FROM vectors WHERE id = ?").run(id);
173
- this.db.prepare("DELETE FROM chunks WHERE id = ?").run(id);
174
- }
175
- })();
176
- }
177
- getChunk(id) {
178
- const row = this.db.prepare("SELECT * FROM chunks WHERE id = ?").get(id);
179
- if (!row)
180
- return null;
181
- return rowToChunkMeta(row);
182
- }
183
- search(queryVector, opts = {}) {
184
- const limit = opts.limit ?? 10;
185
- const minScore = opts.minScore ?? 0;
186
- const conditions = [];
187
- const params = {};
188
- if (opts.types && opts.types.length > 0) {
189
- const placeholders = opts.types.map((_, i) => `$type${i}`).join(", ");
190
- conditions.push(`c.chunk_type IN (${placeholders})`);
191
- opts.types.forEach((t, i) => {
192
- params[`$type${i}`] = t;
193
- });
194
- }
195
- if (opts.filePrefix) {
196
- conditions.push("c.file_path LIKE $filePrefix");
197
- params.$filePrefix = `${opts.filePrefix}%`;
198
- }
199
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
200
- const sql = `
201
- SELECT c.id, c.entity_id, c.content, c.chunk_type, c.file_path, c.updated_at,
202
- v.embedding
203
- FROM chunks c
204
- JOIN vectors v ON c.id = v.id
205
- ${where}
206
- `;
207
- const rows = this.db.prepare(sql).all(params);
208
- const scored = [];
209
- for (const row of rows) {
210
- const storedVec = new Float32Array(row.embedding.buffer, row.embedding.byteOffset, row.embedding.byteLength / 4);
211
- const score = cosineSimilarity(queryVector, storedVec);
212
- if (score >= minScore) {
213
- scored.push({
214
- chunk: rowToChunkMeta(row),
215
- score
216
- });
217
- }
218
- }
219
- scored.sort((a, b) => b.score - a.score);
220
- return scored.slice(0, limit);
221
- }
222
- count() {
223
- const row = this.db.prepare("SELECT COUNT(*) as cnt FROM chunks").get();
224
- return row?.cnt ?? 0;
225
- }
226
- countByType() {
227
- const rows = this.db.prepare("SELECT chunk_type, COUNT(*) as cnt FROM chunks GROUP BY chunk_type").all();
228
- const result = {};
229
- for (const row of rows) {
230
- result[row.chunk_type] = row.cnt;
231
- }
232
- return result;
233
- }
234
- clear() {
235
- this.db.exec("DELETE FROM vectors");
236
- this.db.exec("DELETE FROM chunks");
237
- }
238
- close() {
239
- this.db.close();
240
- }
241
- }
242
- function rowToChunkMeta(row) {
243
- return {
244
- id: row.id,
245
- entityId: row.entity_id,
246
- content: row.content,
247
- chunkType: row.chunk_type,
248
- filePath: row.file_path ?? undefined,
249
- updatedAt: row.updated_at
250
- };
251
- }
252
- function cosineSimilarity(a, b) {
253
- if (a.length !== b.length)
254
- return 0;
255
- let dot = 0;
256
- let normA = 0;
257
- let normB = 0;
258
- for (let i = 0;i < a.length; i++) {
259
- dot += a[i] * b[i];
260
- normA += a[i] * a[i];
261
- normB += b[i] * b[i];
262
- }
263
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
264
- return denom === 0 ? 0 : dot / denom;
265
- }
266
- var _DatabaseCtor = null, SCHEMA_SQL = `
267
- CREATE TABLE IF NOT EXISTS chunks (
268
- id TEXT PRIMARY KEY,
269
- entity_id TEXT NOT NULL,
270
- content TEXT NOT NULL,
271
- chunk_type TEXT NOT NULL,
272
- file_path TEXT,
273
- updated_at TEXT NOT NULL
274
- );
275
-
276
- CREATE TABLE IF NOT EXISTS vectors (
277
- id TEXT PRIMARY KEY,
278
- embedding BLOB NOT NULL,
279
- FOREIGN KEY (id) REFERENCES chunks(id) ON DELETE CASCADE
280
- );
281
-
282
- CREATE INDEX IF NOT EXISTS idx_chunks_entity ON chunks(entity_id);
283
- CREATE INDEX IF NOT EXISTS idx_chunks_type ON chunks(chunk_type);
284
- CREATE INDEX IF NOT EXISTS idx_chunks_file ON chunks(file_path);
285
- `;
286
- var init_store = () => {};
287
-
288
- // src/embeddings/chunker.ts
289
- function chunkIssue(issue) {
290
- const now = new Date().toISOString();
291
- const chunks = [];
292
- if (issue.title) {
293
- chunks.push({
294
- id: `issue:${issue.id}:title`,
295
- entityId: `issue:${issue.id}`,
296
- content: issue.title,
297
- chunkType: "issue_title",
298
- updatedAt: now
299
- });
300
- }
301
- if (issue.description) {
302
- chunks.push({
303
- id: `issue:${issue.id}:desc`,
304
- entityId: `issue:${issue.id}`,
305
- content: issue.description,
306
- chunkType: "issue_desc",
307
- updatedAt: now
308
- });
309
- }
310
- return chunks;
311
- }
312
- function chunkDecision(decision) {
313
- const parts = [];
314
- parts.push(`Decision ${decision.id}: ${decision.toolName}`);
315
- if (decision.rationale)
316
- parts.push(`Rationale: ${decision.rationale}`);
317
- if (decision.context)
318
- parts.push(`Context: ${decision.context}`);
319
- if (decision.outputSummary)
320
- parts.push(`Output: ${decision.outputSummary}`);
321
- const content = parts.join(`
322
- `);
323
- if (!content.trim())
324
- return [];
325
- return [
326
- {
327
- id: `decision:${decision.id}:rationale`,
328
- entityId: `decision:${decision.id}`,
329
- content,
330
- chunkType: "decision_rationale",
331
- updatedAt: new Date().toISOString()
332
- }
333
- ];
334
- }
335
- function chunkMilestone(milestone) {
336
- if (!milestone.message)
337
- return [];
338
- return [
339
- {
340
- id: `milestone:${milestone.id}:msg`,
341
- entityId: `milestone:${milestone.id}`,
342
- content: milestone.message,
343
- chunkType: "milestone_msg",
344
- updatedAt: new Date().toISOString()
345
- }
346
- ];
347
- }
348
- function chunkMarkdown(filePath, content) {
349
- if (!content.trim())
350
- return [];
351
- const entityId = `file:${filePath}`;
352
- const now = new Date().toISOString();
353
- const sections = splitByHeadings(content);
354
- const chunks = [];
355
- for (let i = 0;i < sections.length; i++) {
356
- const section = sections[i];
357
- if (!section.text.trim())
358
- continue;
359
- if (section.text.length <= MAX_CHUNK_CHARS) {
360
- chunks.push({
361
- id: `${entityId}:section:${i}`,
362
- entityId,
363
- content: section.text,
364
- chunkType: "markdown",
365
- filePath,
366
- updatedAt: now
367
- });
368
- } else {
369
- const windows = slidingWindow(section.text);
370
- for (let w = 0;w < windows.length; w++) {
371
- chunks.push({
372
- id: `${entityId}:section:${i}:w${w}`,
373
- entityId,
374
- content: windows[w],
375
- chunkType: "markdown",
376
- filePath,
377
- updatedAt: now
378
- });
379
- }
380
- }
381
- }
382
- return chunks;
383
- }
384
- function chunkCodeEntities(filePath, declarations) {
385
- const now = new Date().toISOString();
386
- const chunks = [];
387
- for (const decl of declarations) {
388
- const parts = [];
389
- if (decl.docComment)
390
- parts.push(decl.docComment);
391
- parts.push(`${decl.kind} ${decl.name}`);
392
- parts.push(decl.signature);
393
- const content = parts.join(`
394
- `).slice(0, MAX_CHUNK_CHARS);
395
- chunks.push({
396
- id: `symbol:${filePath}#${decl.name}`,
397
- entityId: `symbol:${filePath}#${decl.name}`,
398
- content,
399
- chunkType: "code_entity",
400
- filePath,
401
- updatedAt: now
402
- });
403
- }
404
- return chunks;
405
- }
406
- function chunkDocComments(filePath, comments) {
407
- if (comments.length === 0)
408
- return [];
409
- const entityId = `file:${filePath}`;
410
- const now = new Date().toISOString();
411
- const chunks = [];
412
- for (let i = 0;i < comments.length; i++) {
413
- const comment = comments[i];
414
- if (!comment.text.trim())
415
- continue;
416
- chunks.push({
417
- id: `${entityId}:doc:${i}`,
418
- entityId,
419
- content: comment.text.slice(0, MAX_CHUNK_CHARS),
420
- chunkType: "doc_comment",
421
- filePath,
422
- updatedAt: now
423
- });
424
- }
425
- return chunks;
426
- }
427
- function chunkSummary(filePath, content) {
428
- if (!content.trim())
429
- return [];
430
- const entityId = `file:${filePath}`;
431
- const now = new Date().toISOString();
432
- if (content.length <= MAX_CHUNK_CHARS) {
433
- return [
434
- {
435
- id: `${entityId}:summary`,
436
- entityId,
437
- content,
438
- chunkType: "summary_md",
439
- filePath,
440
- updatedAt: now
441
- }
442
- ];
443
- }
444
- return chunkMarkdown(filePath, content).map((c) => ({
445
- ...c,
446
- chunkType: "summary_md"
447
- }));
448
- }
449
- function chunkFile(filePath, content) {
450
- if (!content.trim())
451
- return [];
452
- const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
453
- if (filePath.endsWith("summary.md")) {
454
- return chunkSummary(filePath, content);
455
- }
456
- if (ext === "md") {
457
- return chunkMarkdown(filePath, content);
458
- }
459
- return [];
460
- }
461
- function splitByHeadings(content) {
462
- const lines = content.split(`
463
- `);
464
- const sections = [];
465
- let currentSection = { text: "" };
466
- for (const line of lines) {
467
- if (/^#{1,3}\s/.test(line)) {
468
- if (currentSection.text.trim()) {
469
- sections.push(currentSection);
470
- }
471
- currentSection = { heading: line, text: line + `
472
- ` };
473
- } else {
474
- currentSection.text += line + `
475
- `;
476
- }
477
- }
478
- if (currentSection.text.trim()) {
479
- sections.push(currentSection);
480
- }
481
- return sections;
482
- }
483
- function slidingWindow(text) {
484
- const windows = [];
485
- let start = 0;
486
- while (start < text.length) {
487
- const end = Math.min(start + MAX_CHUNK_CHARS, text.length);
488
- windows.push(text.slice(start, end));
489
- if (end >= text.length)
490
- break;
491
- start += MAX_CHUNK_CHARS - OVERLAP_CHARS;
492
- }
493
- return windows;
494
- }
495
- var MAX_CHUNK_CHARS = 512, OVERLAP_CHARS = 64;
496
- var init_chunker = () => {};
497
-
498
- // src/embeddings/search.ts
499
- import { join } from "path";
500
- import { readFileSync, existsSync } from "fs";
501
-
502
- class EmbeddingManager {
503
- store;
504
- embedFn;
505
- constructor(dbPath, embedFn) {
506
- this.store = new VectorStore(dbPath);
507
- this.embedFn = embedFn ?? embed;
508
- }
509
- async reindex(engine) {
510
- this.store.clear();
511
- const allChunks = [];
512
- const issues = engine.listIssues();
513
- for (const issue of issues) {
514
- allChunks.push(...chunkIssue(issue));
515
- }
516
- const milestones = engine.listMilestones();
517
- for (const ms of milestones) {
518
- allChunks.push(...chunkMilestone(ms));
519
- }
520
- if (engine.queryDecisions) {
521
- const decisions = engine.queryDecisions();
522
- for (const dec of decisions) {
523
- allChunks.push(...chunkDecision(dec));
524
- }
525
- }
526
- const rootPath = engine.getRootPath();
527
- const trackedFiles = engine.trackedFiles();
528
- for (const tf of trackedFiles) {
529
- try {
530
- const absPath = join(rootPath, tf.path);
531
- if (!existsSync(absPath))
532
- continue;
533
- const content = readFileSync(absPath, "utf-8");
534
- allChunks.push(...chunkFile(tf.path, content));
535
- } catch {}
536
- }
537
- if (engine.parseFile) {
538
- for (const tf of trackedFiles) {
539
- const ext = tf.path.split(".").pop()?.toLowerCase() ?? "";
540
- if (![
541
- "ts",
542
- "js",
543
- "tsx",
544
- "jsx",
545
- "py",
546
- "go",
547
- "rs",
548
- "rb",
549
- "java",
550
- "cs"
551
- ].includes(ext)) {
552
- continue;
553
- }
554
- try {
555
- const parsed = engine.parseFile(tf.path);
556
- if (parsed && Array.isArray(parsed.entities)) {
557
- const declarations = parsed.entities.map((e) => ({
558
- id: e.id ?? e.name,
559
- name: e.name,
560
- kind: e.kind,
561
- signature: e.signature ?? e.rawText?.split(`
562
- `)[0] ?? "",
563
- docComment: e.docComment
564
- }));
565
- allChunks.push(...chunkCodeEntities(tf.path, declarations));
566
- }
567
- } catch {}
568
- }
569
- }
570
- const records = [];
571
- for (const chunk of allChunks) {
572
- try {
573
- const vector = await this.embedFn(chunk.content);
574
- records.push({ ...chunk, embedding: vector });
575
- } catch {}
576
- }
577
- this.store.upsertBatch(records);
578
- return { chunks: records.length };
579
- }
580
- async indexFile(filePath, content, engine) {
581
- this.store.deleteByFile(filePath);
582
- const chunks = chunkFile(filePath, content);
583
- if (engine?.parseFile) {
584
- const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
585
- if ([
586
- "ts",
587
- "js",
588
- "tsx",
589
- "jsx",
590
- "py",
591
- "go",
592
- "rs",
593
- "rb",
594
- "java",
595
- "cs"
596
- ].includes(ext)) {
597
- try {
598
- const parsed = engine.parseFile(filePath);
599
- if (parsed && Array.isArray(parsed.entities)) {
600
- const declarations = parsed.entities.map((e) => ({
601
- id: e.id ?? e.name,
602
- name: e.name,
603
- kind: e.kind,
604
- signature: e.signature ?? e.rawText?.split(`
605
- `)[0] ?? "",
606
- docComment: e.docComment
607
- }));
608
- chunks.push(...chunkCodeEntities(filePath, declarations));
609
- }
610
- } catch {}
611
- }
612
- }
613
- const records = [];
614
- for (const chunk of chunks) {
615
- try {
616
- const vector = await this.embedFn(chunk.content);
617
- records.push({ ...chunk, embedding: vector });
618
- } catch {}
619
- }
620
- if (records.length > 0) {
621
- this.store.upsertBatch(records);
622
- }
623
- return records.length;
624
- }
625
- async indexIssue(issue) {
626
- this.store.deleteByEntity(`issue:${issue.id}`);
627
- const chunks = chunkIssue(issue);
628
- const records = [];
629
- for (const chunk of chunks) {
630
- try {
631
- const vector = await this.embedFn(chunk.content);
632
- records.push({ ...chunk, embedding: vector });
633
- } catch {}
634
- }
635
- if (records.length > 0) {
636
- this.store.upsertBatch(records);
637
- }
638
- return records.length;
639
- }
640
- async indexMilestone(milestone) {
641
- this.store.deleteByEntity(`milestone:${milestone.id}`);
642
- const chunks = chunkMilestone(milestone);
643
- const records = [];
644
- for (const chunk of chunks) {
645
- try {
646
- const vector = await this.embedFn(chunk.content);
647
- records.push({ ...chunk, embedding: vector });
648
- } catch {}
649
- }
650
- if (records.length > 0) {
651
- this.store.upsertBatch(records);
652
- }
653
- return records.length;
654
- }
655
- async search(query, opts) {
656
- const queryVector = await this.embedFn(query);
657
- return this.store.search(queryVector, opts);
658
- }
659
- removeFile(filePath) {
660
- this.store.deleteByFile(filePath);
661
- }
662
- stats() {
663
- return {
664
- total: this.store.count(),
665
- byType: this.store.countByType()
666
- };
667
- }
668
- close() {
669
- this.store.close();
670
- }
671
- }
672
- var init_search = __esm(() => {
673
- init_store();
674
- init_model();
675
- init_chunker();
676
- });
677
-
678
- // src/embeddings/auto-embed.ts
679
- function entitySummaryText(entityId, facts, links) {
680
- const type = facts.find((f) => f.a === "type")?.v ?? "Entity";
681
- const name = facts.find((f) => f.a === "name" || f.a === "title")?.v ?? entityId;
682
- const parts = [`${type}: ${name} (${entityId})`];
683
- const attrs = facts.filter((f) => !["type", "name", "title", "createdAt", "updatedAt"].includes(f.a));
684
- if (attrs.length > 0) {
685
- parts.push(attrs.map((f) => ` ${f.a} = ${f.v}`).join(`
686
- `));
687
- }
688
- if (links.length > 0) {
689
- parts.push("Relations:");
690
- parts.push(links.map((l) => ` ${l.a} \u2192 ${l.e2}`).join(`
691
- `));
692
- }
693
- return parts.join(`
694
- `);
695
- }
696
- function createAutoEmbedMiddleware(options) {
697
- const store = new VectorStore(options.dbPath);
698
- const embedFn = options.embedFn ?? embed;
699
- const embedIndividual = options.embedIndividualFacts ?? false;
700
- return {
701
- name: "auto-embed",
702
- handleOp: async (op, ctx, next) => {
703
- await next(op, ctx);
704
- try {
705
- await _processOp(op, store, embedFn, embedIndividual);
706
- } catch {}
707
- },
708
- close: () => {
709
- store.close();
710
- }
711
- };
712
- }
713
- async function _processOp(op, store, embedFn, embedIndividual) {
714
- const now = new Date().toISOString();
715
- const entityIds = new Set;
716
- if (op.facts)
717
- for (const f of op.facts)
718
- entityIds.add(f.e);
719
- if (op.links)
720
- for (const l of op.links) {
721
- entityIds.add(l.e1);
722
- entityIds.add(l.e2);
723
- }
724
- if (op.deleteFacts)
725
- for (const f of op.deleteFacts)
726
- entityIds.add(f.e);
727
- if (op.deleteLinks)
728
- for (const l of op.deleteLinks) {
729
- entityIds.add(l.e1);
730
- entityIds.add(l.e2);
731
- }
732
- if (op.deleteFacts || op.deleteLinks) {
733
- for (const eid of entityIds) {
734
- store.deleteByEntity(eid);
735
- }
736
- }
737
- if (op.facts && op.facts.length > 0) {
738
- const factsByEntity = new Map;
739
- for (const f of op.facts) {
740
- const existing = factsByEntity.get(f.e) ?? [];
741
- existing.push(f);
742
- factsByEntity.set(f.e, existing);
743
- }
744
- const linksByEntity = new Map;
745
- if (op.links) {
746
- for (const l of op.links) {
747
- const existing = linksByEntity.get(l.e1) ?? [];
748
- existing.push(l);
749
- linksByEntity.set(l.e1, existing);
750
- }
751
- }
752
- const records = [];
753
- for (const [eid, facts] of factsByEntity) {
754
- const links = linksByEntity.get(eid) ?? [];
755
- const summaryText = entitySummaryText(eid, facts, links);
756
- if (summaryText.trim()) {
757
- try {
758
- const vector = await embedFn(summaryText);
759
- records.push({
760
- id: `entity:${eid}:summary`,
761
- entityId: eid,
762
- content: summaryText,
763
- chunkType: "summary_md",
764
- updatedAt: now,
765
- embedding: vector
766
- });
767
- } catch {}
768
- }
769
- if (embedIndividual) {
770
- for (const fact of facts) {
771
- if (["type", "createdAt", "updatedAt"].includes(fact.a))
772
- continue;
773
- const text = `${fact.a}: ${fact.v}`;
774
- try {
775
- const vector = await embedFn(text);
776
- records.push({
777
- id: `entity:${eid}:fact:${fact.a}`,
778
- entityId: eid,
779
- content: text,
780
- chunkType: "doc_comment",
781
- updatedAt: now,
782
- embedding: vector
783
- });
784
- } catch {}
785
- }
786
- }
787
- }
788
- if (records.length > 0) {
789
- store.upsertBatch(records);
790
- }
791
- }
792
- }
793
- async function buildRAGContext(query, vectorStore, embedFn = embed, options) {
794
- const maxChunks = options?.maxChunks ?? 10;
795
- const maxTokens = options?.maxTokens ?? 4000;
796
- const minScore = options?.minScore ?? 0.1;
797
- const queryVector = await embedFn(query);
798
- const results = vectorStore.search(queryVector, {
799
- limit: maxChunks * 2,
800
- minScore
801
- });
802
- const chunks = [];
803
- let totalChars = 0;
804
- for (const r of results) {
805
- if (chunks.length >= maxChunks)
806
- break;
807
- if (totalChars + r.chunk.content.length > maxTokens * 4)
808
- break;
809
- chunks.push({
810
- content: r.chunk.content,
811
- entityId: r.chunk.entityId,
812
- score: r.score,
813
- chunkType: r.chunk.chunkType
814
- });
815
- totalChars += r.chunk.content.length;
816
- }
817
- return {
818
- query,
819
- chunks,
820
- estimatedTokens: Math.ceil(totalChars / 4)
821
- };
822
- }
823
- var init_auto_embed = __esm(() => {
824
- init_store();
825
- init_model();
826
- });
827
-
828
- // src/embeddings/index.ts
829
- var exports_embeddings = {};
830
- __export(exports_embeddings, {
831
- slidingWindow: () => slidingWindow,
832
- resetModel: () => resetModel,
833
- loadModel: () => loadModel,
834
- embedBatch: () => embedBatch,
835
- embed: () => embed,
836
- createAutoEmbedMiddleware: () => createAutoEmbedMiddleware,
837
- cosineSimilarity: () => cosineSimilarity,
838
- chunkSummary: () => chunkSummary,
839
- chunkMilestone: () => chunkMilestone,
840
- chunkMarkdown: () => chunkMarkdown,
841
- chunkIssue: () => chunkIssue,
842
- chunkFile: () => chunkFile,
843
- chunkDocComments: () => chunkDocComments,
844
- chunkDecision: () => chunkDecision,
845
- chunkCodeEntities: () => chunkCodeEntities,
846
- buildRAGContext: () => buildRAGContext,
847
- VectorStore: () => VectorStore,
848
- EmbeddingManager: () => EmbeddingManager,
849
- DEFAULT_MODEL_CONFIG: () => DEFAULT_MODEL_CONFIG
850
- });
851
- var init_embeddings = __esm(() => {
852
- init_types();
853
- init_model();
854
- init_store();
855
- init_search();
856
- init_auto_embed();
857
- init_chunker();
858
- });
859
-
860
- export { DEFAULT_MODEL_CONFIG, loadModel, embed, embedBatch, resetModel, init_model, VectorStore, cosineSimilarity, init_store, chunkIssue, chunkDecision, chunkMilestone, chunkMarkdown, chunkCodeEntities, chunkDocComments, chunkSummary, chunkFile, slidingWindow, EmbeddingManager, createAutoEmbedMiddleware, buildRAGContext, init_auto_embed, exports_embeddings, init_embeddings };