@yaks/embedding 0.0.0-stage → 0.2.36

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 (132) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +549 -2
  3. package/_dist/compile.d.ts +34 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/ddl.d.ts +31 -0
  6. package/_dist/ddl.d.ts.map +1 -0
  7. package/_dist/embedder.d.ts +55 -0
  8. package/_dist/embedder.d.ts.map +1 -0
  9. package/_dist/fields.d.ts +70 -0
  10. package/_dist/fields.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +63 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/held.d.ts +16 -0
  14. package/_dist/held.d.ts.map +1 -0
  15. package/_dist/image.d.ts +20 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +105 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/native.d.ts +20 -0
  20. package/_dist/native.d.ts.map +1 -0
  21. package/_dist/near.d.ts +35 -0
  22. package/_dist/near.d.ts.map +1 -0
  23. package/_dist/neighbours.d.ts +29 -0
  24. package/_dist/neighbours.d.ts.map +1 -0
  25. package/_dist/options.d.ts +37 -0
  26. package/_dist/options.d.ts.map +1 -0
  27. package/_dist/outage.d.ts +64 -0
  28. package/_dist/outage.d.ts.map +1 -0
  29. package/_dist/owed.d.ts +79 -0
  30. package/_dist/owed.d.ts.map +1 -0
  31. package/_dist/remote.d.ts +116 -0
  32. package/_dist/remote.d.ts.map +1 -0
  33. package/_dist/score.d.ts +10 -0
  34. package/_dist/score.d.ts.map +1 -0
  35. package/_dist/search.d.ts +24 -0
  36. package/_dist/search.d.ts.map +1 -0
  37. package/_dist/service.d.ts +23 -0
  38. package/_dist/service.d.ts.map +1 -0
  39. package/_dist/sleeper.d.ts +37 -0
  40. package/_dist/sleeper.d.ts.map +1 -0
  41. package/_dist/sweep.d.ts +71 -0
  42. package/_dist/sweep.d.ts.map +1 -0
  43. package/_dist/tools.d.ts +14 -0
  44. package/_dist/tools.d.ts.map +1 -0
  45. package/_dist/vector.d.ts +30 -0
  46. package/_dist/vector.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +6 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/coded.js +98 -0
  50. package/coded.js.map +1 -0
  51. package/coded.ts +85 -0
  52. package/compile.js +145 -0
  53. package/compile.js.map +1 -0
  54. package/compile.ts +206 -0
  55. package/ddl.js +476 -0
  56. package/ddl.js.map +1 -0
  57. package/ddl.ts +346 -0
  58. package/deno.json +1 -0
  59. package/embedder.js +85 -0
  60. package/embedder.js.map +1 -0
  61. package/embedder.ts +113 -0
  62. package/fields.js +178 -0
  63. package/fields.js.map +1 -0
  64. package/fields.ts +259 -0
  65. package/fill.js +177 -0
  66. package/fill.js.map +1 -0
  67. package/fill.ts +144 -0
  68. package/graph.js +113 -0
  69. package/graph.js.map +1 -0
  70. package/graph.ts +167 -0
  71. package/held.js +680 -0
  72. package/held.js.map +1 -0
  73. package/held.ts +726 -0
  74. package/image.js +202 -0
  75. package/image.js.map +1 -0
  76. package/image.ts +185 -0
  77. package/mod.js +105 -0
  78. package/mod.js.map +1 -0
  79. package/mod.ts +113 -0
  80. package/native.js +236 -0
  81. package/native.js.map +1 -0
  82. package/native.ts +288 -0
  83. package/near.js +123 -0
  84. package/near.js.map +1 -0
  85. package/near.ts +192 -0
  86. package/neighbours.js +223 -0
  87. package/neighbours.js.map +1 -0
  88. package/neighbours.ts +303 -0
  89. package/options.js +187 -0
  90. package/options.js.map +1 -0
  91. package/options.ts +269 -0
  92. package/outage.js +128 -0
  93. package/outage.js.map +1 -0
  94. package/outage.ts +132 -0
  95. package/owed.js +287 -0
  96. package/owed.js.map +1 -0
  97. package/owed.ts +346 -0
  98. package/package.json +45 -4
  99. package/remote.js +264 -0
  100. package/remote.js.map +1 -0
  101. package/remote.ts +391 -0
  102. package/score.js +46 -0
  103. package/score.js.map +1 -0
  104. package/score.ts +60 -0
  105. package/search.js +65 -0
  106. package/search.js.map +1 -0
  107. package/search.ts +118 -0
  108. package/service.js +107 -0
  109. package/service.js.map +1 -0
  110. package/service.ts +133 -0
  111. package/sleeper.js +107 -0
  112. package/sleeper.js.map +1 -0
  113. package/sleeper.ts +166 -0
  114. package/sparse.js +36 -0
  115. package/sparse.js.map +1 -0
  116. package/sparse.ts +49 -0
  117. package/sweep.js +374 -0
  118. package/sweep.js.map +1 -0
  119. package/sweep.ts +446 -0
  120. package/tools.js +57 -0
  121. package/tools.js.map +1 -0
  122. package/tools.ts +88 -0
  123. package/vector.js +78 -0
  124. package/vector.js.map +1 -0
  125. package/vector.ts +96 -0
  126. package/visibility.js +83 -0
  127. package/visibility.js.map +1 -0
  128. package/visibility.ts +111 -0
  129. package/vocab.js +22 -0
  130. package/vocab.js.map +1 -0
  131. package/vocab.json +19 -0
  132. package/vocab.ts +22 -0
