@dikolab/kbdb 0.1.6 → 0.2.0

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 (193) hide show
  1. package/README.md +30 -9
  2. package/dist/cli.cjs +181 -50
  3. package/dist/cli.cjs.map +3 -3
  4. package/dist/cli.mjs +181 -50
  5. package/dist/cli.mjs.map +3 -3
  6. package/dist/kbdb-worker.cjs +283 -29
  7. package/dist/kbdb-worker.cjs.map +4 -4
  8. package/dist/mod.cjs +13 -2
  9. package/dist/mod.cjs.map +2 -2
  10. package/dist/mod.mjs +13 -2
  11. package/dist/mod.mjs.map +2 -2
  12. package/dist/src/shared/cli/functions/format-output.function.d.ts +7 -7
  13. package/dist/src/shared/cli/functions/run-search.function.d.ts +25 -16
  14. package/dist/src/shared/cli/index.d.ts +1 -1
  15. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +2 -0
  16. package/dist/src/shared/cli/typings/search-display.model.d.ts +25 -7
  17. package/dist/src/shared/mcp/functions/handle-recall.function.d.ts +29 -0
  18. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +30 -11
  19. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  20. package/dist/src/shared/wasm-codec/functions/decode-recall-result.function.d.ts +28 -0
  21. package/dist/src/shared/wasm-codec/functions/decode-scored-results.function.d.ts +14 -7
  22. package/dist/src/shared/wasm-codec/functions/encode-recall-params.function.d.ts +21 -0
  23. package/dist/src/shared/wasm-codec/functions/encode-search-params.function.d.ts +1 -1
  24. package/dist/src/shared/wasm-codec/index.d.ts +5 -2
  25. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +13 -3
  26. package/dist/src/shared/worker-client/index.d.ts +2 -1
  27. package/dist/src/shared/worker-client/typings/recall-result.model.d.ts +94 -0
  28. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +2 -0
  29. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +23 -7
  30. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +1 -0
  31. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +18 -0
  32. package/dist/wasm/fs-database/kbdb_fs_database.js +30 -0
  33. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  34. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +2 -0
  35. package/dist/wasm/kb-worker/kbdb_worker.d.ts +38 -0
  36. package/dist/wasm/kb-worker/kbdb_worker.js +56 -0
  37. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  38. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +3 -0
  39. package/dist/worker.mjs +283 -29
  40. package/dist/worker.mjs.map +4 -4
  41. package/docs/details/README.md +26 -0
  42. package/docs/details/cli.md +608 -0
  43. package/docs/details/library-api.md +406 -0
  44. package/docs/details/mcp-server.md +430 -0
  45. package/docs/details/search-and-ranking.md +457 -0
  46. package/docs/details/storage.md +529 -0
  47. package/docs/goals/agents.md +751 -0
  48. package/docs/goals/architecture.svg +198 -0
  49. package/docs/goals/cli.md +2308 -0
  50. package/docs/goals/content-composer.md +609 -0
  51. package/docs/goals/content-parser.md +279 -0
  52. package/docs/goals/database.md +1452 -0
  53. package/docs/goals/document.md +368 -0
  54. package/docs/goals/mcp.md +1467 -0
  55. package/docs/goals/overview.md +124 -0
  56. package/docs/goals/query-parser.md +271 -0
  57. package/docs/goals/query-result.md +693 -0
  58. package/docs/goals/skills.md +738 -0
  59. package/docs/goals/worker-client.md +944 -0
  60. package/docs/goals/worker-daemon.md +1447 -0
  61. package/docs/modules/overview.md +298 -0
  62. package/docs/modules/rust/fs-database/functions/document.md +48 -0
  63. package/docs/modules/rust/fs-database/functions/integrity.md +68 -0
  64. package/docs/modules/rust/fs-database/functions/io.md +87 -0
  65. package/docs/modules/rust/fs-database/functions/module.md +22 -0
  66. package/docs/modules/rust/fs-database/functions/query-exec.md +44 -0
  67. package/docs/modules/rust/fs-database/functions/section.md +59 -0
  68. package/docs/modules/rust/fs-database/indexes/btree.md +35 -0
  69. package/docs/modules/rust/fs-database/indexes/corpus.md +61 -0
  70. package/docs/modules/rust/fs-database/indexes/inverted.md +60 -0
  71. package/docs/modules/rust/fs-database/indexes/module.md +64 -0
  72. package/docs/modules/rust/fs-database/indexes/positional.md +39 -0
  73. package/docs/modules/rust/fs-database/module.md +149 -0
  74. package/docs/modules/rust/fs-database/types/catalog.md +53 -0
  75. package/docs/modules/rust/fs-database/types/module.md +12 -0
  76. package/docs/modules/rust/fs-database/types/section.md +101 -0
  77. package/docs/modules/rust/kb-worker/functions/compose.md +57 -0
  78. package/docs/modules/rust/kb-worker/functions/module.md +20 -0
  79. package/docs/modules/rust/kb-worker/functions/retrieve.md +194 -0
  80. package/docs/modules/rust/kb-worker/functions/search.md +173 -0
  81. package/docs/modules/rust/kb-worker/functions/write.md +172 -0
  82. package/docs/modules/rust/kb-worker/module.md +171 -0
  83. package/docs/modules/rust/kb-worker/types/cache.md +90 -0
  84. package/docs/modules/rust/kb-worker/types/context.md +26 -0
  85. package/docs/modules/rust/kb-worker/types/module.md +16 -0
  86. package/docs/modules/rust/kb-worker/types/status.md +29 -0
  87. package/docs/modules/rust/kb-worker/types/token.md +50 -0
  88. package/docs/modules/rust/overview.md +495 -0
  89. package/docs/modules/rust/query-parser/functions/extract.md +56 -0
  90. package/docs/modules/rust/query-parser/functions/module.md +16 -0
  91. package/docs/modules/rust/query-parser/functions/parse.md +33 -0
  92. package/docs/modules/rust/query-parser/functions/pipeline.md +103 -0
  93. package/docs/modules/rust/query-parser/functions/rank.md +85 -0
  94. package/docs/modules/rust/query-parser/module.md +136 -0
  95. package/docs/modules/rust/query-parser/types/cache.md +39 -0
  96. package/docs/modules/rust/query-parser/types/keyphrase.md +60 -0
  97. package/docs/modules/rust/query-parser/types/module.md +17 -0
  98. package/docs/modules/rust/query-parser/types/token.md +42 -0
  99. package/docs/modules/rust/shared/content-composer/functions.md +114 -0
  100. package/docs/modules/rust/shared/content-composer/module.md +147 -0
  101. package/docs/modules/rust/shared/content-composer/types.md +93 -0
  102. package/docs/modules/rust/shared/content-parser/functions.md +72 -0
  103. package/docs/modules/rust/shared/content-parser/module.md +99 -0
  104. package/docs/modules/rust/shared/content-parser/types.md +71 -0
  105. package/docs/modules/rust/shared/corpus/module.md +24 -0
  106. package/docs/modules/rust/shared/corpus/types.md +141 -0
  107. package/docs/modules/rust/shared/document/module.md +25 -0
  108. package/docs/modules/rust/shared/document/types.md +154 -0
  109. package/docs/modules/rust/shared/encode/module.md +22 -0
  110. package/docs/modules/rust/shared/encode/traits.md +304 -0
  111. package/docs/modules/rust/shared/error/module.md +28 -0
  112. package/docs/modules/rust/shared/error/types.md +302 -0
  113. package/docs/modules/rust/shared/kbid/module.md +24 -0
  114. package/docs/modules/rust/shared/kbid/types.md +147 -0
  115. package/docs/modules/rust/shared/memory/functions.md +209 -0
  116. package/docs/modules/rust/shared/memory/module.md +24 -0
  117. package/docs/modules/rust/shared/module.md +168 -0
  118. package/docs/modules/rust/shared/query/module.md +27 -0
  119. package/docs/modules/rust/shared/query/types.md +236 -0
  120. package/docs/modules/rust/shared/section/module.md +25 -0
  121. package/docs/modules/rust/shared/section/types.md +294 -0
  122. package/docs/modules/rust/shared/term/module.md +25 -0
  123. package/docs/modules/rust/shared/term/types.md +139 -0
  124. package/docs/modules/typescript/cli.md +129 -0
  125. package/docs/modules/typescript/kbdb-worker.md +135 -0
  126. package/docs/modules/typescript/overview.md +378 -0
  127. package/docs/modules/typescript/shared/cli/constants.md +23 -0
  128. package/docs/modules/typescript/shared/cli/functions.md +630 -0
  129. package/docs/modules/typescript/shared/cli/module.md +125 -0
  130. package/docs/modules/typescript/shared/cli/typings.md +172 -0
  131. package/docs/modules/typescript/shared/hash/functions.md +20 -0
  132. package/docs/modules/typescript/shared/hash/module.md +21 -0
  133. package/docs/modules/typescript/shared/mcp/classes.md +179 -0
  134. package/docs/modules/typescript/shared/mcp/functions.md +386 -0
  135. package/docs/modules/typescript/shared/mcp/module.md +160 -0
  136. package/docs/modules/typescript/shared/mcp/typings.md +522 -0
  137. package/docs/modules/typescript/shared/module.md +94 -0
  138. package/docs/modules/typescript/shared/platform/functions.md +42 -0
  139. package/docs/modules/typescript/shared/platform/module.md +25 -0
  140. package/docs/modules/typescript/shared/runtime/functions.md +26 -0
  141. package/docs/modules/typescript/shared/runtime/module.md +27 -0
  142. package/docs/modules/typescript/shared/runtime/typings.md +13 -0
  143. package/docs/modules/typescript/shared/version/module.md +27 -0
  144. package/docs/modules/typescript/shared/wasm-codec/functions.md +391 -0
  145. package/docs/modules/typescript/shared/wasm-codec/module.md +98 -0
  146. package/docs/modules/typescript/shared/worker-client/classes.md +264 -0
  147. package/docs/modules/typescript/shared/worker-client/functions.md +175 -0
  148. package/docs/modules/typescript/shared/worker-client/module.md +84 -0
  149. package/docs/modules/typescript/shared/worker-client/typings.md +508 -0
  150. package/docs/modules/typescript/shared/worker-daemon/classes.md +239 -0
  151. package/docs/modules/typescript/shared/worker-daemon/constants.md +37 -0
  152. package/docs/modules/typescript/shared/worker-daemon/functions.md +221 -0
  153. package/docs/modules/typescript/shared/worker-daemon/module.md +112 -0
  154. package/docs/modules/typescript/shared/worker-daemon/typings.md +126 -0
  155. package/docs/overview.md +188 -0
  156. package/docs/release-notes/0.1.0.md +189 -0
  157. package/docs/release-notes/0.1.1.md +46 -0
  158. package/docs/release-notes/0.1.2.md +38 -0
  159. package/docs/release-notes/0.1.3.md +42 -0
  160. package/docs/release-notes/0.2.0.md +147 -0
  161. package/docs/release-notes/README.md +9 -0
  162. package/package.json +8 -2
  163. package/src/shared/cli/functions/dispatch-command.function.ts +3 -3
  164. package/src/shared/cli/functions/format-output.function.ts +41 -34
  165. package/src/shared/cli/functions/parse-args.function.ts +7 -0
  166. package/src/shared/cli/functions/run-search.function.ts +53 -27
  167. package/src/shared/cli/index.ts +4 -1
  168. package/src/shared/cli/typings/cli-options.interface.ts +2 -0
  169. package/src/shared/cli/typings/search-display.model.ts +26 -7
  170. package/src/shared/mcp/functions/create-tool-definitions.function.ts +64 -4
  171. package/src/shared/mcp/functions/handle-recall.function.ts +66 -0
  172. package/src/shared/mcp/functions/handle-tool-call.function.ts +11 -1
  173. package/src/shared/mcp/typings/mcp-client.interface.ts +33 -15
  174. package/src/shared/version/constants/version.constant.ts +1 -1
  175. package/src/shared/wasm-codec/functions/decode-recall-result.function.ts +267 -0
  176. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +81 -27
  177. package/src/shared/wasm-codec/functions/encode-recall-params.function.ts +68 -0
  178. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +4 -1
  179. package/src/shared/wasm-codec/index.ts +11 -3
  180. package/src/shared/worker-client/classes/worker-client.class.ts +24 -4
  181. package/src/shared/worker-client/index.ts +11 -1
  182. package/src/shared/worker-client/typings/recall-result.model.ts +98 -0
  183. package/src/shared/worker-client/typings/search-params.model.ts +2 -0
  184. package/src/shared/worker-client/typings/search-result.model.ts +24 -7
  185. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +25 -4
  186. package/src/wasm/fs-database/kbdb_fs_database.d.ts +18 -0
  187. package/src/wasm/fs-database/kbdb_fs_database.js +30 -0
  188. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  189. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +2 -0
  190. package/src/wasm/kb-worker/kbdb_worker.d.ts +38 -0
  191. package/src/wasm/kb-worker/kbdb_worker.js +56 -0
  192. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  193. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +3 -0
