@gmickel/gno 2.15.0 → 2.17.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -19,6 +19,11 @@ import { ChunkingPolicyConflictError } from "../chunking";
19
19
  const TARGET_KEY = "chunking_policy_v1";
20
20
  const LAYOUT_PREFIX = "chunking_mirror_v1:";
21
21
 
22
+ const chunkingTargetCache = new WeakMap<
23
+ Database,
24
+ { raw: string; token: ChunkingPolicyToken }
25
+ >();
26
+
22
27
  export function readChunkingTarget(db: Database): ChunkingPolicyToken {
23
28
  const row = db
24
29
  .query<{ value: string }, [string]>(
@@ -26,6 +31,13 @@ export function readChunkingTarget(db: Database): ChunkingPolicyToken {
26
31
  )
27
32
  .get(TARGET_KEY);
28
33
  if (!row) return { params: { ...DEFAULT_CHUNKING_PARAMS }, generation: 0 };
34
+ const cached = chunkingTargetCache.get(db);
35
+ if (cached && cached.raw === row.value) {
36
+ return {
37
+ params: { ...cached.token.params },
38
+ generation: cached.token.generation,
39
+ };
40
+ }
29
41
  const parsed: unknown = JSON.parse(row.value);
30
42
  if (
31
43
  !parsed ||
@@ -38,10 +50,12 @@ export function readChunkingTarget(db: Database): ChunkingPolicyToken {
38
50
  ) {
39
51
  throw new Error("Invalid stored chunking policy");
40
52
  }
41
- return {
53
+ const token: ChunkingPolicyToken = {
42
54
  params: ChunkingConfigSchema.parse(parsed.params),
43
55
  generation: parsed.generation,
44
56
  };
57
+ chunkingTargetCache.set(db, { raw: row.value, token });
58
+ return { params: { ...token.params }, generation: token.generation };
45
59
  }
46
60
 
47
61
  export function assertChunkingTarget(
@@ -3,9 +3,17 @@ import type { Database } from "bun:sqlite";
3
3
  import type { DocumentEligibilityOptions } from "../types";
4
4
 
5
5
  import { TYPED_METADATA_INGEST_VERSION } from "../../core/typed-metadata";
6
- import { matchesExcludedText } from "../../pipeline/exclude";
7
6
  import { compileMetadataPredicate } from "./metadata-predicate";
8
7
 
8
+ function containsLowerTerm(haystack: string, lowerTerms: string[]): boolean {
9
+ if (!haystack) return false;
10
+ const lowered = haystack.toLowerCase();
11
+ for (const term of lowerTerms) {
12
+ if (lowered.includes(term)) return true;
13
+ }
14
+ return false;
15
+ }
16
+
9
17
  /** Unbounded owner selection; compose with FTS rowids or chunk mirror ownership
10
18
  * before ranking/LIMIT. EXISTS keeps multiple tags/scopes from duplicating owners.
11
19
  * Retains store filter semantics; lexical runtime language remains reserved. */
@@ -35,11 +43,10 @@ export function buildEligibleDocumentQuery(
35
43
 
36
44
  // tagsAny: document has at least one of these tags
37
45
  if (options.tagsAny && options.tagsAny.length > 0) {
38
- const placeholders = options.tagsAny.map(() => "?").join(",");
39
46
  conditions.push(
40
- `EXISTS (SELECT 1 FROM doc_tags dt WHERE dt.document_id = d.id AND dt.tag IN (${placeholders}))`
47
+ "EXISTS (SELECT 1 FROM doc_tags dt WHERE dt.document_id = d.id AND dt.tag IN (SELECT value FROM json_each(?)))"
41
48
  );
42
- params.push(...options.tagsAny);
49
+ params.push(JSON.stringify(options.tagsAny));
43
50
  }
44
51
 
45
52
  // tagsAll: document has all of these tags
@@ -65,11 +72,11 @@ export function buildEligibleDocumentQuery(
65
72
  options.categories &&
66
73
  options.categories.length > 0
67
74
  ) {
68
- const placeholders = options.categories.map(() => "?").join(",");
75
+ const categoriesJson = JSON.stringify(options.categories);
69
76
  conditions.push(
70
- `(d.content_type IN (${placeholders}) OR EXISTS (SELECT 1 FROM json_each(COALESCE(d.categories, '[]')) jc WHERE jc.value IN (${placeholders})))`
77
+ "(d.content_type IN (SELECT value FROM json_each(?)) OR EXISTS (SELECT 1 FROM json_each(COALESCE(d.categories, '[]')) jc WHERE jc.value IN (SELECT value FROM json_each(?))))"
71
78
  );
72
- params.push(...options.categories, ...options.categories);
79
+ params.push(categoriesJson, categoriesJson);
73
80
  }
74
81
  if (!options.semanticMetadata && options.author) {
75
82
  conditions.push("LOWER(COALESCE(d.author, '')) LIKE ?");
@@ -105,89 +112,122 @@ export function buildEligibleDocumentQuery(
105
112
  );
106
113
  }
107
114
  if (options.memoryScopesAny?.length) {
108
- const placeholders = options.memoryScopesAny.map(() => "?").join(",");
109
115
  conditions.push(
110
- `EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (${placeholders}))`
116
+ "EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (SELECT value FROM json_each(?)))"
111
117
  );
112
- params.push(...options.memoryScopesAny);
118
+ params.push(JSON.stringify(options.memoryScopesAny));
113
119
  }
114
120
  if (options.excludeSuperseded) {
115
121
  conditions.push(
116
122
  "NOT EXISTS (SELECT 1 FROM doc_edges se JOIN documents sd ON sd.id = se.src_doc_id AND sd.active = 1 WHERE se.dst_doc_id = d.id AND se.edge_type = 'supersedes')"
117
123
  );
118
124
  }
125
+ const hasExclude = Boolean(options.exclude?.length);
119
126
  if (
120
- options.exclude?.length ||
127
+ hasExclude ||
121
128
  (options.semanticMetadata && (options.author || options.categories?.length))
122
129
  ) {
123
130
  if (!db)
124
131
  throw new Error("Exclusion eligibility requires document metadata");
125
- // One bulk read, preserving JavaScript Unicode case folding and exclusions
126
- // across every chunk, including chunks outside a later language selection.
127
- const rows = db
128
- .query<
129
- {
130
- id: number;
131
- title: string | null;
132
- path: string;
133
- text: string | null;
134
- author: string | null;
135
- content_type: string | null;
136
- categories: string | null;
137
- },
138
- (string | number)[]
139
- >(`
140
- SELECT d.id, d.title, d.author, d.content_type, d.categories, COALESCE(d.record_source_path, d.rel_path) AS path, cc.text
141
- FROM documents d${hashPin} LEFT JOIN content_chunks cc ON cc.mirror_hash = d.mirror_hash
142
- WHERE ${conditions.join(" AND ")}
143
- `)
144
- .iterate(...params);
132
+ const lowerAuthor = options.author?.toLowerCase();
133
+ const wantedCategories = options.categories?.length
134
+ ? new Set(options.categories.map((value) => value.toLowerCase()))
135
+ : null;
136
+ const lowerExcludes = hasExclude
137
+ ? options.exclude!.map((term) => term.toLowerCase())
138
+ : null;
139
+ const needsCategories = Boolean(
140
+ options.semanticMetadata || options.excludeMetadata
141
+ );
142
+
143
+ // Omit content_chunks join when no text exclusions are requested; check
144
+ // document-level metadata once per document and short-circuit denied docs.
145
+ const sql = hasExclude
146
+ ? `SELECT d.id, d.title, d.author, d.content_type, d.categories, COALESCE(d.record_source_path, d.rel_path) AS path, cc.text
147
+ FROM documents d${hashPin} LEFT JOIN content_chunks cc ON cc.mirror_hash = d.mirror_hash
148
+ WHERE ${conditions.join(" AND ")}`
149
+ : `SELECT d.id, d.title, d.author, d.content_type, d.categories, COALESCE(d.record_source_path, d.rel_path) AS path, NULL AS text
150
+ FROM documents d${hashPin}
151
+ WHERE ${conditions.join(" AND ")}`;
152
+
153
+ const stmt = db.prepare<
154
+ {
155
+ id: number;
156
+ title: string | null;
157
+ path: string;
158
+ text: string | null;
159
+ author: string | null;
160
+ content_type: string | null;
161
+ categories: string | null;
162
+ },
163
+ (string | number)[]
164
+ >(sql);
145
165
  const denied = new Set<number>();
146
- for (const row of rows) {
147
- const categories: unknown =
148
- options.semanticMetadata || options.excludeMetadata
149
- ? JSON.parse(row.categories ?? "[]")
150
- : [];
151
- if (
152
- !Array.isArray(categories) ||
153
- !categories.every((value): value is string => typeof value === "string")
154
- ) {
155
- denied.add(row.id);
156
- continue;
157
- }
158
- if (options.semanticMetadata) {
159
- const wanted = options.categories?.map((value) => value.toLowerCase());
166
+ const checkedDocs = new Set<number>();
167
+ try {
168
+ for (const row of stmt.iterate(...params)) {
169
+ if (denied.has(row.id)) continue;
170
+ if (!checkedDocs.has(row.id)) {
171
+ checkedDocs.add(row.id);
172
+ let categories: string[] = [];
173
+ if (needsCategories) {
174
+ const parsed: unknown = JSON.parse(row.categories ?? "[]");
175
+ if (
176
+ !Array.isArray(parsed) ||
177
+ !parsed.every(
178
+ (value): value is string => typeof value === "string"
179
+ )
180
+ ) {
181
+ denied.add(row.id);
182
+ continue;
183
+ }
184
+ categories = parsed;
185
+ }
186
+ if (options.semanticMetadata) {
187
+ if (
188
+ (lowerAuthor &&
189
+ !(row.author ?? "").toLowerCase().includes(lowerAuthor)) ||
190
+ (wantedCategories &&
191
+ !wantedCategories.has((row.content_type ?? "").toLowerCase()) &&
192
+ !categories.some((value) =>
193
+ wantedCategories.has(value.toLowerCase())
194
+ ))
195
+ ) {
196
+ denied.add(row.id);
197
+ continue;
198
+ }
199
+ }
200
+ if (lowerExcludes) {
201
+ if (
202
+ containsLowerTerm(row.title ?? "", lowerExcludes) ||
203
+ containsLowerTerm(row.path, lowerExcludes) ||
204
+ (options.excludeMetadata &&
205
+ (containsLowerTerm(row.author ?? "", lowerExcludes) ||
206
+ containsLowerTerm(row.content_type ?? "", lowerExcludes) ||
207
+ categories.some((cat) =>
208
+ containsLowerTerm(cat, lowerExcludes)
209
+ )))
210
+ ) {
211
+ denied.add(row.id);
212
+ continue;
213
+ }
214
+ }
215
+ }
160
216
  if (
161
- (options.author &&
162
- !(row.author ?? "")
163
- .toLowerCase()
164
- .includes(options.author.toLowerCase())) ||
165
- (wanted?.length &&
166
- ![row.content_type ?? "", ...categories].some((value) =>
167
- wanted.includes(value.toLowerCase())
168
- ))
217
+ lowerExcludes &&
218
+ row.text &&
219
+ containsLowerTerm(row.text, lowerExcludes)
169
220
  ) {
170
221
  denied.add(row.id);
171
- continue;
172
222
  }
173
223
  }
174
- if (
175
- matchesExcludedText(
176
- [
177
- row.title ?? "",
178
- row.path,
179
- row.text ?? "",
180
- ...(options.excludeMetadata
181
- ? [row.author ?? "", row.content_type ?? "", ...categories]
182
- : []),
183
- ],
184
- options.exclude ?? []
185
- )
186
- )
187
- denied.add(row.id);
224
+ } finally {
225
+ stmt.finalize();
226
+ }
227
+ if (denied.size > 0) {
228
+ conditions.push("d.id NOT IN (SELECT value FROM json_each(?))");
229
+ params.push(JSON.stringify([...denied]));
188
230
  }
189
- conditions.push("d.id NOT IN (SELECT value FROM json_each(?))");
190
- params.push(JSON.stringify([...denied]));
191
231
  }
192
232
  return {
193
233
  sql: `SELECT d.id, d.mirror_hash FROM documents d${hashPin} WHERE ${conditions.join(" AND ")}`,
@@ -103,9 +103,6 @@ const matchesWikiKey = (targetRefNorm: string, keys: Set<string>): boolean => {
103
103
  return false;
104
104
  };
105
105
 
106
- const escapeLike = (value: string): string =>
107
- value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
108
-
109
106
  /** Effective graph allowlist; undefined means unrestricted. */
110
107
  export const graphCollectionAllowlist = (options: {
111
108
  collection?: string;
@@ -125,8 +122,8 @@ const inScopeClause = (
125
122
  sql:
126
123
  allowlist.size === 0
127
124
  ? "AND 0"
128
- : `AND ${column} IN (${[...allowlist].map(() => "?").join(",")})`,
129
- params: [...allowlist],
125
+ : `AND ${column} IN (SELECT value FROM json_each(?))`,
126
+ params: allowlist.size === 0 ? [] : [JSON.stringify([...allowlist])],
130
127
  }
131
128
  : { sql: "", params: [] };
132
129
 
@@ -137,15 +134,14 @@ const loadSeeds = (db: Database, seedDocumentIds: number[]): SeedDocRow[] => {
137
134
  if (uniqueIds.length === 0) {
138
135
  return [];
139
136
  }
140
- const placeholders = uniqueIds.map(() => "?").join(",");
141
137
  return db
142
- .query<SeedDocRow, number[]>(
138
+ .query<SeedDocRow, [string]>(
143
139
  `SELECT id, docid, title, rel_path, collection
144
140
  FROM documents
145
- WHERE active = 1 AND id IN (${placeholders})
141
+ WHERE active = 1 AND id IN (SELECT value FROM json_each(?))
146
142
  ORDER BY id ASC`
147
143
  )
148
- .all(...uniqueIds);
144
+ .all(JSON.stringify(uniqueIds));
149
145
  };
150
146
 
151
147
  const collectIncomingCandidateLinks = (
@@ -159,17 +155,20 @@ const collectIncomingCandidateLinks = (
159
155
  const sourceScope = inScopeClause(allowlist, "src.collection");
160
156
 
161
157
  const wikiKeysByCollection = new Map<string, Set<string>>();
158
+ const allWikiKeys = new Set<string>();
162
159
  for (const seed of seeds) {
163
160
  const keys = wikiKeysByCollection.get(seed.collection) ?? new Set<string>();
164
161
  for (const key of wikiKeysForSeed(seed)) {
165
162
  keys.add(key);
163
+ allWikiKeys.add(key);
166
164
  }
167
165
  wikiKeysByCollection.set(seed.collection, keys);
168
166
  }
169
167
 
170
168
  const targetCollections = [...wikiKeysByCollection.keys()];
171
- if (targetCollections.length > 0) {
172
- const collectionPlaceholders = targetCollections.map(() => "?").join(",");
169
+ if (targetCollections.length > 0 && allWikiKeys.size > 0) {
170
+ const targetCollectionsJson = JSON.stringify(targetCollections);
171
+ const exactKeysJson = JSON.stringify([...allWikiKeys]);
173
172
  const wikiRows = db
174
173
  .query<RawLinkRow & { source_doc_id: number }, string[]>(
175
174
  `SELECT dl.source_doc_id, ${RAW_LINK_COLUMNS}
@@ -178,12 +177,26 @@ const collectIncomingCandidateLinks = (
178
177
  WHERE dl.link_type = 'wiki'
179
178
  AND (
180
179
  (dl.target_collection IS NULL
181
- AND src.collection IN (${collectionPlaceholders}))
182
- OR dl.target_collection IN (${collectionPlaceholders})
180
+ AND src.collection IN (SELECT value FROM json_each(?)))
181
+ OR dl.target_collection IN (SELECT value FROM json_each(?))
182
+ )
183
+ AND (
184
+ dl.target_ref_norm IN (SELECT value FROM json_each(?))
185
+ OR EXISTS (
186
+ SELECT 1 FROM json_each(?) sk
187
+ WHERE length(dl.target_ref_norm) > length(sk.value)
188
+ AND substr(dl.target_ref_norm, -length(sk.value) - 1) = '/' || sk.value
189
+ )
183
190
  )
184
191
  ${sourceScope.sql}`
185
192
  )
186
- .all(...targetCollections, ...targetCollections, ...sourceScope.params);
193
+ .all(
194
+ targetCollectionsJson,
195
+ targetCollectionsJson,
196
+ exactKeysJson,
197
+ exactKeysJson,
198
+ ...sourceScope.params
199
+ );
187
200
  examinedLinkRows += wikiRows.length;
188
201
 
189
202
  for (const row of wikiRows) {
@@ -221,24 +234,21 @@ const collectIncomingCandidateLinks = (
221
234
  memberships,
222
235
  new Set(workspaceSeeds.map(({ wsKey }) => wsKey))
223
236
  );
224
- const conditions: string[] = [];
225
- const params: string[] = [];
237
+ const wsExactKeys = new Set<string>();
238
+ const wsSuffixKeys = new Set<string>();
226
239
  for (const { seed } of workspaceSeeds) {
227
240
  const base = stripWikiMdExt(
228
241
  normalizeWikiName(seed.rel_path.split("/").pop() ?? seed.rel_path)
229
242
  );
230
243
  for (const value of [base, `${base}.md`]) {
231
- conditions.push(
232
- "dl.target_ref_norm = ? OR dl.target_ref_norm LIKE ? ESCAPE '\\'"
233
- );
234
- params.push(value, `%/${escapeLike(value)}`);
244
+ wsExactKeys.add(value);
245
+ wsSuffixKeys.add(value);
235
246
  }
236
247
  for (const key of wikiKeysForSeed(seed)) {
237
- conditions.push("dl.target_ref_norm = ?");
238
- params.push(key);
248
+ wsExactKeys.add(key);
239
249
  }
240
250
  }
241
- if (members.length > 0 && conditions.length > 0) {
251
+ if (members.length > 0 && wsExactKeys.size > 0) {
242
252
  const rows = db
243
253
  .query<RawLinkRow & { source_doc_id: number }, string[]>(
244
254
  `SELECT dl.source_doc_id, ${RAW_LINK_COLUMNS}
@@ -246,11 +256,23 @@ const collectIncomingCandidateLinks = (
246
256
  JOIN documents src ON src.id = dl.source_doc_id AND src.active = 1
247
257
  WHERE dl.link_type = 'wiki'
248
258
  AND dl.target_collection IS NULL
249
- AND src.collection IN (${members.map(() => "?").join(",")})
250
- AND (${conditions.join(" OR ")})
259
+ AND src.collection IN (SELECT value FROM json_each(?))
260
+ AND (
261
+ dl.target_ref_norm IN (SELECT value FROM json_each(?))
262
+ OR EXISTS (
263
+ SELECT 1 FROM json_each(?) sk
264
+ WHERE length(dl.target_ref_norm) > length(sk.value)
265
+ AND substr(dl.target_ref_norm, -length(sk.value) - 1) = '/' || sk.value
266
+ )
267
+ )
251
268
  ${sourceScope.sql}`
252
269
  )
253
- .all(...members, ...params, ...sourceScope.params);
270
+ .all(
271
+ JSON.stringify(members),
272
+ JSON.stringify([...wsExactKeys]),
273
+ JSON.stringify([...wsSuffixKeys]),
274
+ ...sourceScope.params
275
+ );
254
276
  examinedLinkRows += rows.length;
255
277
  for (const row of rows) {
256
278
  if (!seedIdSet.has(row.source_doc_id)) linksById.set(row.id, row);
@@ -258,26 +280,30 @@ const collectIncomingCandidateLinks = (
258
280
  }
259
281
  }
260
282
 
261
- for (const seed of seeds) {
283
+ // Batch markdown backlink lookup across all seeds in one SQL query.
284
+ const mdSeedPairs = seeds.map((seed) => [seed.rel_path, seed.collection]);
285
+ if (mdSeedPairs.length > 0) {
262
286
  const mdRows = db
263
287
  .query<RawLinkRow & { source_doc_id: number }, string[]>(
264
- `SELECT dl.source_doc_id, ${RAW_LINK_COLUMNS}
265
- FROM doc_links dl
288
+ `WITH seed_targets AS (
289
+ SELECT DISTINCT
290
+ json_extract(value, '$[0]') AS rel_path,
291
+ json_extract(value, '$[1]') AS collection
292
+ FROM json_each(?)
293
+ )
294
+ SELECT dl.source_doc_id, ${RAW_LINK_COLUMNS}
295
+ FROM seed_targets st
296
+ JOIN doc_links dl
297
+ ON dl.link_type = 'markdown'
298
+ AND dl.target_ref_norm = st.rel_path
266
299
  JOIN documents src ON src.id = dl.source_doc_id AND src.active = 1
267
- WHERE dl.link_type = 'markdown'
268
- AND dl.target_ref_norm = ?
269
- AND (
270
- (dl.target_collection IS NULL AND src.collection = ?)
271
- OR dl.target_collection = ?
272
- )
273
- ${sourceScope.sql}`
300
+ WHERE (
301
+ (dl.target_collection IS NULL AND src.collection = st.collection)
302
+ OR dl.target_collection = st.collection
303
+ )
304
+ ${sourceScope.sql}`
274
305
  )
275
- .all(
276
- seed.rel_path,
277
- seed.collection,
278
- seed.collection,
279
- ...sourceScope.params
280
- );
306
+ .all(JSON.stringify(mdSeedPairs), ...sourceScope.params);
281
307
  examinedLinkRows += mdRows.length;
282
308
  for (const row of mdRows) {
283
309
  if (!seedIdSet.has(row.source_doc_id)) {
@@ -297,19 +323,18 @@ const loadRawLinksForSources = (
297
323
  if (sourceIds.length === 0) {
298
324
  return [];
299
325
  }
300
- const sourcePlaceholders = sourceIds.map(() => "?").join(",");
301
326
  const sourceScope = inScopeClause(allowlist, "src.collection");
302
327
  return db
303
- .query<RawLinkRow, (string | number)[]>(
328
+ .query<RawLinkRow, string[]>(
304
329
  `SELECT ${RAW_LINK_COLUMNS}
305
330
  FROM documents src
306
331
  JOIN doc_links dl ON dl.source_doc_id = src.id
307
332
  WHERE src.active = 1
308
- AND src.id IN (${sourcePlaceholders})
333
+ AND src.id IN (SELECT value FROM json_each(?))
309
334
  ${sourceScope.sql}
310
335
  ORDER BY src.id ASC, dl.id ASC`
311
336
  )
312
- .all(...sourceIds, ...sourceScope.params);
337
+ .all(JSON.stringify(sourceIds), ...sourceScope.params);
313
338
  };
314
339
 
315
340
  const resolveRawEdges = (
@@ -7,6 +7,7 @@ import type {
7
7
  GraphReferenceStore,
8
8
  } from "../types";
9
9
 
10
+ import { normalizeRelationTarget } from "../../core/change-diff";
10
11
  import { buildWikiMatchExpression } from "../../core/graph-resolver";
11
12
  import { normalizeWikiName, stripWikiMdExt } from "../../core/links";
12
13
 
@@ -139,9 +140,26 @@ export function createGraphReferenceStore(db: Database): GraphReferenceStore {
139
140
  .all(JSON.stringify(targets))
140
141
  .map((row) => row.sourceId);
141
142
  },
143
+ docidReferenceSources(docids) {
144
+ if (docids.length === 0) return [];
145
+ const docidSet = new Set(docids);
146
+ const rows = db
147
+ .query<{ sourceId: number; target: string }, []>(
148
+ `SELECT source_doc_id AS sourceId, target
149
+ FROM graph_frontmatter_references
150
+ WHERE instr(target, '#') > 0`
151
+ )
152
+ .all();
153
+ const sources = new Set<number>();
154
+ for (const row of rows) {
155
+ if (docidSet.has(normalizeRelationTarget(row.target))) {
156
+ sources.add(row.sourceId);
157
+ }
158
+ }
159
+ return [...sources];
160
+ },
142
161
  writeInventory({ document: d, references }) {
143
- db.transaction(() => {
144
- db.run("UPDATE graph_projection_state SET dirty = 1 WHERE id = 1");
162
+ const write = () => {
145
163
  db.run(
146
164
  `INSERT INTO graph_reference_documents
147
165
  (document_id, collection, rel_path, docid, uri, title, mirror_hash, source_hash, content_type)
@@ -171,7 +189,13 @@ export function createGraphReferenceStore(db: Database): GraphReferenceStore {
171
189
  [d.documentId, ordinal, ref.edgeType, ref.target]
172
190
  );
173
191
  }
174
- })();
192
+ };
193
+ // Avoid nested savepoints when already inside projectGraph's outer transaction.
194
+ if (db.inTransaction) {
195
+ write();
196
+ } else {
197
+ db.transaction(write)();
198
+ }
175
199
  },
176
200
  complete(expectedEpoch) {
177
201
  db.transaction(() => {
@@ -29,10 +29,38 @@ export interface StoredSimilarityEdge {
29
29
 
30
30
  function dot(a: Float32Array, b: Float32Array): number {
31
31
  let sum = 0;
32
- for (let i = 0; i < a.length; i++) sum += (a[i] ?? 0) * (b[i] ?? 0);
32
+ for (let i = 0; i < a.length; i++) sum += a[i]! * b[i]!;
33
33
  return sum;
34
34
  }
35
35
 
36
+ function compareSimilarityEdge(
37
+ a: StoredSimilarityEdge,
38
+ b: StoredSimilarityEdge
39
+ ): number {
40
+ return b.score - a.score || a.target.localeCompare(b.target);
41
+ }
42
+
43
+ function insertTopK(
44
+ buffer: StoredSimilarityEdge[],
45
+ candidate: StoredSimilarityEdge,
46
+ topK: number
47
+ ): void {
48
+ if (
49
+ buffer.length >= topK &&
50
+ compareSimilarityEdge(candidate, buffer[topK - 1]!) >= 0
51
+ ) {
52
+ return;
53
+ }
54
+ let pos = buffer.length;
55
+ while (pos > 0 && compareSimilarityEdge(candidate, buffer[pos - 1]!) < 0) {
56
+ pos -= 1;
57
+ }
58
+ buffer.splice(pos, 0, candidate);
59
+ if (buffer.length > topK) {
60
+ buffer.pop();
61
+ }
62
+ }
63
+
36
64
  /**
37
65
  * Top-K most similar other nodes per node, by the first-chunk vector each
38
66
  * document stores for `model`. Documents sharing content are not similarity
@@ -63,23 +91,42 @@ export function storedSimilarityEdges(
63
91
  const vector = vectors.get(document.id);
64
92
  return vector ? [{ ...document, vector }] : [];
65
93
  });
66
- const edges: StoredSimilarityEdge[] = [];
67
- for (const node of nodes) {
68
- const scored: StoredSimilarityEdge[] = [];
69
- for (const other of nodes) {
94
+ if (topK <= 0 || nodes.length < 2) {
95
+ return { embeddedNodes: nodes.length, edges: [] };
96
+ }
97
+ const buffers: StoredSimilarityEdge[][] = Array.from(
98
+ { length: nodes.length },
99
+ () => []
100
+ );
101
+ for (let i = 0; i < nodes.length; i++) {
102
+ const node = nodes[i]!;
103
+ const nodeBuf = buffers[i]!;
104
+ for (let j = i + 1; j < nodes.length; j++) {
105
+ const other = nodes[j]!;
70
106
  if (
71
107
  other.mirrorHash === node.mirrorHash ||
72
108
  other.vector.length !== node.vector.length
73
- )
109
+ ) {
74
110
  continue;
111
+ }
75
112
  const score = Math.max(0, Math.min(1, dot(node.vector, other.vector)));
76
- if (score >= threshold)
77
- scored.push({ source: node.docid, target: other.docid, score });
113
+ if (score >= threshold) {
114
+ insertTopK(
115
+ nodeBuf,
116
+ { source: node.docid, target: other.docid, score },
117
+ topK
118
+ );
119
+ insertTopK(
120
+ buffers[j]!,
121
+ { source: other.docid, target: node.docid, score },
122
+ topK
123
+ );
124
+ }
78
125
  }
79
- scored.sort(
80
- (a, b) => b.score - a.score || a.target.localeCompare(b.target)
81
- );
82
- edges.push(...scored.slice(0, topK));
126
+ }
127
+ const edges: StoredSimilarityEdge[] = [];
128
+ for (const buf of buffers) {
129
+ edges.push(...buf);
83
130
  }
84
131
  return { embeddedNodes: nodes.length, edges };
85
132
  } catch {