package/README.md CHANGED
@@ -1,3 +1,550 @@
1
- # Temporary Holding Version
1
+ # @yaks/embedding
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Maintains text vectors for graph entities and ranks entities by vector
4
+ similarity. An embedder converts text into a `Float32Array`; a background
5
+ reconciliation pass stores the vectors in SQLite. The SQL extension answers
6
+ `.near=<entity>` queries from those stored vectors without making network
7
+ requests during compilation.
8
+
9
+ A **bundle** is one entity's components as a JSON object. The **host** is the
10
+ process that opened the graph and loaded the plugin, such as `yak serve` or a
11
+ CLI command.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ deno add jsr:@yaks/embedding
17
+ # or: npx jsr add @yaks/embedding
18
+ ```
19
+
20
+ ## Use
21
+
22
+ Here `db` is @yaks/sql's synchronous `Statements` capability, which runs a
23
+ statement with `query(statement)`, over an in-memory database holding two books.
24
+
25
+ ```ts
26
+ import { loadVocab } from '@yaks/vocab'
27
+ import { graph } from '@yaks/graph'
28
+ import { statements, storage } from '@yaks/sqlite'
29
+ import { open } from '@yaks/sqlite/db'
30
+ import {
31
+ fields,
32
+ hashEmbedder,
33
+ meaning,
34
+ schema,
35
+ semantic,
36
+ sweep,
37
+ } from '@yaks/embedding'
38
+
39
+ let title = { type: 'string', search: true }
40
+ let book = { component: true, properties: { title, price: { type: 'number' } } }
41
+ let vocab = loadVocab([{ $defs: { book } }])
42
+ let driver = open(':memory:')
43
+ let db = statements(driver)
44
+ for (let statement of storage(driver, vocab).ddl()) db.query(statement)
45
+ graph({ storage: storage(driver, vocab), vocab }).apply([
46
+ { entity: { eid: 'book-1' }, book: { title: 'The Hobbit', price: 12 } },
47
+ { entity: { eid: 'book-2' }, book: { title: 'The Silmarillion', price: 18 } },
48
+ ])
49
+
50
+ let text = fields(vocab)
51
+ for (let statement of schema()) db.query(statement)
52
+
53
+ let embedder = hashEmbedder()
54
+ await sweep(db, text, embedder)
55
+
56
+ let near = semantic(db, embedder)
57
+ let store = storage(driver, vocab, { extend: [near] })
58
+ let rows = store.read('.near=book-1&.order=similar .book.price<20')
59
+ let ranked = near.rank(rows) // adds rank: { score } to matching bundles
60
+ let hits = await meaning(
61
+ db,
62
+ text,
63
+ embedder,
64
+ 'a story about an unexpected journey',
65
+ )
66
+ // each hit has { entity, similarity, excerpt }
67
+ ```
68
+
69
+ `hashEmbedder()` is deterministic and needs no network. It measures hashed word
70
+ counts, not semantic meaning; use a model-backed embedder for semantic search.
71
+ Call `sweep()` after text changes or schedule it through the plugin below.
72
+
73
+ `meaning()` embeds new search words and ranks the stored vectors. Each excerpt
74
+ comes from the configured text that made the vector, including resolved text for
75
+ a property stored by address. An excerpt has no match markers: a semantic hit
76
+ need not contain any search word. It returns at most 20 hits by default;
77
+ `limit`, `floor` and an optional candidate `screen` can narrow them. The screen
78
+ is asked for once the words are embedded (@yaks/sql `Screen`), so a store's
79
+ `screen(query)` names the archetypes the search then reads.
80
+
81
+ ## As a plugin
82
+
83
+ The plugin configuration names a provider and a model, the way a session names
84
+ what serves it, and the text fields:
85
+
86
+ ```json
87
+ {
88
+ "plugins": [
89
+ "@yaks/doc",
90
+ "@yaks/model",
91
+ {
92
+ "use": "@yaks/embedding",
93
+ "with": {
94
+ "embedder": {
95
+ "provider": "ollama",
96
+ "model": "granite-embedding-30m-english"
97
+ },
98
+ "text": ["doc.title"],
99
+ "neighbours": 8,
100
+ "after": 3000
101
+ }
102
+ }
103
+ ]
104
+ }
105
+ ```
106
+
107
+ A provider reached over HTTP is a row in the graph ([@yaks/model](../model)):
108
+ `provider{name, base, api}` says where it answers and which API it speaks
109
+ (`ollama`, or `openai` for an OpenAI-compatible server), and a `serves` edge
110
+ from it to the `model` row says what it calls that model (`serves.name`). So
111
+ choosing another model, or another server, is a write, never a release:
112
+
113
+ ```json
114
+ [
115
+ {
116
+ "entity": { "eid": "$ollama" },
117
+ "provider": {
118
+ "name": "ollama",
119
+ "base": "https://ollama.example",
120
+ "api": "ollama"
121
+ }
122
+ },
123
+ {
124
+ "entity": { "eid": "$granite" },
125
+ "model": { "name": "granite-embedding-30m-english" }
126
+ },
127
+ {
128
+ "entity": { "eid": "$serves" },
129
+ "edge": { "from": "$ollama", "to": "$granite" },
130
+ "serves": { "name": "granite-embedding:30m" }
131
+ }
132
+ ]
133
+ ```
134
+
135
+ The vector space is the model's own name (`granite-embedding-30m-english`), and
136
+ its width where `dim` cuts it (`qwen3-embedding-0.6b#256`), whoever serves it:
137
+ the same model moved to another provider keeps its vectors. A provider that
138
+ wants a token is given one beside it, `"key": { "secret": "NAME" }`. Workers AI
139
+ outside a Worker is such a row as well: `api: "openai"`, its base
140
+ `https://api.cloudflare.com/client/v4/accounts/<account>/ai`, and a token for
141
+ `key`. A provider that runs in this process needs no row: `hash`, the offline
142
+ embedder below, or one another plugin lends the host by name (@yaks/host
143
+ `embedders`), such as `model2vec` from @yaks/model2vec. This package imports no
144
+ embedder provider.
145
+
146
+ `@yaks/embedding/graph` creates the vector tables through the host's SQL driver.
147
+ Its `extend()` export registers the `.near` compiler; its `meaning()` factory is
148
+ the host's `meaning` (@yaks/host), which resolves the current embedder on each
149
+ search, so a key arriving later is used without rebuilding the host, and ranks
150
+ among what a `within` filter line admits, compiled by the storage's `screen`.
151
+ `@yaks/embedding/service` is the plugin's service, held by one process per
152
+ graph: it sweeps the queue, takes the next batch at once while work is left, and
153
+ looks again after `after` once the queue is empty. The graph write does not
154
+ await embedding. The service stops when its signal aborts, and a pass the host
155
+ ended leaves its work queued. A pass that fails reports to the host's `report`
156
+ (the box's tracker) as a yaks.app store's drain does (`drained`, `failed`,
157
+ below), tagged `{ package: '@yaks/embedding', step: 'embedding pass' }`.
158
+
159
+ Options:
160
+
161
+ | Option | Meaning |
162
+ | ------------ | -------------------------------------------------------------------------------------- |
163
+ | `embedder` | `{ provider, model?, dim?, key?, chars? }`: `hash`, a lent embedder, or a provider row |
164
+ | `text` | Selected `component.property` names; defaults to the properties marked `search: true` |
165
+ | `neighbours` | Maximum `.near` results, default 8 |
166
+ | `floor` | Minimum similarity for `.near`, default 0 |
167
+ | `after` | How long an empty queue waits before the next look, in milliseconds, default 3000 |
168
+ | `batch` | Queued entities one sweep takes, default 64 |
169
+
170
+ The `batch` option bounds one sweep; it does not mean a graph transaction.
171
+
172
+ Missing embedder configuration, a missing configured key, or a provider or model
173
+ row not written yet does not prevent startup. `vector_check` reports what is
174
+ missing, and the service keeps looking until it arrives, reading the rows again
175
+ on every pass. Invalid `text` names are also reported.
176
+
177
+ The CLI resolves `{ "secret": "NAME" }` through [@yaks/secrets](../secrets) each
178
+ time options are read, so a key written through the graph after the host started
179
+ is used on the next pass. A later export in a separate shell does not change an
180
+ already running process's environment. A writing host adds the vector tables
181
+ with the rest of its composed schema (`schema()` in `./graph`). Field watches
182
+ and the query extension are bound when the plugin is composed; changing their
183
+ configuration may require rebuilding them.
184
+
185
+ The package has a `vocab.json` declaring the `vector_check` tool, but no graph
186
+ component for stored vectors. Vectors are derived SQL data and are not included
187
+ in ordinary graph snapshots or client sync.
188
+
189
+ ## Which text is embedded
190
+
191
+ `fields(vocab)` selects stored scalar text properties in vocabulary order,
192
+ excluding computed properties and references. A `pick(prop)` argument replaces
193
+ that default predicate; combine it with `textual(prop)` to narrow the default
194
+ safely. After them come the fields a component's `search` list names
195
+ (@yaks/vocab): `entry` says `"search": ["content.body"]`, so a transcript entry
196
+ is embedded by its content and no other entity carrying `content` is. The same
197
+ list makes @yaks/fts index that text, so what a bare word finds, `.near` finds
198
+ too.
199
+
200
+ An entity wearing a component marked `embed: false` gets no vector, and neither
201
+ does one wearing a component marked `found: false`, which no search finds
202
+ (@yaks/kernel's `quarantined`). Each field carries those components as its
203
+ `not`; the sweep drops a vector when one is put on and makes it again when it
204
+ comes off.
205
+
206
+ Each entity gets one vector from its nonblank selected fields joined with
207
+ newlines. The source query reads component columns directly, except a column the
208
+ host reads through an expression: `resolved(fields, host.derived)` gives such a
209
+ field its `text` expression, so a `@yaks/blob` body is embedded as its prose
210
+ rather than its stored hash. The plugin's sweep does this; a caller running
211
+ `sweep()` itself passes resolved fields.
212
+
213
+ ## The embedder is yours
214
+
215
+ ```ts
216
+ type Embedder = {
217
+ model: string
218
+ embed: (text: string) => Float32Array | Promise<Float32Array>
219
+ }
220
+ ```
221
+
222
+ The model name is stored beside each vector and included in the source hash.
223
+ Queries compare only vectors under the selected model name. Changing that name
224
+ makes existing text stale and causes the next sweep to recompute it.
225
+
226
+ `hashEmbedder(dim?)` defaults to 64 dimensions. It hashes words into counts and
227
+ normalizes the resulting vector. `remote({ api, model, base, key?, dim? })`
228
+ posts to Ollama's `/api/embed` or an OpenAI-compatible `/v1/embeddings`
229
+ endpoint, asking for `model` by the name the server knows it by; `space` names
230
+ the vectors otherwise. The calls made together, as `Promise.all(texts.map(...))`
231
+ makes them, ride in one request, up to `count` (64) inputs and `load` (128,000)
232
+ characters each. Credentials are arguments; `remote()` itself reads no
233
+ environment variables. Optional `dim` truncates and renormalizes vectors; use it
234
+ with a model that supports that operation. Two widths of one model are two
235
+ spaces, so a `dim` is part of the stored model name
236
+ (`qwen3-embedding-0.6b#256`). `chars` (default 30,000) bounds the text sent for
237
+ one vector. A server may refuse a text past its model's context rather than
238
+ truncate it, as Ollama does for some texts on a 512-token model, so a text
239
+ refused alone is asked again as its opening half, down to 256 characters. A
240
+ status saying the input was refused (400, 413, 422) rejects with `Refused`. Any
241
+ other failure is the provider's, which usually passes in seconds, so the request
242
+ is sent again after each pause of `retries.waits` (half a second, two, then
243
+ six); one that outlasts them rejects once with `Unanswered`. Its message names
244
+ only the provider (`@yaks/embedding: workers-ai did not answer`), so one outage
245
+ reads as one failure however many texts it met or in which words; its `context`
246
+ holds the model, how many texts and how many tries, and its `cause` is the
247
+ provider's last failure. `retrying(provider, model, ask, waits?)` is that, for
248
+ any `ask`.
249
+
250
+ `{ provider: 'model2vec', model: 'minishlab/potion-retrieval-32M@6fc8051', dim: 256 }`,
251
+ with the `@yaks/model2vec` plugin composed beside this one, runs a Model2Vec
252
+ static model in this process ([@yaks/model2vec](../model2vec)): about a
253
+ millisecond for a 500-token text on one core, fast enough to embed every prompt.
254
+ The model is fetched from the Hugging Face hub on the first embed and kept in
255
+ the platform's cache. Its space is the pinned model and its width
256
+ (`minishlab/potion-retrieval-32M@6fc8051#256`).
257
+
258
+ `{ provider: 'workers-ai', model: '@cf/qwen/qwen3-embedding-0.6b', dim: 256 }`,
259
+ with the `@yaks/workers-ai` plugin composed beside this one and lent a Worker's
260
+ `AI` binding, asks Cloudflare Workers AI through it
261
+ ([@yaks/workers-ai](../workers-ai)). Outside a Worker, Workers AI is an
262
+ OpenAI-compatible endpoint for `remote`. `batched(model, ask, load?)` is the
263
+ batching such a provider shares with `remote`, for any that answers many texts
264
+ at once.
265
+
266
+ ## The sweep
267
+
268
+ Triggers on each component a field lives on queue the entity a write touched in
269
+ `embedding_owed`, in the same statement as the write, whichever process made it.
270
+ `watch(db, fields)` makes the triggers match the fields. A trigger it makes,
271
+ drops or changes queues the entities in the table it is on, wearing a field or
272
+ holding a vector, which is how a new field is backfilled; a component whose
273
+ trigger stood is not queued, since its trigger saw every write. A new database,
274
+ or a vector table made again, moves the triggers on the vectors and the
275
+ tombstones and queues every entity (`moves` says which). With unchanged fields
276
+ and schema, `watch` issues no SQL. Both trigger inspection and
277
+ native-installation inspection reuse the statement capability's
278
+ `revision('schema')` token; DDL, rollback, and file-peer schema changes discard
279
+ those decisions.
280
+
281
+ Reconciliation keeps durable source-table cursors in `embedding_fill`. Each pass
282
+ visits at most 256 candidate rows by primary key before checking their fields or
283
+ exclusions; even an excluded tail advances. The queue and cursor advance in one
284
+ transaction. A restart resumes the cursor, and triggers cover writes made while
285
+ it advances. The service yields to the event loop between passes.
286
+
287
+ `sweep(db, fields, embedder, limit?)` calls `watch`, then takes the newest
288
+ `limit` (64) queued entities: it embeds those whose text changed, deletes the
289
+ vector of those with no text (emptied, deleted, or no longer wearing a field),
290
+ and settles each unless a write queued it again meanwhile. Source hashes avoid
291
+ model calls for unchanged text. Once the queue is empty, a vector made by
292
+ another model queues everything again. It returns `{ fresh, left, refused }`;
293
+ `left` counts queued owners plus one while reconciliation still has candidates
294
+ to visit. A text the embedder refuses loses its vector and is reported in
295
+ `refused`; any other embedder failure stops the pass, the caller receives the
296
+ error, and the work stays queued.
297
+
298
+ `drain(db, fields, embedder, { batch?, signal? })` sweeps pass after pass until
299
+ nothing is owed, registering the native scan or folding the pass into the
300
+ vectors held in memory after each (below), then codes every vector that has no
301
+ int8 codes (Native scans), and returns `{ fresh, refused }`: the service's loop
302
+ is a drain and a wait, and a host with nothing standing between requests (a
303
+ Durable Object sleeps) drains once a write commits. An aborted `signal` stops it
304
+ after the pass it is in.
305
+
306
+ A model that does not answer is an outage the drains ride out: its texts stay
307
+ owed, are still found by their words, and are embedded by the first drain after
308
+ it answers. So what fails is the wait, not each try. `drained` and
309
+ `failed(error)` say what one drain's outcome makes of the `Outage` a host keeps
310
+ between drains: an `Unanswered` starts an outage or rides on in it, and the
311
+ drain that answers ends it, each end a line to log; once its texts have waited
312
+ `OVERDUE` (a quarter of an hour) the outage reports once, as `Overdue`, the
313
+ `Unanswered` as its cause and the wait in its `context`. Any other failure
314
+ reports at once, and once while drains keep failing by it; the drain that next
315
+ answers logs that it did.
316
+
317
+ ```ts
318
+ import { equal } from '@yaks/testing'
319
+ import { failed, OVERDUE, Overdue, Unanswered } from '@yaks/embedding'
320
+
321
+ let down = failed(
322
+ new Unanswered('workers-ai', { model: 'm', texts: '1', tries: '4' }, '4009'),
323
+ )
324
+ let { outage, log } = down(null, 0)
325
+ equal([outage, typeof log], [{ since: 0 }, 'string'])
326
+ equal(down(outage, OVERDUE - 1).report, undefined)
327
+ equal(down(outage, OVERDUE).report instanceof Overdue, true)
328
+ ```
329
+
330
+ `sources()`, `put()`, `watch()`, `moves()`, `owe()`, `due()` and `paid()` expose
331
+ the individual operations. Embedding can run asynchronously; source reads,
332
+ vector writes and query ranking use the synchronous database driver. A sweep is
333
+ not one graph transaction.
334
+
335
+ A newly created entity cannot be compared until its vector exists. The plugin's
336
+ reply (below) makes that vector at once for an entity a tool call created; an
337
+ application of its own can embed the new text and call `nearest()`.
338
+
339
+ ## A write answers what it is near
340
+
341
+ As a plugin, `@yaks/embedding/graph` exports `reply(host, options)`: what a
342
+ direct tool call's answer carries beside the tool's own
343
+ ([@yaks/tools](../tools/README.md) `Reply`). For each entity the call's write
344
+ created, up to five, it answers the three existing entities of the same kind
345
+ nearest to it, so whoever wrote a task, a memory or a comment sees at once
346
+ whether the graph already holds it. A read, a rehearsal and a refusal created
347
+ nothing and get nothing.
348
+
349
+ The new entity's vector is made then, waiting at most a second for the model,
350
+ and stored as the sweep stores it, so the sweep finds it made and calls no
351
+ model. The neighbours are `.near=<entity>&.order=similar` among entities of that
352
+ kind. Where the model has not answered or no embedder is configured, the words
353
+ of the entity's first line (a document's title) are the query instead, ordered
354
+ by `.order=search`: a twin that says the same thing in the same words. A config
355
+ without this plugin answers no neighbours.
356
+
357
+ Each neighbour is a bundle carrying a query-only `hit`, the shape a search
358
+ answers with: its `kind`, its `title` (or an excerpt of its text as `snippet`),
359
+ its `status` where it has one, `source` (`meaning` or `text`), and `near`, the
360
+ eid of the new entity it was found near. The tool's own bundles come first,
361
+ unchanged. A model reads each neighbour as one line:
362
+
363
+ ```text
364
+ near <new eid>: <eid> Fix the login page crash on submit · task open (meaning)
365
+ ```
366
+
367
+ ## How `.near` compiles
368
+
369
+ `semantic(db, { model }, options?)` supplies an `@yaks/sql` extension:
370
+
371
+ 1. Read the target entity's stored vector.
372
+ 2. Rank candidates admitted by the rest of the query's filters.
373
+ 3. Compile the selected integer entity IDs into the SQL condition and a `CASE`
374
+ expression for `.order=similar`.
375
+
376
+ The extension declares `.near` one of its `few` clauses (@yaks/sql
377
+ `Extension.few`), so the statement reads those few owners by key and tests the
378
+ rest of the query on each, rather than selecting every owner the other filters
379
+ admit to find them among.
380
+
381
+ The default limit is eight neighbors and the target itself is excluded. A target
382
+ without a vector selects nothing. A custom `rank` implementation receives the
383
+ same candidate filter and must honor it before limiting results.
384
+
385
+ `.near=book-1&.order=similar&.limit=5` returns the first five results. An
386
+ ordinary `.after=<num>` cursor continues after that entity's position in the
387
+ ranking; a cursor outside the selected neighbors returns an empty page.
388
+ `.order=similar` without `.near` throws `Unsupported`.
389
+
390
+ `near.rank(bundles)` adds a query-only `rank: { score }` component and sorts
391
+ matching bundles by similarity. It preserves unmatched bundles at the end and
392
+ stores nothing. The extension retains scores for the most recently compiled
393
+ query and resets them when another compilation begins. Read/decorate one query's
394
+ results before reusing the same extension for another query.
395
+
396
+ ## The ranking
397
+
398
+ `nearest()` ranks by cosine similarity over current stored vectors, among the
399
+ entities a screen admits, excluding tombstones immediately. A copy of the
400
+ vectors held in memory answers where the process holds one (below). Where it
401
+ holds none, a screen admitting at most 5000 entities, or an eighth of the
402
+ corpus, reads only its admitted int8 codes on shared storage, and broader local
403
+ SQLite searches scan the corpus with sqlite-vector. Candidates are rescored from
404
+ their current float vectors before the final cut. Missing codes or mixed models
405
+ use the ordinary float reader for a selective screen.
406
+
407
+ Supply `semantic(db, space, { rank })` with a `Rank` implementation to use
408
+ another ranking; it receives the same screen.
409
+
410
+ ## Native scans
411
+
412
+ The native `vector_full_scan` reads each vector's int8 codes on shared storage,
413
+ and the float vectors where some vector has none yet. The screen and exclusion
414
+ of deleted entities are asked of the nearest the scan draws (eight times the
415
+ pool under a screen), not of every stored vector; too few admitted draws eight
416
+ times as many, up to the whole corpus, so the pool is the one a screened scan
417
+ would give. The pool is ranked by its float vectors. Writes are visible
418
+ immediately, including those made by another connection. There is no quantized
419
+ index or rebuild on the write path.
420
+
421
+ The codes live in `embedding_code`, one row per vector: each coordinate over the
422
+ vector's largest in 127 steps, whose cosine is the vector's within a step. A row
423
+ takes 384 bytes at 384 dimensions where the floats take 1,536 and only two fit a
424
+ 4 KB page, so a scan whose pages the box's cache has let go reads a fifth as
425
+ much from disk: 577 MB of floats for 282k vectors, against about 115 MB of
426
+ codes. The sweep codes each vector it stores, triggers delete a vector's codes
427
+ when it changes or goes, and `drain` codes whatever has none (`heal`: vectors
428
+ another writer stored, or stored before the table existed). A search uses the
429
+ codes once there are as many as vectors.
430
+
431
+ A read-only probe of 202,852 stored 384-dimensional vectors took 513–585 ms for
432
+ a warm broad top-eight search over the floats and 592 ms with a task filter.
433
+ Cold calls under concurrent migration and database load took up to 13.4 s, and a
434
+ search by meaning on the box once took 11 s waiting on disk. A full index
435
+ rebuild held the live worker for 27.9 s. Exact scans trade broad-search latency
436
+ for predictable writes. Narrow screens rank their admitted codes directly, then
437
+ read only the best candidates' float vectors.
438
+
439
+ `installNative(db)` loads the storage adapter's vector facility once on a
440
+ writable database. `prepare(db)` registers its vector shape before read-only
441
+ connections use it; the embedding service does this before storing a new batch.
442
+ While models of different widths share a table, the ordinary vector reader
443
+ scores only the requested model. Other SQL engines use the same reader or the
444
+ exclusive store's held vectors.
445
+
446
+ ## Held in memory
447
+
448
+ A process keeps a database's vectors in its memory as int8, one copy per driver,
449
+ loaded the first time a search asks for them, or before its first read where it
450
+ answers many (a read worker runs the graph facet's `preload`). Each vector is
451
+ one signed byte per coordinate, its coordinates over its own largest in 127
452
+ steps, and one float scaling them back. A search scans every held vector's
453
+ codes, then tests the best against the graph a few at a time until `RESCORE`
454
+ (100, or the limit where that is more) stand: an entity that is buried, or one
455
+ the rest of the query does not admit, is passed over for the next. Where the
456
+ rate so far says a screen admits too few to find by walking the ranking, the
457
+ screen is read whole instead. The float rows of those that stand are read in the
458
+ same statement, and they are ranked by their exact cosine, cut to the floor and
459
+ the limit.
460
+
461
+ Scaling each vector by its own largest coordinate suits an embedding model's
462
+ unit vectors: Qwen3-Embedding's largest coordinate is about 3.8 times its root
463
+ mean square and no one dimension holds it, so a step is about 1/33 of a typical
464
+ coordinate. It needs no ranges drawn from the data, so a vector codes the same
465
+ whenever it is coded. Over 1,000 queries among 1k, 10k and 25k Qwen3-Embedding
466
+ vectors of real texts, the scan alone finds 99.4% of the exact float32 top 8,
467
+ and the re-scored answer finds all of them.
468
+
469
+ A database only this process has open (a Durable Object's, or one in memory: the
470
+ driver sets no `file`) keeps its copy current by a dirty set. Whatever wrote a
471
+ vector, the dirty set names it, and a search codes what the set names from its
472
+ rows beside the copy. After each sweep pass, `absorb(db)` folds the set into
473
+ that process's copy, clears it and numbers a new build; a copy that sees a build
474
+ it did not make loads again. The answer is the one a copy loaded afresh gives,
475
+ to the last bit.
476
+
477
+ Shared storage, the file on a box other processes write too, loads its copy from
478
+ `embedding_code` once every vector has codes under one model, scaling each
479
+ vector's codes by their own length. Triggers append every vector written,
480
+ changed or deleted to `embedding_change`, whoever writes it, and a search first
481
+ folds in the changes past the last one its copy read, coding those vectors from
482
+ their floats. A copy more than `FOLLOW` (4096) changes behind, or behind what
483
+ the sweep trimmed (`absorb` keeps the newest `FOLLOW`), loads again. On the box,
484
+ 314k vectors at 384 dimensions load in about 2 s and hold 133 MB; a search over
485
+ them takes 150–180 ms and reads only the rows it rescores, where the native scan
486
+ read every code, 7 s of them from disk once the page cache had let them go.
487
+
488
+ A vector costs its width in bytes and 40 beside it: 1,064 bytes at 1024
489
+ dimensions, so 24,000 vectors hold 24 MB. Every copy in the process shares
490
+ `HELD` (48 MB of a Worker isolate's 128 MB, which every object in it shares),
491
+ and copies of shared storage share `SHARED` (512 MB of a box's process): the
492
+ least recently searched copy is dropped to make room, and a database whose
493
+ vectors alone would pass it is not held, and every search reads its vectors.
494
+
495
+ ## Storage
496
+
497
+ The vector table is:
498
+
499
+ ```sql
500
+ create table embedding (
501
+ owner integer primary key references entity(id),
502
+ model text not null,
503
+ hash text not null,
504
+ vec blob not null,
505
+ at text not null
506
+ )
507
+ ```
508
+
509
+ The primary key allows one stored vector per entity, including only one model at
510
+ a time. It is named `owner`, as are `embedding_dirty`'s and `embedding_owed`'s:
511
+ `@yaks/sqlite` takes a table keyed by an integer `entity` for a component table,
512
+ and a vector is not a component. `vec` contains packed Float32 bytes, with
513
+ dimension equal to byte length divided by four. `schema()` creates the table and
514
+ its maintenance objects idempotently; it does not migrate incompatible existing
515
+ definitions. `rekey(db)`, run before it, renames the key of tables made while it
516
+ was named `entity`.
517
+
518
+ The package assumes `@yaks/sqlite`'s integer `entity.id`, public `entity.eid`,
519
+ component owner columns, and `tombstone` table. The vector data can be rebuilt
520
+ from the selected text: after deleting its tables, recreate them with `schema()`
521
+ before running another sweep.
522
+
523
+ `vector_check` reports missing embedding configuration and hosts with no vector
524
+ table. On a shared file it warns when the native facility is not installed or
525
+ models share the table, so searches must use the ordinary reader. Old vectors do
526
+ not owe an index rebuild.
527
+
528
+ ## Exports
529
+
530
+ The root exports field selection, `Embedder`, `hashEmbedder`, `remote`,
531
+ `batched`, `retrying`, `halving`, `answered`, vector math/packing helpers, the
532
+ schema, sweep operations, native scans (`installNative`, `prepare`, `state`),
533
+ the vectors held in memory (`absorb`, `HELD`, `SHARED`, `FOLLOW`, `RESCORE`),
534
+ `vectorOf`, `nearest`, `meaning`, `semantic` and supporting types such as
535
+ `Rank`. The `Statements` capability it runs on is `@yaks/sql`'s.
536
+
537
+ | Sub-module export | Purpose |
538
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
539
+ | `@yaks/embedding/vocab` | `embeddingDoc` and `docs`, declaring `vector_check` |
540
+ | `@yaks/embedding/graph` | `plugins(host)` creates SQL objects; `extend(host, options)` creates the compiler extension; `meaning(host, options)` searches words; `reply(host, options)` answers a new entity's neighbours |
541
+ | `@yaks/embedding/service` | `service(host, options, signal)` sweeps the queue until the signal aborts |
542
+ | `@yaks/embedding/tools` | `runs(host, options)` implements `vector_check`; exports the options type |
543
+
544
+ ## Compatibility
545
+
546
+ Requires synchronous SQL statements that support blob values. The package
547
+ chooses no SQLite binding. A statement that unions a term per text field is cut
548
+ to the terms the statement capability's `arms` allows (@yaks/sql `ARMS`: a
549
+ Durable Object's SQLite takes five). Remote embedders also require `fetch`; the
550
+ offline embedder needs no network access.
@@ -0,0 +1,34 @@
1
+ import type { Bundle } from "@yaks/graph";
2
+ import { type Extension } from "@yaks/sql";
3
+ import type { Statements } from "@yaks/sql";
4
+ import { type Near, type Rank } from "./near.js";
5
+ import { type Field } from "./fields.js";
6
+ import type { ImageIndex } from "./image.js";
7
+ /** The `.order=` value that means "nearest first". */ export declare let SIMILAR: string;
8
+ /** The name of the query-only component that carries the similarity back. */ export declare let RANK: string;
9
+ /** How a `.near` neighbourhood is bounded. */ export type SemanticOpts = {
10
+ /** The configured text sources that fed the stored vectors. */ fields?: Field[];
11
+ /** how many neighbours the directive selects (default 8) */ limit?: number;
12
+ /** the similarity a neighbour must reach to be selected at all (default 0) */ floor?: number;
13
+ /** the ranking to use; the default is an exact scan over the stored vectors */ rank?: Rank;
14
+ /** The private image index in a read that has authorized its use. */ image?: () => ImageIndex | undefined;
15
+ };
16
+ /**
17
+ * The @yaks/sql extension, plus the two things a caller wants back from it: the
18
+ * neighbourhood it resolved, and the bundles with their scores attached.
19
+ */ export type Semantic = Extension & {
20
+ /** the neighbourhood the compiled `.near` selected, most similar first */ neighbours: () => Near[];
21
+ /** those bundles, nearest first, each carrying the query-only `rank` comp */ rank: (bundles: Bundle[]) => Bundle[];
22
+ };
23
+ /**
24
+ * A semantic query extension over a database's stored vectors.
25
+ *
26
+ * What it needs is the vector space, not the embedder: a `.near` anchor reads
27
+ * the vector already stored for it and never calls the network, because
28
+ * compiling a query is synchronous. Embedding text that has no entity yet is
29
+ * the sweep's job — which is why a server whose embedder is still waiting for a
30
+ * key ranks perfectly well over the vectors it already has.
31
+ */ export declare let semantic: (db: Statements, space: {
32
+ model: string;
33
+ } | null, opts?: SemanticOpts) => Semantic;
34
+ //# sourceMappingURL=compile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.d.ts","sources":["../compile.ts"],"names":[],"mappings":"AAiCA,cAAc,MAAM,2BAAgC;AACpD,SAGE,KAAK,SAAS,yBAQa;AAC7B,cAAc,UAAU,yBAA8B;AACtD,SAAS,KAAK,IAAI,EAAW,KAAK,IAAI,oBAA6B;AACnE,SAAS,KAAK,KAAK,sBAAuC;AAC1D,cAAc,UAAU,qBAAoB;AAG5C,oDAAoD,GACpD,OAAO,YAAI,gBAAmB;AAE9B,2EAA2E,GAC3E,OAAO,YAAI,aAAa;AAExB,4CAA4C,GAC5C,YAAY;EACV,6DAA6D,GAC7D,SAAS;EACT,0DAA0D,GAC1D,QAAQ,MAAM;EACd,4EAA4E,GAC5E,QAAQ,MAAM;EACd,6EAA6E,GAC7E,OAAO;EACP,mEAAmE,GACnE,cAAc,aAAa,SAAS;;AAGtC;;;CAGC,GACD,YAAY,WAAW;EACrB,wEAAwE,GACxE,kBAAkB;EAClB,2EAA2E,GAC3E,OAAO,SAAS,aAAa;;AAG/B;;;;;;;;CAQC,GACD,OAAO,YAAI,WACT,IAAI,YACJ;EAAS,OAAO,MAAM;IAAK,IAAI,EAC/B,OAAM,iBACL,SA6GF"}
package/_dist/ddl.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { type Statements, type Stmt } from "@yaks/sql";
2
+ /** The vector table's name. */ export declare let TABLE: string;
3
+ /** The exclusive cache generation. Legacy native metadata stays readable by
4
+ * older CLI processes; new searches ignore it. */ export declare let BUILD: string;
5
+ /** Vectors changed since the exclusive reader refreshed its cache. */ export declare let DIRTY: string;
6
+ /** Each vector's int8 codes, on shared storage. A row is the codes of the
7
+ * vector its owner holds now: triggers delete it when that vector changes or
8
+ * goes, so the table only ever lacks codes, and a scan uses it once it has as
9
+ * many rows as the vectors (./coded.ts). */ export declare let CODE: string;
10
+ /** The owners of the vectors that have no codes, kept by triggers on both
11
+ * tables whoever writes them, so asking whether every vector has its codes
12
+ * reads one row rather than counting both tables (./coded.ts). */ export declare let UNCODED: string;
13
+ /** Every vector written or deleted on shared storage, in the order the writes
14
+ * committed: each process's copy reads on from the last change it folded in
15
+ * (./held.ts). Triggers append to it, whoever writes, and the sweep trims all
16
+ * but the newest. */ export declare let JOURNAL: string;
17
+ /** The queue's name: one row per entity owed a look, and how many writes have
18
+ * queued it since it was last settled. */ export declare let OWED: string;
19
+ /** Durable cursors of source tables being reconciled into the queue. */ export declare let FILL: string;
20
+ /**
21
+ * Heal a store whose vector tables were made while their key was named
22
+ * `entity`: each such table has the column renamed to `owner`, which SQLite
23
+ * carries into every trigger and index that names it. Run it before
24
+ * {@link schema}. It can be deleted once every store has opened with it.
25
+ */ export declare let rekey: (db: Statements) => void;
26
+ /**
27
+ * The schema the vectors need, as ordered statements. Run them after the
28
+ * component tables exist — the table references the entity spine. Every
29
+ * statement is idempotent, so a table that already exists is left as it is.
30
+ */ export declare let schema: (ownership?: Statements['ownership']) => Stmt[];
31
+ //# sourceMappingURL=ddl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ddl.d.ts","sources":["../ddl.ts"],"names":[],"mappings":"AAMA,SAUE,KAAK,UAAU,EACf,KAAK,IAAI,yBAIkB;AAE7B,6BAA6B,GAC7B,OAAO,YAAI,cAAmB;AAE9B;gDACgD,GAChD,OAAO,YAAI,cAAyB;AAEpC,oEAAoE,GACpE,OAAO,YAAI,cAAyB;AAEpC;;;0CAG0C,GAC1C,OAAO,YAAI,aAAuB;AAElC;;gEAEgE,GAChE,OAAO,YAAI,gBAA6B;AAExC;;;mBAGmB,GACnB,OAAO,YAAI,gBAA4B;AAEvC;wCACwC,GACxC,OAAO,YAAI,aAAuB;AAElC,sEAAsE,GACtE,OAAO,YAAI,aAAuB;AA0DlC;;;;;CAKC,GACD,OAAO,YAAI,QAAS,IAAI,eAAa,IAAI,CAUxC;AAED;;;;CAIC,GACD,OAAO,YAAI,SACT,YAAW,WAAW,iBACrB,OAiEF"}