@@ -0,0 +1,194 @@
1
+ # functions::retrieve -- Read & Status Orchestration
2
+
3
+ *Read sections and documents from cache or disk.
4
+ Report database status.*
5
+
6
+ ## Source
7
+
8
+ `engine/crates/kb-worker/src/orchestrate/retrieve.rs`
9
+
10
+ ## Exported WASM Functions
11
+
12
+ ### `worker_read_sections`
13
+
14
+ ```rust
15
+ pub fn worker_read_sections(
16
+ kbid_ptr: *const u8,
17
+ kbid_len: u32,
18
+ ) -> u64;
19
+ ```
20
+
21
+ Read one or more sections by KbId. Returns Encode'd
22
+ `Vec<SectionRecord>`.
23
+
24
+ ### `worker_retrieve_doc`
25
+
26
+ ```rust
27
+ pub fn worker_retrieve_doc(
28
+ doc_id_ptr: *const u8,
29
+ doc_id_len: u32,
30
+ ) -> u64;
31
+ ```
32
+
33
+ Read a document manifest and all its sections.
34
+ Returns Encode'd `DocumentRecord`.
35
+
36
+ ### `worker_status`
37
+
38
+ ```rust
39
+ pub fn worker_status() -> u64;
40
+ ```
41
+
42
+ Returns Encode'd `StatusResult` (see
43
+ [types/status](../types/status.md)).
44
+
45
+ ### `worker_result_status`
46
+
47
+ ```rust
48
+ pub fn worker_result_status(
49
+ token_ptr: *const u8,
50
+ token_len: u32,
51
+ ) -> u32;
52
+ ```
53
+
54
+ Poll an async token. Returns `0` = busy,
55
+ `1` = success, `2` = fail.
56
+
57
+ ### `worker_get_result`
58
+
59
+ ```rust
60
+ pub fn worker_get_result(
61
+ token_ptr: *const u8,
62
+ token_len: u32,
63
+ ) -> u64;
64
+ ```
65
+
66
+ Fetch the result buffer for a completed token.
67
+ Returns `(ptr, len)`. Consumes the token (one-shot).
68
+
69
+ ### `worker_invalidate`
70
+
71
+ ```rust
72
+ pub fn worker_invalidate(
73
+ keys_ptr: *const u8,
74
+ keys_len: u32,
75
+ ) -> u32;
76
+ ```
77
+
78
+ Evict specific cache entries. Returns count evicted.
79
+
80
+ ### `worker_invalidate_all`
81
+
82
+ ```rust
83
+ pub fn worker_invalidate_all() -> u32;
84
+ ```
85
+
86
+ Evict entire cache. Returns count evicted.
87
+
88
+ ## `worker_recall` -- Progressive Context Expansion
89
+
90
+ ```rust
91
+ pub fn worker_recall(
92
+ params_ptr: *const u8,
93
+ params_len: u32,
94
+ ) -> u64;
95
+ ```
96
+
97
+ WASM export for the `recall` IPC method. Accepts
98
+ a serialized `RecallParams` (kbid or kbids array,
99
+ depth 0--3). Returns serialized `RecallResult`
100
+ (single) or `RecallResult[]` (batch) via the shared
101
+ memory return slot.
102
+
103
+ ### Recall Flow
104
+
105
+ ```
106
+ 1. Receive kbid(s) + depth
107
+ |
108
+ 2. For each kbid: read section from cache
109
+ (disk fallback)
110
+ -> SectionRecord with heading, type, docids,
111
+ content
112
+ |
113
+ 3. If depth == 0: return section data
114
+ |
115
+ 4. If depth >= 1: for each docid in section's
116
+ docids, read document manifest -> list of all
117
+ section kbids with headings and types.
118
+ Query references.idx for back-references
119
+ (entries where target_id == kbid and
120
+ direction == back).
121
+ |
122
+ 5. If depth >= 2: read full content of sibling
123
+ sections (other sections in the same documents).
124
+ Query references.idx for forward references
125
+ (entries where source_kbid == kbid and
126
+ direction == forward).
127
+ |
128
+ 6. If depth >= 3: for each forward-referenced
129
+ section, read its full content. Query
130
+ references.idx for their back-references.
131
+ |
132
+ Return RecallResult(s) via shared memory
133
+ ```
134
+
135
+ **Cache interaction:** Recall is read-heavy and
136
+ benefits from the LRU cache. Section reads at
137
+ depth 0 hit the cache populated by recent searches.
138
+ Sibling and reference reads at depth 2--3 may cause
139
+ cache misses on first access.
140
+
141
+ **Reference graph lookup:** Forward and back
142
+ references are read from `references.idx` via
143
+ `fs-database.wasm` index lookup functions. This is
144
+ O(1) per kbid via the B+ tree index -- no content
145
+ re-parsing needed.
146
+
147
+ ---
148
+
149
+ ## Retrieve Flow
150
+
151
+ ```
152
+ 1. Receive KbId
153
+
154
+ 2. Check cache → hit? → return cached
155
+ ↓ miss
156
+ 3. db_read_section → SectionRecord from disk
157
+
158
+ 4. Put into cache
159
+
160
+ Return SectionRecord
161
+ ```
162
+
163
+ Document retrieval follows the same pattern but calls
164
+ `db_read_document` and caches the manifest separately
165
+ from individual sections.
166
+
167
+ ## Maintenance Exports
168
+
169
+ ### `worker_check_integrity`
170
+
171
+ ```rust
172
+ pub fn worker_check_integrity() -> u64;
173
+ ```
174
+
175
+ Delegates to `db_check_integrity`. Returns Encode'd
176
+ `IntegrityReport`.
177
+
178
+ ### `worker_garbage_collect`
179
+
180
+ ```rust
181
+ pub fn worker_garbage_collect() -> u64;
182
+ ```
183
+
184
+ Delegates to `db_garbage_collect`. Returns count of
185
+ removed orphans.
186
+
187
+ ### `worker_rebuild_indexes`
188
+
189
+ ```rust
190
+ pub fn worker_rebuild_indexes() -> u64;
191
+ ```
192
+
193
+ Delegates to `db_index_rebuild`. Invalidates entire
194
+ cache afterward.
@@ -0,0 +1,173 @@
1
+ # functions::search -- Search Orchestration
2
+
3
+ *End-to-end search flow: query string in, ranked
4
+ results out.*
5
+
6
+ ## Source
7
+
8
+ `engine/crates/kb-worker/src/orchestrate/search.rs`
9
+
10
+ ## Exported WASM Functions
11
+
12
+ ### `worker_search`
13
+
14
+ ```rust
15
+ pub fn worker_search(
16
+ query_ptr: *const u8,
17
+ query_len: u32,
18
+ limit: u32,
19
+ ) -> u64;
20
+ ```
21
+
22
+ Synchronous search. Returns `(ptr, len)` packed into
23
+ `u64`. The result buffer contains Encode'd ranked
24
+ matches.
25
+
26
+ ### `worker_query`
27
+
28
+ ```rust
29
+ pub fn worker_query(
30
+ query_ptr: *const u8,
31
+ query_len: u32,
32
+ limit: u32,
33
+ ) -> u64;
34
+ ```
35
+
36
+ Async search. Returns a `(ptr, len)` token string.
37
+ Poll with `worker_result_status`, fetch with
38
+ `worker_get_result`.
39
+
40
+ ## Search Flow (13 Steps)
41
+
42
+ ```
43
+ 1. Receive query string from TypeScript IPC
44
+
45
+ 2. qp_tokenize → token stream
46
+
47
+ 3. qp_parse_query → QueryPlan
48
+
49
+ 4. db_execute_plan → Vec<RawMatch>
50
+
51
+ 5. db_corpus_stats → CorpusStats
52
+
53
+ 6. qp_score_bm25f → base scores
54
+
55
+ 7. qp_score_proximity → proximity boost
56
+
57
+ 8. qp_score_zone → zone/field boost
58
+
59
+ 9. Sort by combined score descending
60
+
61
+ 10. Apply offset: skip first `offset` entries
62
+
63
+ 11. Truncate to `limit`
64
+
65
+ 12. Shape results: for each scored section, read
66
+ heading, type, and docids from the section
67
+ header; generate KWIC snippet (~150 chars
68
+ centered on the highest-scoring matched term
69
+ position from the positional index)
70
+
71
+ 13. Build paged envelope: wrap shaped items with
72
+ `total` (pre-offset/limit count), `offset`,
73
+ `limit`, `has_more`
74
+
75
+ Return PagedSearchResult via shared memory
76
+ ```
77
+
78
+ ### Step Details
79
+
80
+ 1. **Receive query** -- TypeScript writes the UTF-8
81
+ query into shared memory and calls
82
+ `worker_search(ptr, len, limit)`.
83
+
84
+ 2. **Tokenize** -- Calls `qp_tokenize` from
85
+ query-parser. Produces a `TokenStream` with
86
+ normalized, stemmed tokens.
87
+
88
+ 3. **Parse** -- Calls `qp_parse_query`. Interprets
89
+ boolean operators, phrase markers, field
90
+ qualifiers. Produces a `QueryPlan`.
91
+
92
+ 4. **Execute plan** -- Calls `db_execute_plan` from
93
+ fs-database. Walks the inverted index and
94
+ positional index. Returns `Vec<RawMatch>` with
95
+ per-field TFs (`field_tfs`), positions,
96
+ `token_count`, and `field_token_counts` per
97
+ matching section.
98
+
99
+ 5. **Corpus stats** -- Calls `db_corpus_stats`. Gets
100
+ document count, term frequencies for IDF
101
+ computation, and per-field average lengths
102
+ (`avg_heading_length`, `avg_body_length`,
103
+ `avg_code_length`) for BM25F normalization.
104
+
105
+ 6. **BM25F** -- Calls `qp_score_bm25f`. Computes
106
+ per-field BM25 using `FieldTf` values from each
107
+ `RawMatch` and per-field corpus averages. Field
108
+ weights (heading 2.0x, body 1.0x, code 1.5x) are
109
+ applied at query time. See
110
+ [Query Result](../../../../goals/query-result.md)
111
+ for the full scoring specification.
112
+
113
+ 7. **Proximity** -- Calls `qp_score_proximity`.
114
+ Boosts documents where query terms appear close
115
+ together.
116
+
117
+ 8. **Zone scoring** -- Calls `qp_score_zone`. Boosts
118
+ matches in high-value zones (title, headings,
119
+ first paragraph).
120
+
121
+ 9. **Sort** -- Combines all scores, sorts descending.
122
+
123
+ 10. **Apply offset** -- Skips the first `offset`
124
+ entries from the sorted result list. Enables
125
+ cursor-based pagination without re-executing the
126
+ query.
127
+
128
+ 11. **Truncate** -- Takes at most `limit` entries
129
+ from the offset-adjusted list.
130
+
131
+ 12. **Shape results** -- For each scored section,
132
+ reads heading, type, and docids from the section
133
+ header. Generates a KWIC snippet (~150 chars
134
+ centered on the highest-scoring matched term
135
+ position from the positional index). See
136
+ [Snippet Generation](#snippet-generation) below.
137
+
138
+ 13. **Build paged envelope** -- Wraps shaped items
139
+ with `total` (pre-offset/limit count), `offset`,
140
+ `limit`, and `has_more`. Encodes as
141
+ `PagedSearchResult` via the `Encode` trait into
142
+ shared memory.
143
+
144
+ ---
145
+
146
+ ### Snippet Generation
147
+
148
+ Snippets are generated during step 12 (result
149
+ shaping), using data already available from the
150
+ search pipeline:
151
+
152
+ - The positional index provides the token offset
153
+ of each matched term in each section.
154
+ - The section content is read from cache (or disk
155
+ fallback).
156
+
157
+ **Algorithm:**
158
+
159
+ 1. For each matched section, find the position of
160
+ the highest-scoring matched term (the term with
161
+ the highest BM25F contribution).
162
+ 2. Convert the token position to a byte offset in
163
+ the section content.
164
+ 3. Extract ~150 characters centered on that byte
165
+ offset. If the offset is near the start or end,
166
+ shift the window accordingly.
167
+ 4. Trim to word boundaries and add `...` ellipsis
168
+ at truncated boundaries.
169
+ 5. If the highest-scoring match is in the heading
170
+ (not body), use the first ~150 characters of
171
+ the body content instead.
172
+ 6. For image sections (`image/*`) or sections with
173
+ no body content, the snippet is empty string.
@@ -0,0 +1,172 @@
1
+ # functions::write -- Write Orchestration
2
+
3
+ *Add, update, and remove operations for text, code,
4
+ and image sections.*
5
+
6
+ ## Source
7
+
8
+ `engine/crates/kb-worker/src/orchestrate/write.rs`
9
+
10
+ ## Exported WASM Functions
11
+
12
+ ### `worker_add_section`
13
+
14
+ ```rust
15
+ pub fn worker_add_section(
16
+ params_ptr: *const u8,
17
+ params_len: u32,
18
+ ) -> u64;
19
+ ```
20
+
21
+ Params buffer contains Encode'd `AddSectionParams`.
22
+ Returns `(ptr, len)` with the new `KbId`.
23
+
24
+ ### `worker_update_section`
25
+
26
+ ```rust
27
+ pub fn worker_update_section(
28
+ params_ptr: *const u8,
29
+ params_len: u32,
30
+ ) -> u64;
31
+ ```
32
+
33
+ ### `worker_remove_section`
34
+
35
+ ```rust
36
+ pub fn worker_remove_section(
37
+ kbid_ptr: *const u8,
38
+ kbid_len: u32,
39
+ ) -> u64;
40
+ ```
41
+
42
+ ### `worker_group_sections`
43
+
44
+ ```rust
45
+ pub fn worker_group_sections(
46
+ params_ptr: *const u8,
47
+ params_len: u32,
48
+ ) -> u64;
49
+ ```
50
+
51
+ Creates a document manifest grouping multiple
52
+ sections.
53
+
54
+ ### `worker_remove_grouping`
55
+
56
+ ```rust
57
+ pub fn worker_remove_grouping(
58
+ doc_id_ptr: *const u8,
59
+ doc_id_len: u32,
60
+ ) -> u64;
61
+ ```
62
+
63
+ ## Add Flow (Text)
64
+
65
+ ```
66
+ 1. Receive content + metadata via shared memory
67
+
68
+ 2. Per-field tokenization:
69
+ - title → qp_tokenize → heading tokens
70
+ - body + description → qp_tokenize → body tokens
71
+
72
+ 3. qp_extract_keywords → Vec<Keyphrase>
73
+
74
+ 4. qp_compute_field_tf → per-field TFs + token counts
75
+
76
+ 5. db_add_section → KbId (content-addressed)
77
+ (includes title, description, and 4 token counts
78
+ in section header)
79
+
80
+ 6. db_index_add → update inverted (per-field TFs)
81
+ + positional index
82
+
83
+ 7. Invalidate cache entries for affected terms
84
+
85
+ Return AddSectionResult
86
+ ```
87
+
88
+ ## Add Flow (Code)
89
+
90
+ ```
91
+ 1. Receive source code + language tag
92
+
93
+ 2. Per-field tokenization:
94
+ - title → qp_tokenize → heading tokens
95
+ - description → qp_tokenize → body tokens
96
+ - code content → qp_split_identifiers
97
+ + qp_tokenize → code tokens
98
+
99
+ 3. Merge identifier tokens + content tokens
100
+
101
+ 4. qp_extract_keywords → Vec<Keyphrase>
102
+
103
+ 5. qp_compute_field_tf → per-field TFs + token counts
104
+
105
+ 6-8. Same as text flow (store, index, cache)
106
+ ```
107
+
108
+ Code sections use `qp_split_identifiers` to split
109
+ camelCase and snake_case identifiers into searchable
110
+ terms before merging with tokens from comments and
111
+ string literals. Code content feeds the code field;
112
+ title feeds the heading field; description feeds the
113
+ body field.
114
+
115
+ ## Add Flow (Image)
116
+
117
+ ```
118
+ 1. Receive image binary + title (required)
119
+ + description (optional)
120
+
121
+ 2. Per-field tokenization:
122
+ - title → qp_tokenize → heading tokens (2.0x)
123
+ - description → qp_tokenize → body tokens (1.0x)
124
+
125
+ 3. qp_compute_field_tf → per-field TFs + token counts
126
+
127
+ 4. db_add_section → KbId (hash of binary)
128
+ (includes title, description, and 4 token counts
129
+ in section header)
130
+
131
+ 5. db_index_add → index title/description terms
132
+ with per-field TFs
133
+
134
+ Return AddSectionResult
135
+ ```
136
+
137
+ Image binary is stored as-is and not indexed.
138
+ Title (required) is tokenized into the heading
139
+ field and description (optional) into the body
140
+ field. Validation: image sections require a title.
141
+
142
+ ## Update Flow
143
+
144
+ ```
145
+ 1. Receive KbId + new content
146
+
147
+ 2. db_index_remove → remove old index entries
148
+
149
+ 3. Re-run the appropriate add flow (text/code/image)
150
+
151
+ 4. db_update_section → overwrite content
152
+
153
+ 5. Invalidate cache for old + new terms
154
+ ```
155
+
156
+ Update is delete-old-indexes + re-add. The KbId may
157
+ change if content changes (content-addressed), so the
158
+ caller receives the new KbId.
159
+
160
+ ## Remove Flow
161
+
162
+ ```
163
+ 1. Receive KbId
164
+
165
+ 2. db_index_remove → remove all index entries
166
+
167
+ 3. db_remove_section → delete content file
168
+
169
+ 4. Invalidate cache for removed KbId
170
+
171
+ Return success/failure
172
+ ```
@@ -0,0 +1,171 @@
1
+ # kb-worker -- Worker Orchestration and Cache
2
+
3
+ *Rust crate that imports query-parser and fs-database,
4
+ orchestrates all database operations, and manages the
5
+ in-memory LRU cache. Compiles to `kb-worker.wasm`.*
6
+
7
+ ## Crate
8
+
9
+ | Field | Value |
10
+ |-------------|------------------------------------|
11
+ | Name | `kbdb-worker` |
12
+ | Path | `engine/crates/kb-worker/` |
13
+ | Crate type | `cdylib` (WASM) + `rlib` (tests) |
14
+ | WASM output | `dist/wasm/kb-worker.wasm` |
15
+ | Depends on | `kbdb-shared`, `kbdb-query-parser`, `kbdb-fs-database` |
16
+
17
+ `kbdb-worker` is the **top-level** WASM module. It
18
+ imports both `query-parser.wasm` and
19
+ `fs-database.wasm` and sits between the TypeScript
20
+ IPC layer and the two standalone modules.
21
+
22
+ ```
23
+ query-parser.wasm fs-database.wasm
24
+ (standalone) (standalone)
25
+ ↑ ↑
26
+ └────────┬───────────┘
27
+ |
28
+ kb-worker.wasm
29
+ (imports both, orchestrates)
30
+
31
+ |
32
+ src/worker.ts
33
+ (TypeScript daemon, loads this module)
34
+ ```
35
+
36
+ See [Worker Daemon](../../../goals/worker-daemon.md)
37
+ for the full behavioral specification.
38
+
39
+ ## Workspace Position
40
+
41
+ ```
42
+ engine/
43
+ ├── Cargo.toml # workspace root
44
+ └── crates/
45
+ ├── shared/ # kbdb-shared
46
+ ├── fs-database/ # kbdb-fs-database
47
+ ├── query-parser/ # kbdb-query-parser
48
+ └── kb-worker/ # this crate
49
+ ```
50
+
51
+ ## Directory Layout
52
+
53
+ ```
54
+ engine/crates/kb-worker/
55
+ ├── Cargo.toml
56
+ └── src/
57
+ ├── lib.rs # crate root, WASM exports
58
+ ├── mem.rs # shared-memory helpers
59
+ ├── context.rs # database context init
60
+ ├── orchestrate/
61
+ │ ├── mod.rs # dispatch facade
62
+ │ ├── search.rs # search flow
63
+ │ ├── write.rs # write flow
64
+ │ └── retrieve.rs # read flow
65
+ ├── cache/
66
+ │ ├── mod.rs # cache facade
67
+ │ ├── lru.rs # LRU data structure
68
+ │ ├── entry.rs # cache entry with TTL
69
+ │ └── config.rs # cache configuration
70
+ ├── token.rs # result token management
71
+ └── status.rs # status reporting
72
+ ```
73
+
74
+ ## Modules
75
+
76
+ ### [types/](types/module.md) -- Structs
77
+
78
+ - **[context](types/context.md)** -- `Context` struct.
79
+ Database context initialization.
80
+ - **[cache](types/cache.md)** -- `Cache`,
81
+ `CacheConfig`, `CacheEntry`, `CacheStats`,
82
+ `LruCache`.
83
+ - **[token](types/token.md)** -- `TokenStore`,
84
+ `TokenEntry`, `TokenStatus`. Async result token
85
+ management.
86
+ - **[status](types/status.md)** -- `StatusResult`.
87
+
88
+ ### [functions/](functions/module.md) -- Orchestration
89
+
90
+ - **[search](functions/search.md)** -- Search flow:
91
+ parse → lookup → rank.
92
+ - **[write](functions/write.md)** -- Write flow:
93
+ tokenize → store → index (text/code/image).
94
+ - **[retrieve](functions/retrieve.md)** -- Read flow:
95
+ cache check → disk read. Status reporting.
96
+ - **[compose](functions/compose.md)** -- Content
97
+ composition flow: resolve → fetch → compose.
98
+
99
+ ## WASM Exports
100
+
101
+ | Export | Description |
102
+ |---------------------------|--------------------------|
103
+ | `worker_init` | Initialize context |
104
+ | `worker_search` | Full search flow |
105
+ | `worker_add_section` | Full add flow |
106
+ | `worker_update_section` | Full update flow |
107
+ | `worker_remove_section` | Full remove flow |
108
+ | `worker_read_sections` | Read sections by kb-id |
109
+ | `worker_retrieve_doc` | Read document + sections |
110
+ | `worker_group_sections` | Create document grouping |
111
+ | `worker_remove_grouping` | Remove document grouping |
112
+ | `worker_status` | Database + cache status |
113
+ | `worker_query` | Async query (returns token) |
114
+ | `worker_result_status` | Poll token status |
115
+ | `worker_get_result` | Fetch result by token |
116
+ | `worker_invalidate` | Evict cache entries |
117
+ | `worker_invalidate_all` | Evict entire cache |
118
+ | `worker_compose` | Content composition flow |
119
+ | `worker_check_integrity` | Run integrity checks |
120
+ | `worker_garbage_collect` | Remove orphaned sections |
121
+ | `worker_rebuild_indexes` | Full index rebuild |
122
+ | `worker_recall` | Progressive context expansion (recall) |
123
+ | `alloc` / `free` | Memory management (from `kbdb-shared`) |
124
+
125
+ ## WASM Imports
126
+
127
+ **From `query-parser.wasm`:** `qp_tokenize`,
128
+ `qp_parse_query`, `qp_extract_keywords`,
129
+ `qp_compute_tf`, `qp_compute_field_tf`,
130
+ `qp_compute_tfidf`,
131
+ `qp_score_bm25f`, `qp_score_proximity`,
132
+ `qp_score_zone`, `qp_score_freshness`,
133
+ `qp_split_identifiers`.
134
+
135
+ **From `fs-database.wasm`:** `db_init`,
136
+ `db_read_section`, `db_read_sections`,
137
+ `db_add_section`, `db_update_section`,
138
+ `db_remove_section`, `db_read_document`,
139
+ `db_write_document`, `db_remove_document`,
140
+ `db_update_section_ref`, `db_index_add`,
141
+ `db_index_remove`, `db_index_rebuild`,
142
+ `db_execute_plan`, `db_corpus_stats`, `db_status`,
143
+ `db_check_integrity`, `db_garbage_collect`.
144
+
145
+ ## Dependencies
146
+
147
+ ```toml
148
+ [dependencies]
149
+ kbdb-shared = { path = "../shared" }
150
+ kbdb-query-parser = { path = "../query-parser" }
151
+ kbdb-fs-database = { path = "../fs-database" }
152
+ ```
153
+
154
+ ## Build
155
+
156
+ ```sh
157
+ cd engine
158
+ wasm-pack build crates/kb-worker \
159
+ --target no-modules \
160
+ --out-dir ../../../dist/wasm/kb-worker
161
+ ```
162
+
163
+ Build order: `kbdb-shared` → `kbdb-query-parser` +
164
+ `kbdb-fs-database` (parallel) → `kbdb-worker`.
165
+
166
+ ## Testing
167
+
168
+ ```sh
169
+ cd engine && cargo test -p kbdb-worker
170
+ cd engine && wasm-pack test --node crates/kb-worker
171
+ ```