@gmickel/gno 2.15.0 → 2.16.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 (198) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -24,66 +24,118 @@ function isCurrent(
24
24
  );
25
25
  }
26
26
 
27
- /** Exact inputs are inferred once; successful current owners checkpoint atomically. */
28
- export async function embedVariantBatch(params: {
29
- store: VectorVariantStore;
30
- embedPort: EmbeddingPort;
27
+ function filterCurrentOwners(
28
+ store: VectorVariantStore,
29
+ owners: VectorOwnerInput[]
30
+ ): VectorOwnerInput[] {
31
+ if (owners.length === 0) return [];
32
+ if (typeof store.filterCurrent === "function") {
33
+ return store.filterCurrent(owners);
34
+ }
35
+ return owners.filter((owner) => isCurrent(store, owner));
36
+ }
37
+
38
+ export interface PreparedVariantBatch {
31
39
  owners: VectorOwnerInput[];
32
- identityStillCurrent: () => boolean;
33
- delays?: number[];
34
- force?: boolean;
35
- /** Gate held only around the checkpoint write, never around inference. */
36
- acquireWriteTurn?: AcquireWriteTurn;
37
- /** Called with the text count of each provider request (see `embedTextsWithRecovery`). */
38
- onSubmit?: (texts: number) => void;
39
- }): Promise<{
40
+ inputs: Map<string, string>;
41
+ reusable: Set<string>;
42
+ sharedFromInFlight: Map<string, string>;
43
+ }
44
+
45
+ export interface VariantBatchOutcome {
40
46
  embedded: number;
41
47
  errors: number;
42
48
  contentionErrors: number;
43
49
  retryOwners: VectorOwnerInput[];
44
50
  deferred?: boolean;
45
- }> {
46
- const { store, embedPort, identityStillCurrent } = params;
47
- const empty = {
48
- embedded: 0,
49
- errors: 0,
50
- contentionErrors: 0,
51
- retryOwners: [] as VectorOwnerInput[],
52
- };
53
- if (!identityStillCurrent()) return empty;
54
- const owners = [
51
+ }
52
+
53
+ export function prepareVariantBatch(params: {
54
+ store: VectorVariantStore;
55
+ owners: VectorOwnerInput[];
56
+ force?: boolean;
57
+ inFlightHashes?: ReadonlySet<string>;
58
+ }): PreparedVariantBatch {
59
+ const { store } = params;
60
+ const deduped = [
55
61
  ...new Map(
56
62
  params.owners.map((owner) => [chunkRetryKey(owner), owner])
57
63
  ).values(),
58
- ].filter((owner) => isCurrent(store, owner));
59
- const inputs = new Map<string, string>();
64
+ ];
65
+
66
+ let owners: VectorOwnerInput[];
60
67
  const reusable = new Set<string>();
61
- for (const owner of owners) {
62
- if (!params.force && store.reusable(owner)) reusable.add(owner.inputHash);
63
- else inputs.set(owner.inputHash, owner.formattedInput);
68
+ const inputs = new Map<string, string>();
69
+ const sharedFromInFlight = new Map<string, string>();
70
+
71
+ if (!params.force && typeof store.findReusableHashes === "function") {
72
+ const found = store.findReusableHashes(deduped);
73
+ owners = found.current;
74
+ for (const hash of found.reusableHashes) {
75
+ reusable.add(hash);
76
+ }
77
+ for (const owner of owners) {
78
+ if (reusable.has(owner.inputHash)) continue;
79
+ if (params.inFlightHashes?.has(owner.inputHash)) {
80
+ sharedFromInFlight.set(owner.inputHash, owner.formattedInput);
81
+ } else {
82
+ inputs.set(owner.inputHash, owner.formattedInput);
83
+ }
84
+ }
85
+ } else {
86
+ owners = filterCurrentOwners(store, deduped);
87
+ for (const owner of owners) {
88
+ const canReuse =
89
+ !params.force &&
90
+ (typeof store.hasReusable === "function"
91
+ ? store.hasReusable(owner)
92
+ : Boolean(store.reusable(owner)));
93
+ if (canReuse) {
94
+ reusable.add(owner.inputHash);
95
+ } else if (!params.force && params.inFlightHashes?.has(owner.inputHash)) {
96
+ sharedFromInFlight.set(owner.inputHash, owner.formattedInput);
97
+ } else {
98
+ inputs.set(owner.inputHash, owner.formattedInput);
99
+ }
100
+ }
64
101
  }
65
- const keys = [...inputs.keys()];
66
- const result = await embedTextsWithRecovery(embedPort, [...inputs.values()], {
67
- onSubmit: params.onSubmit,
68
- });
102
+
103
+ return { owners, inputs, reusable, sharedFromInFlight };
104
+ }
105
+
106
+ export async function commitVariantBatch(params: {
107
+ store: VectorVariantStore;
108
+ owners: VectorOwnerInput[];
109
+ reusable: ReadonlySet<string>;
110
+ vectors: ReadonlyMap<string, Float32Array>;
111
+ identityStillCurrent: () => boolean;
112
+ delays?: number[];
113
+ acquireWriteTurn?: AcquireWriteTurn;
114
+ }): Promise<VariantBatchOutcome> {
115
+ const { store, owners, reusable, vectors, identityStillCurrent } = params;
116
+ const empty: VariantBatchOutcome = {
117
+ embedded: 0,
118
+ errors: 0,
119
+ contentionErrors: 0,
120
+ retryOwners: [],
121
+ };
69
122
  if (!identityStillCurrent()) return empty;
70
- const current = owners.filter((owner) => isCurrent(store, owner));
71
- const vectors = new Map<string, Float32Array>();
72
- if (result.ok) {
73
- for (const [index, key] of keys.entries()) {
74
- const vector = result.value.vectors[index];
75
- if (vector) vectors.set(key, new Float32Array(vector));
123
+
124
+ const failedOwners: VectorOwnerInput[] = [];
125
+ const rows: { owner: VectorOwnerInput; embedding?: Float32Array }[] = [];
126
+ for (const owner of owners) {
127
+ const vec = vectors.get(owner.inputHash);
128
+ if (vec !== undefined || reusable.has(owner.inputHash)) {
129
+ rows.push({ owner, embedding: vec });
130
+ } else {
131
+ failedOwners.push(owner);
76
132
  }
77
133
  }
78
- const retryOwners = current.filter(
79
- (owner) => !reusable.has(owner.inputHash) && !vectors.has(owner.inputHash)
80
- );
81
- const rows = current
82
- .filter(
83
- (owner) => reusable.has(owner.inputHash) || vectors.has(owner.inputHash)
84
- )
85
- .map((owner) => ({ owner, embedding: vectors.get(owner.inputHash) }));
134
+ // Recheck isCurrent post-inference only for failed retryOwners; writeCurrent
135
+ // validates and filters successful rows atomically inside the write txn.
136
+ const retryOwners = filterCurrentOwners(store, failedOwners);
86
137
  if (!rows.length) return { ...empty, retryOwners };
138
+
87
139
  let written = 0;
88
140
  const turn = await inWriteTurn(params.acquireWriteTurn, () =>
89
141
  upsertVectorsWithContentionRetry(
@@ -92,9 +144,13 @@ export async function embedVariantBatch(params: {
92
144
  try {
93
145
  // A contention wait may allow document or runtime mutations. Revalidate each attempt.
94
146
  if (!identityStillCurrent()) return Promise.resolve(ok(undefined));
95
- const valid = rows.filter(({ owner }) => isCurrent(store, owner));
96
- store.write(valid);
97
- written = valid.length;
147
+ if (typeof store.writeCurrent === "function") {
148
+ written = store.writeCurrent(rows).length;
149
+ } else {
150
+ const valid = rows.filter(({ owner }) => isCurrent(store, owner));
151
+ store.write(valid);
152
+ written = valid.length;
153
+ }
98
154
  return Promise.resolve(ok(undefined));
99
155
  } catch (cause) {
100
156
  return Promise.resolve(
@@ -124,3 +180,56 @@ export async function embedVariantBatch(params: {
124
180
  };
125
181
  return { ...empty, embedded: written, retryOwners };
126
182
  }
183
+
184
+ /** Exact inputs are inferred once; successful current owners checkpoint atomically. */
185
+ export async function embedVariantBatch(params: {
186
+ store: VectorVariantStore;
187
+ embedPort: EmbeddingPort;
188
+ owners: VectorOwnerInput[];
189
+ identityStillCurrent: () => boolean;
190
+ delays?: number[];
191
+ force?: boolean;
192
+ /** Gate held only around the checkpoint write, never around inference. */
193
+ acquireWriteTurn?: AcquireWriteTurn;
194
+ /** Called with the text count of each provider request (see `embedTextsWithRecovery`). */
195
+ onSubmit?: (texts: number) => void;
196
+ }): Promise<VariantBatchOutcome> {
197
+ const { store, embedPort, identityStillCurrent } = params;
198
+ const empty: VariantBatchOutcome = {
199
+ embedded: 0,
200
+ errors: 0,
201
+ contentionErrors: 0,
202
+ retryOwners: [],
203
+ };
204
+ if (!identityStillCurrent()) return empty;
205
+ const prepared = prepareVariantBatch({
206
+ store,
207
+ owners: params.owners,
208
+ force: params.force,
209
+ });
210
+ const keys = [...prepared.inputs.keys()];
211
+ const result = await embedTextsWithRecovery(
212
+ embedPort,
213
+ [...prepared.inputs.values()],
214
+ {
215
+ onSubmit: params.onSubmit,
216
+ }
217
+ );
218
+ if (!identityStillCurrent()) return empty;
219
+ const vectors = new Map<string, Float32Array>();
220
+ if (result.ok) {
221
+ for (const [index, key] of keys.entries()) {
222
+ const vector = result.value.vectors[index];
223
+ if (vector) vectors.set(key, new Float32Array(vector));
224
+ }
225
+ }
226
+ return commitVariantBatch({
227
+ store,
228
+ owners: prepared.owners,
229
+ reusable: prepared.reusable,
230
+ vectors,
231
+ identityStillCurrent,
232
+ delays: params.delays,
233
+ acquireWriteTurn: params.acquireWriteTurn,
234
+ });
235
+ }
package/src/index.ts CHANGED
@@ -6,10 +6,9 @@
6
6
  * @module src/index
7
7
  */
8
8
 
9
- import { runCli } from "./cli/run";
10
9
  import { tracePhase } from "./core/phase-trace";
11
10
  import { FILE_PROCESSOR_CHILD_ENV } from "./ingestion/file-child-env";
12
- import { resetModelManager } from "./llm/nodeLlamaCpp/lifecycle";
11
+ import { resetLoadedModelManager } from "./llm/model-cleanup";
13
12
  import { IMPORT_CHILD_ENV } from "./sessions/import-child-env";
14
13
 
15
14
  /**
@@ -48,7 +47,7 @@ function flushStream(stream: NodeJS.WriteStream): Promise<void> {
48
47
  * Without the explicit exit, llama.cpp native threads can keep the process alive.
49
48
  */
50
49
  async function cleanupAndExit(code: number): Promise<never> {
51
- await resetModelManager().catch(() => {
50
+ await resetLoadedModelManager().catch(() => {
52
51
  // Ignore cleanup errors on exit
53
52
  });
54
53
  tracePhase("exit: models reset");
@@ -92,6 +91,7 @@ if (process.env[FILE_PROCESSOR_CHILD_ENV] === "1") {
92
91
 
93
92
  // Await module completion so pending piped stdin keeps Windows Bun alive.
94
93
  tracePhase("cli: start");
94
+ const { runCli } = await import("./cli/run");
95
95
  await runCli(process.argv)
96
96
  .then((code) => {
97
97
  tracePhase(`cli: done (${code})`);
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Budget-stop conversion error codes.
3
+ * Extracted from src/ingestion/file-processor so read-only CLI modules do not
4
+ * pull in the worker/markdown-parsing graph just to check error codes.
5
+ *
6
+ * @module src/ingestion/budget-error-codes
7
+ */
8
+
9
+ /** Error codes of a file stopped at its budget. */
10
+ export const BUDGET_ERROR_CODES: ReadonlySet<string> = new Set([
11
+ "TIMEOUT",
12
+ "MEMORY_LIMIT",
13
+ ]);
@@ -8,6 +8,7 @@
8
8
  import type { ChunkerPort, ChunkOutput, ChunkParams } from "./types";
9
9
 
10
10
  import { defaultLanguageDetector } from "./language";
11
+ import { buildLineOffsets } from "./position";
11
12
  import { DEFAULT_CHUNK_PARAMS } from "./types";
12
13
 
13
14
  /** Approximate chars per token (conservative estimate) */
@@ -21,6 +22,7 @@ const MAX_OVERLAP_PERCENT = 0.5;
21
22
 
22
23
  /** Regex for sentence ending followed by whitespace and capital letter (global) */
23
24
  const SENTENCE_END_REGEX = /[.!?](\s+)[A-Z]/g;
25
+ const NON_WHITESPACE_REGEX = /\S/;
24
26
  const MIN_CODE_CHUNK_PERCENT = 0.35;
25
27
 
26
28
  type CodeChunkLanguage =
@@ -138,6 +140,10 @@ function collectStructuralBreakPoints(
138
140
  return [];
139
141
  }
140
142
 
143
+ // Keep independent per-pattern scans so overlapping multiline matches (e.g.,
144
+ // `export default\nclass Foo`, U+2028 line separators, and `export\nclass`)
145
+ // produce bit-for-bit identical breakpoint offsets; findStructuralBreakPoint
146
+ // uses binary search over the sorted result.
141
147
  const points = new Set<number>();
142
148
  for (const pattern of patterns) {
143
149
  pattern.lastIndex = 0;
@@ -163,72 +169,76 @@ function findStructuralBreakPoint(
163
169
  windowSize: number,
164
170
  minChunkChars: number
165
171
  ): number | null {
166
- if (breakPoints.length === 0) {
172
+ const len = breakPoints.length;
173
+ if (len === 0) {
167
174
  return null;
168
175
  }
169
176
 
170
177
  const minStart = currentPos + minChunkChars;
171
178
  const start = Math.max(minStart, target - windowSize);
172
179
  const end = target + windowSize;
173
- const candidates = breakPoints.filter(
174
- (point) => point >= start && point <= end
175
- );
176
- if (candidates.length === 0) {
180
+ if (start > end) {
177
181
  return null;
178
182
  }
179
183
 
180
- const beforeTarget = candidates.filter((point) => point <= target);
181
- if (beforeTarget.length > 0) {
182
- return beforeTarget.at(-1) ?? null;
184
+ // Lower bound: first index with breakPoints[idx] >= start
185
+ let low = 0;
186
+ let high = len;
187
+ while (low < high) {
188
+ const mid = (low + high) >>> 1;
189
+ if ((breakPoints[mid] ?? 0) < start) {
190
+ low = mid + 1;
191
+ } else {
192
+ high = mid;
193
+ }
183
194
  }
184
195
 
185
- return candidates[0] ?? null;
186
- }
187
-
188
- /**
189
- * Line index for O(1) line number lookups.
190
- * Stores positions of all newline characters.
191
- */
192
- interface LineIndex {
193
- /** Positions of '\n' characters in the text */
194
- newlines: number[];
195
- }
196
+ const first = breakPoints[low];
197
+ if (first === undefined || first > end) {
198
+ return null;
199
+ }
200
+ if (first > target) {
201
+ return first;
202
+ }
196
203
 
197
- /**
198
- * Build a line index from text (O(n) once).
199
- */
200
- function buildLineIndex(text: string): LineIndex {
201
- const newlines: number[] = [];
202
- for (let i = 0; i < text.length; i += 1) {
203
- if (text[i] === "\n") {
204
- newlines.push(i);
204
+ // Upper bound: first index with breakPoints[idx] > target
205
+ let uLow = low;
206
+ let uHigh = len;
207
+ const limit = Math.min(target, end);
208
+ while (uLow < uHigh) {
209
+ const mid = (uLow + uHigh) >>> 1;
210
+ if ((breakPoints[mid] ?? 0) <= limit) {
211
+ uLow = mid + 1;
212
+ } else {
213
+ uHigh = mid;
205
214
  }
206
215
  }
207
- return { newlines };
216
+
217
+ return breakPoints[uLow - 1] ?? null;
208
218
  }
209
219
 
210
220
  /**
211
- * Find line number at character position using binary search (O(log n)).
212
- * Returns 1-based line number.
221
+ * Find 1-based line number at character position using binary search (O(log n))
222
+ * over line start offsets (`[0, nl0 + 1, nl1 + 1, ...]`).
213
223
  */
214
- function lineAtPosition(index: LineIndex, pos: number): number {
215
- const { newlines } = index;
216
-
217
- // Binary search for the number of newlines before pos
224
+ function lineAtPosition(lineStarts: readonly number[], pos: number): number {
218
225
  let low = 0;
219
- let high = newlines.length;
220
-
221
- while (low < high) {
222
- const mid = Math.floor((low + high) / 2);
223
- const newlinePos = newlines[mid];
224
- if (newlinePos !== undefined && newlinePos < pos) {
226
+ let high = lineStarts.length - 1;
227
+ let lineIndex = 0;
228
+
229
+ while (low <= high) {
230
+ const mid = (low + high) >>> 1;
231
+ const lineStart = lineStarts[mid];
232
+ if (lineStart === undefined) break;
233
+ if (lineStart <= pos) {
234
+ lineIndex = mid;
225
235
  low = mid + 1;
226
236
  } else {
227
- high = mid;
237
+ high = mid - 1;
228
238
  }
229
239
  }
230
240
 
231
- return low + 1; // 1-based line number
241
+ return lineIndex + 1; // 1-based line number
232
242
  }
233
243
 
234
244
  /**
@@ -324,9 +334,10 @@ export class MarkdownChunker implements ChunkerPort {
324
334
  markdown: string,
325
335
  params?: ChunkParams,
326
336
  documentLanguageHint?: string,
327
- sourcePath?: string
337
+ sourcePath?: string,
338
+ precomputedLineOffsets?: readonly number[]
328
339
  ): ChunkOutput[] {
329
- if (!markdown || markdown.trim().length === 0) {
340
+ if (!markdown || !NON_WHITESPACE_REGEX.test(markdown)) {
330
341
  return [];
331
342
  }
332
343
 
@@ -338,8 +349,8 @@ export class MarkdownChunker implements ChunkerPort {
338
349
  const windowSize = Math.floor(maxChars * 0.1); // 10% window for break search
339
350
  const minCodeChunkChars = Math.floor(maxChars * MIN_CODE_CHUNK_PERCENT);
340
351
 
341
- // Build line index once for O(log n) lookups
342
- const lineIndex = buildLineIndex(markdown);
352
+ // Reuse precomputed line start offsets when available; otherwise scan once.
353
+ const lineStarts = precomputedLineOffsets ?? buildLineOffsets(markdown);
343
354
  const structuralBreakPoints = collectStructuralBreakPoints(
344
355
  markdown,
345
356
  sourcePath
@@ -384,9 +395,9 @@ export class MarkdownChunker implements ChunkerPort {
384
395
  const text = markdown.slice(pos, endPos);
385
396
 
386
397
  // Only skip truly empty chunks (all whitespace after full content consumed)
387
- if (text.trim().length > 0) {
388
- const startLine = lineAtPosition(lineIndex, pos);
389
- const endLine = lineAtPosition(lineIndex, endPos - 1);
398
+ if (NON_WHITESPACE_REGEX.test(text)) {
399
+ const startLine = lineAtPosition(lineStarts, pos);
400
+ const endLine = lineAtPosition(lineStarts, endPos - 1);
390
401
 
391
402
  // Detect language for this chunk
392
403
  const language =
@@ -1,13 +1,12 @@
1
1
  /** Generated context is derived evidence and must not feed recursive retrieval. */
2
2
  const SIDECAR_MARKER = /"artifactKind"\s*:\s*"gno_compiled_context_sidecar"/;
3
+ const UTF8_DECODER = new TextDecoder();
4
+
3
5
  export function isCompiledContextPath(path: string): boolean {
4
- return path
5
- .toLowerCase()
6
- .split(/[\\/]/)
7
- .some((part) => part.includes(".gno-context."));
6
+ return path.toLowerCase().includes(".gno-context.");
8
7
  }
9
8
  export function isCompiledContextContent(prefix: Uint8Array): boolean {
10
- const text = new TextDecoder().decode(prefix).trimStart();
9
+ const text = UTF8_DECODER.decode(prefix).trimStart();
11
10
  return (
12
11
  text.startsWith("<!-- gno:compiled-context ") ||
13
12
  (text.startsWith("{") && SIDECAR_MARKER.test(text))
@@ -151,7 +151,7 @@ export async function convertFile(path: string): Promise<ConvertFileOutcome> {
151
151
  timeoutMs: DEFAULT_LIMITS.timeoutMs,
152
152
  maxMemoryBytes: defaultConversionMemoryMb() * BYTES_PER_MB,
153
153
  },
154
- { onPrevious: () => undefined }
154
+ { onPrevious: () => undefined, transferInputBytes: true }
155
155
  );
156
156
  if (!prepared.ok) {
157
157
  const { code, message, details } = prepared.error;
@@ -15,20 +15,23 @@ import { resolveContentTypeRule } from "../config";
15
15
  import { normalizeTag, validateTag } from "../core/tags";
16
16
  import {
17
17
  extractHashtags,
18
- parseFrontmatter,
19
- stripFrontmatter,
18
+ type FrontmatterDetails,
19
+ parseFrontmatterDetails,
20
20
  } from "./frontmatter";
21
- import { extractTypedMetadata } from "./typed-metadata";
21
+ import { extractTypedMetadataFromYaml } from "./typed-metadata";
22
22
 
23
23
  /**
24
24
  * Extract tags from markdown content.
25
25
  * Combines frontmatter tags and inline hashtags, normalized and validated.
26
26
  */
27
- export function extractTags(markdown: string): string[] {
27
+ export function extractTags(
28
+ markdown: string,
29
+ preParsed?: FrontmatterDetails
30
+ ): string[] {
28
31
  const tags = new Set<string>();
29
32
 
30
33
  // 1. Extract from frontmatter
31
- const frontmatter = parseFrontmatter(markdown);
34
+ const frontmatter = preParsed ?? parseFrontmatterDetails(markdown);
32
35
  for (const tag of frontmatter.tags) {
33
36
  const normalized = normalizeTag(tag);
34
37
  if (validateTag(normalized)) {
@@ -37,7 +40,10 @@ export function extractTags(markdown: string): string[] {
37
40
  }
38
41
 
39
42
  // 2. Extract hashtags from body (after stripping frontmatter)
40
- const body = stripFrontmatter(markdown);
43
+ const body =
44
+ frontmatter.bodyStart > 0
45
+ ? markdown.slice(frontmatter.bodyStart)
46
+ : markdown;
41
47
  const hashtags = extractHashtags(body);
42
48
  for (const tag of hashtags) {
43
49
  const normalized = normalizeTag(tag);
@@ -177,9 +183,10 @@ export function extractDocumentMetadata(
177
183
  markdown: string,
178
184
  relPath: string,
179
185
  ext: string,
180
- contentTypeRules: NormalizedContentTypeRule[] = []
186
+ contentTypeRules: NormalizedContentTypeRule[] = [],
187
+ preParsed?: FrontmatterDetails
181
188
  ): DocumentMetadata {
182
- const parsed = parseFrontmatter(markdown);
189
+ const parsed = preParsed ?? parseFrontmatterDetails(markdown);
183
190
  const metadata = parsed.metadata;
184
191
  const rawFrontmatterType =
185
192
  typeof metadata.type === "string"
@@ -245,7 +252,7 @@ export function extractDocumentMetadata(
245
252
  }
246
253
 
247
254
  return {
248
- ...extractTypedMetadata(markdown),
255
+ ...extractTypedMetadataFromYaml(parsed.rawYaml),
249
256
  contentType,
250
257
  contentTypeSource,
251
258
  categories: [...categories],
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Excluded-range types and binary-search lookup helpers.
3
+ * Extracted from src/ingestion/strip so link/attachment utilities do not pull
4
+ * in mdast/micromark parser packages at module load time.
5
+ *
6
+ * @module src/ingestion/excluded-ranges
7
+ */
8
+
9
+ export type ExcludedRangeKind =
10
+ | "frontmatter"
11
+ | "fenced_code"
12
+ | "indented_code"
13
+ | "inline_code"
14
+ | "html_comment";
15
+
16
+ export interface ExcludedRange {
17
+ /** String offset in original string (inclusive, UTF-16 code unit index) */
18
+ start: number;
19
+ /** String offset in original string (exclusive, UTF-16 code unit index) */
20
+ end: number;
21
+ /** Type of excluded region */
22
+ kind: ExcludedRangeKind;
23
+ }
24
+
25
+ /**
26
+ * Check if a string offset falls within any excluded range.
27
+ * Uses binary search for O(log n) lookup.
28
+ */
29
+ export function isExcluded(
30
+ offset: number,
31
+ excludedRanges: readonly ExcludedRange[]
32
+ ): boolean {
33
+ let left = 0;
34
+ let right = excludedRanges.length - 1;
35
+
36
+ while (left <= right) {
37
+ const mid = Math.floor((left + right) / 2);
38
+ const range = excludedRanges[mid];
39
+ if (range === undefined) return false;
40
+
41
+ if (offset < range.start) {
42
+ right = mid - 1;
43
+ } else if (offset >= range.end) {
44
+ left = mid + 1;
45
+ } else {
46
+ // offset is in [start, end)
47
+ return true;
48
+ }
49
+ }
50
+
51
+ return false;
52
+ }
53
+
54
+ /**
55
+ * Largest `end` among each prefix of a start-sorted range list, built once
56
+ * per list. Ranges can overlap (a comment around a code span), so a range
57
+ * list's ends are not sorted and the prefix maximum stands in for them.
58
+ */
59
+ const prefixMaxEnds = new WeakMap<readonly ExcludedRange[], Int32Array>();
60
+
61
+ const getPrefixMaxEnds = (ranges: readonly ExcludedRange[]): Int32Array => {
62
+ let maxEnds = prefixMaxEnds.get(ranges);
63
+ if (maxEnds?.length !== ranges.length) {
64
+ maxEnds = new Int32Array(ranges.length);
65
+ let maxEnd = -1;
66
+ for (const [index, range] of ranges.entries()) {
67
+ maxEnd = Math.max(maxEnd, range.end);
68
+ maxEnds[index] = maxEnd;
69
+ }
70
+ prefixMaxEnds.set(ranges, maxEnds);
71
+ }
72
+ return maxEnds;
73
+ };
74
+
75
+ /**
76
+ * Check if a range [start, end) intersects any excluded range.
77
+ * More precise than isExcluded for multi-character matches. Ranges must be
78
+ * sorted by start, as getExcludedRanges returns them; one lookup is a binary
79
+ * search, so checking every link of a large note stays linear.
80
+ */
81
+ export function rangeIntersectsExcluded(
82
+ start: number,
83
+ end: number,
84
+ excludedRanges: readonly ExcludedRange[]
85
+ ): boolean {
86
+ // Ranges starting before `end` form a prefix; one of them intersects
87
+ // [start, end) exactly when the largest end among them passes `start`.
88
+ let low = 0;
89
+ let high = excludedRanges.length;
90
+ while (low < high) {
91
+ const mid = (low + high) >>> 1;
92
+ if ((excludedRanges[mid]?.start ?? end) < end) low = mid + 1;
93
+ else high = mid;
94
+ }
95
+ if (low === 0) return false;
96
+ return (getPrefixMaxEnds(excludedRanges)[low - 1] ?? -1) > start;
97
+ }