@gmickel/gno 2.14.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 (205) 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.14.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 +88 -45
  9. package/spec/db/schema.sql +45 -0
  10. package/spec/output-schemas/embed-receipt.schema.json +89 -0
  11. package/src/cli/commands/agents/commands.ts +1 -1
  12. package/src/cli/commands/ask.ts +1 -1
  13. package/src/cli/commands/context-build.ts +1 -1
  14. package/src/cli/commands/embed.ts +341 -20
  15. package/src/cli/commands/links.ts +1 -1
  16. package/src/cli/commands/mcp/install.ts +2 -2
  17. package/src/cli/commands/mcp/status.ts +1 -1
  18. package/src/cli/commands/mcp/uninstall.ts +1 -1
  19. package/src/cli/commands/query.ts +1 -1
  20. package/src/cli/commands/shared.ts +4 -4
  21. package/src/cli/commands/skill/install.ts +1 -1
  22. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  23. package/src/cli/commands/skill/uninstall.ts +1 -1
  24. package/src/cli/commands/status.ts +75 -58
  25. package/src/cli/config-cache.ts +86 -0
  26. package/src/cli/globals.ts +64 -0
  27. package/src/cli/options.ts +23 -0
  28. package/src/cli/program.ts +44 -37
  29. package/src/cli/run.ts +121 -67
  30. package/src/cli/runtime-health.ts +132 -122
  31. package/src/cli/session-binding.ts +11 -2
  32. package/src/config/saver.ts +8 -0
  33. package/src/converters/adapters/browser-export/formats.ts +25 -15
  34. package/src/converters/adapters/email/adapter.ts +37 -53
  35. package/src/converters/adapters/email/html.ts +37 -20
  36. package/src/converters/adapters/email/mime.ts +71 -39
  37. package/src/converters/adapters/ical/adapter.ts +20 -12
  38. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  39. package/src/converters/adapters/shared/html-text.ts +55 -37
  40. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  41. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  42. package/src/converters/adapters/transcript/adapter.ts +12 -7
  43. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  44. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  45. package/src/converters/canonicalize.ts +17 -3
  46. package/src/converters/native/markdown.ts +24 -17
  47. package/src/converters/native/plaintext.ts +5 -6
  48. package/src/converters/registry.ts +130 -8
  49. package/src/core/activation-status.ts +4 -8
  50. package/src/core/change-diff.ts +38 -11
  51. package/src/core/context-compiler.ts +17 -18
  52. package/src/core/context-evidence.ts +116 -25
  53. package/src/core/context-verifier.ts +70 -31
  54. package/src/core/file-lock.ts +10 -2
  55. package/src/core/graph-analysis.ts +3 -3
  56. package/src/core/link-inventory-markdown.ts +2 -2
  57. package/src/core/links.ts +20 -87
  58. package/src/core/memory-fence.ts +16 -9
  59. package/src/core/memory-recall.ts +168 -34
  60. package/src/core/path-rules.ts +143 -0
  61. package/src/core/section-parse.ts +16 -6
  62. package/src/core/typed-metadata.ts +68 -0
  63. package/src/core/wiki-link-syntax.ts +88 -0
  64. package/src/embed/backlog.ts +173 -60
  65. package/src/embed/batch.ts +83 -12
  66. package/src/embed/resume-cursor.ts +103 -0
  67. package/src/embed/retry.ts +41 -32
  68. package/src/embed/variant-backlog.ts +697 -63
  69. package/src/embed/variant-plan.ts +41 -45
  70. package/src/embed/variant-retry.ts +157 -44
  71. package/src/index.ts +3 -3
  72. package/src/ingestion/budget-error-codes.ts +13 -0
  73. package/src/ingestion/chunker.ts +60 -49
  74. package/src/ingestion/compiled-context.ts +4 -5
  75. package/src/ingestion/convert-file.ts +1 -1
  76. package/src/ingestion/document-metadata.ts +16 -9
  77. package/src/ingestion/excluded-ranges.ts +97 -0
  78. package/src/ingestion/file-processor.ts +122 -37
  79. package/src/ingestion/frontmatter.ts +35 -7
  80. package/src/ingestion/graph-reconciliation.ts +187 -51
  81. package/src/ingestion/language.ts +66 -61
  82. package/src/ingestion/position.ts +5 -5
  83. package/src/ingestion/prepare-file.ts +50 -29
  84. package/src/ingestion/record-adapter-canonical.ts +37 -26
  85. package/src/ingestion/record-adapter.ts +46 -26
  86. package/src/ingestion/record-container.ts +121 -53
  87. package/src/ingestion/record-path.ts +5 -2
  88. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  89. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  90. package/src/ingestion/source-availability/readers.ts +51 -0
  91. package/src/ingestion/strip.ts +39 -105
  92. package/src/ingestion/sync.ts +692 -386
  93. package/src/ingestion/typed-metadata.ts +10 -4
  94. package/src/ingestion/walker.ts +485 -158
  95. package/src/llm/cache.ts +128 -84
  96. package/src/llm/http-inference.ts +112 -35
  97. package/src/llm/http-policy.ts +101 -0
  98. package/src/llm/httpEmbedding.ts +8 -1
  99. package/src/llm/httpGeneration.ts +5 -1
  100. package/src/llm/httpRerank.ts +5 -1
  101. package/src/llm/inference-scope.ts +15 -2
  102. package/src/llm/lazy-ports.ts +33 -3
  103. package/src/llm/lockfile.ts +34 -7
  104. package/src/llm/model-cleanup.ts +24 -0
  105. package/src/llm/native-worker/client.ts +23 -12
  106. package/src/llm/native-worker/dispatcher.ts +19 -9
  107. package/src/llm/native-worker/embedding-identity.ts +42 -16
  108. package/src/llm/native-worker/entry.ts +2 -1
  109. package/src/llm/native-worker/owner.ts +1 -0
  110. package/src/llm/native-worker/ports.ts +86 -23
  111. package/src/llm/native-worker/protocol.ts +386 -55
  112. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  113. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  114. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  115. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  116. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  117. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  118. package/src/llm/types.ts +14 -0
  119. package/src/mcp/context.ts +342 -23
  120. package/src/mcp/http-transport.ts +21 -3
  121. package/src/mcp/tool-profile-types.ts +62 -0
  122. package/src/mcp/tool-profile.ts +32 -56
  123. package/src/mcp/tools/context.ts +5 -1
  124. package/src/mcp/tools/index.ts +269 -191
  125. package/src/mcp/tools/links.ts +7 -5
  126. package/src/mcp/tools/query.ts +60 -37
  127. package/src/mcp/tools/vsearch.ts +25 -14
  128. package/src/pipeline/answer.ts +133 -40
  129. package/src/pipeline/claim-verification.ts +293 -189
  130. package/src/pipeline/claim-verifier.ts +6 -7
  131. package/src/pipeline/egress-lineage.ts +37 -26
  132. package/src/pipeline/exclude.ts +34 -11
  133. package/src/pipeline/expansion.ts +233 -19
  134. package/src/pipeline/filters.ts +169 -33
  135. package/src/pipeline/graph-retrieval.ts +117 -61
  136. package/src/pipeline/hybrid.ts +598 -329
  137. package/src/pipeline/hydration.ts +86 -24
  138. package/src/pipeline/intent.ts +15 -7
  139. package/src/pipeline/owner-fusion.ts +61 -19
  140. package/src/pipeline/query-language.ts +15 -2
  141. package/src/pipeline/rerank.ts +15 -22
  142. package/src/pipeline/search.ts +193 -72
  143. package/src/pipeline/snippet.ts +15 -2
  144. package/src/pipeline/temporal.ts +51 -10
  145. package/src/pipeline/vsearch.ts +250 -152
  146. package/src/publish/attachment-raster.ts +2 -16
  147. package/src/publish/encrypted-export.ts +15 -5
  148. package/src/serve/browse-tree.ts +50 -42
  149. package/src/serve/connectors.ts +2 -1
  150. package/src/serve/context.ts +13 -4
  151. package/src/serve/doc-events.ts +3 -0
  152. package/src/serve/public/app.tsx +49 -21
  153. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  154. package/src/serve/public/components/CaptureModal.tsx +14 -10
  155. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  156. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  157. package/src/serve/public/globals.built.css +1 -1
  158. package/src/serve/public/globals.css +19 -0
  159. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  160. package/src/serve/public/lib/metadata-filter.ts +234 -9
  161. package/src/serve/public/pages/Browse.tsx +61 -27
  162. package/src/serve/public/pages/DocView.tsx +44 -25
  163. package/src/serve/public/pages/GraphView.tsx +8 -3
  164. package/src/serve/resident-runtime.ts +199 -48
  165. package/src/serve/routes/api.ts +98 -67
  166. package/src/serve/routes/links.ts +18 -4
  167. package/src/serve/server.ts +1370 -1180
  168. package/src/serve/spa-bundle-source.ts +52 -27
  169. package/src/serve/status.ts +101 -52
  170. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  171. package/src/serve/watch-reconciliation-shared.ts +42 -4
  172. package/src/serve/watch-reconciliation.ts +21 -8
  173. package/src/serve/watch-service-events.ts +7 -1
  174. package/src/serve/watch-service-hosts.ts +3 -1
  175. package/src/serve/watch-service.ts +46 -21
  176. package/src/serve/watch-snapshot-scan.ts +6 -15
  177. package/src/sessions/archive.ts +20 -8
  178. package/src/sessions/sanitize.ts +38 -18
  179. package/src/sessions/service.ts +180 -102
  180. package/src/store/migrations/036-vector-mirror-state.ts +83 -0
  181. package/src/store/migrations/037-performance-indexes.ts +56 -0
  182. package/src/store/migrations/index.ts +4 -0
  183. package/src/store/sqlite/adapter.ts +1217 -651
  184. package/src/store/sqlite/chunking-policy.ts +15 -1
  185. package/src/store/sqlite/eligibility.ts +110 -70
  186. package/src/store/sqlite/graph-neighbors.ts +71 -46
  187. package/src/store/sqlite/graph-reference-state.ts +27 -3
  188. package/src/store/sqlite/graph-similarity.ts +59 -12
  189. package/src/store/sqlite/metadata-predicate.ts +123 -28
  190. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  191. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  192. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  193. package/src/store/types.ts +32 -0
  194. package/src/store/vector/eligibility.ts +39 -0
  195. package/src/store/vector/lazy.ts +17 -0
  196. package/src/store/vector/partition-index.ts +49 -47
  197. package/src/store/vector/proof-cache.ts +103 -0
  198. package/src/store/vector/sqlite-vec.ts +230 -139
  199. package/src/store/vector/stats.ts +29 -73
  200. package/src/store/vector/status.ts +151 -52
  201. package/src/store/vector/stored-vectors.ts +131 -45
  202. package/src/store/vector/types.ts +10 -0
  203. package/src/store/vector/variant-search.ts +771 -109
  204. package/src/store/vector/variants.ts +785 -144
  205. package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
@@ -2,30 +2,25 @@
2
2
  import { readdirSync } from "node:fs";
3
3
  /**
4
4
  * File walker implementation.
5
- * Walks collection directories using Bun.Glob (`any`) or hierarchical
6
- * availability-aware descent (`local`).
5
+ * Walks collection directories using bounded async readdir with subtree pruning
6
+ * (`any`) or hierarchical availability-aware descent (`local`).
7
7
  *
8
8
  * @module src/ingestion/walker
9
9
  */
10
- // node:fs/promises - Bun has no realpath equivalent for symlink-safe containment.
11
- import { lstat, realpath } from "node:fs/promises";
10
+ // node:fs/promises - Bun has no realpath/lstat/readdir(withFileTypes) equivalents.
11
+ import { lstat, readdir, realpath } from "node:fs/promises";
12
12
  // node:path - Bun has no path manipulation module
13
- import {
14
- extname,
15
- isAbsolute,
16
- join,
17
- normalize as normalizePath,
18
- relative,
19
- resolve,
20
- sep,
21
- } from "node:path";
13
+ import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
22
14
 
23
15
  import type { SkippedEntry, WalkConfig, WalkEntry, WalkerPort } from "./types";
24
16
 
25
17
  import { SUPPORTED_EXTENSIONS } from "../converters/mime";
26
18
  import {
27
- matchesCollectionExclusion,
28
- matchesCollectionSubtreeExclusion,
19
+ type CompiledCollectionExclusions,
20
+ compileCollectionExclusions,
21
+ matchesCompiledExclusion,
22
+ matchesCompiledStrictSubtreeExclusion,
23
+ matchesCompiledSubtreeExclusion,
29
24
  } from "../core/path-rules";
30
25
  import { isCompiledContextPath } from "./compiled-context";
31
26
  import { isRecordVirtualPath } from "./record-path";
@@ -35,6 +30,164 @@ import {
35
30
  isUnprovenDirectoryResult,
36
31
  } from "./source-availability";
37
32
 
33
+ /** Bounded concurrency for lstat() batches and async directory reads. */
34
+ const STAT_CONCURRENCY = 32;
35
+ const READDIR_CONCURRENCY = 16;
36
+
37
+ interface CompiledPatternSegment {
38
+ isGlobstar: boolean;
39
+ /** Compiled matcher for non-dot path segments. */
40
+ glob: Bun.Glob;
41
+ /** Compiled matchers for sub-patterns that explicitly begin with `.`. */
42
+ dotGlobs: Bun.Glob[];
43
+ }
44
+
45
+ interface CompiledPatternBranch {
46
+ glob: Bun.Glob;
47
+ hasExplicitDot: boolean;
48
+ segments: CompiledPatternSegment[] | null;
49
+ }
50
+
51
+ function compilePatternBranch(pattern: string): CompiledPatternBranch {
52
+ const normalized = pattern.replaceAll("\\", "/");
53
+ const glob = new Bun.Glob(pattern);
54
+ const rawSegments = normalized.split("/");
55
+ // If braces span across `/`, fall back to Bun.Glob for dot-aware matching.
56
+ let hasUnbalancedBrace = false;
57
+ let hasExplicitDot = false;
58
+ const segments: CompiledPatternSegment[] = [];
59
+ for (const rawSeg of rawSegments) {
60
+ let depth = 0;
61
+ for (let i = 0; i < rawSeg.length; i += 1) {
62
+ if (rawSeg[i] === "{") depth += 1;
63
+ else if (rawSeg[i] === "}") depth -= 1;
64
+ if (depth < 0) {
65
+ hasUnbalancedBrace = true;
66
+ break;
67
+ }
68
+ }
69
+ if (depth !== 0 || hasUnbalancedBrace) {
70
+ hasUnbalancedBrace = true;
71
+ break;
72
+ }
73
+ const isGlobstar = rawSeg === "**";
74
+ const alternatives =
75
+ rawSeg.startsWith("{") && rawSeg.endsWith("}")
76
+ ? scanPatterns(rawSeg)
77
+ : [rawSeg];
78
+ const dotGlobs: Bun.Glob[] = [];
79
+ for (const alt of alternatives) {
80
+ if (alt.startsWith(".")) {
81
+ hasExplicitDot = true;
82
+ dotGlobs.push(new Bun.Glob(alt));
83
+ }
84
+ }
85
+ segments.push({
86
+ isGlobstar,
87
+ glob: new Bun.Glob(rawSeg),
88
+ dotGlobs,
89
+ });
90
+ }
91
+ if (hasUnbalancedBrace) {
92
+ return {
93
+ glob,
94
+ hasExplicitDot: /(?:^|[/,{])\./.test(normalized),
95
+ segments: null,
96
+ };
97
+ }
98
+ return { glob, hasExplicitDot, segments };
99
+ }
100
+
101
+ function segmentMatches(seg: CompiledPatternSegment, name: string): boolean {
102
+ if (name.startsWith(".")) {
103
+ for (const dotGlob of seg.dotGlobs) {
104
+ if (dotGlob.match(name)) return true;
105
+ }
106
+ return false;
107
+ }
108
+ return seg.glob.match(name);
109
+ }
110
+
111
+ function matchBranchSegments(
112
+ segments: readonly CompiledPatternSegment[],
113
+ pathSegments: readonly string[],
114
+ prefixOnly: boolean
115
+ ): boolean {
116
+ const pLen = segments.length;
117
+ const sLen = pathSegments.length;
118
+ // Memoized DP over (pIdx, sIdx) prevents exponential blowup on multiple `**`.
119
+ const memo = new Int8Array((pLen + 1) * (sLen + 1));
120
+ const visit = (pIdx: number, sIdx: number): boolean => {
121
+ const key = pIdx * (sLen + 1) + sIdx;
122
+ const cached = memo[key];
123
+ if (cached !== 0) return cached === 1;
124
+ let ok = false;
125
+ if (sIdx === sLen) {
126
+ if (prefixOnly) {
127
+ ok = pIdx < pLen || (pIdx > 0 && segments[pIdx - 1]!.isGlobstar);
128
+ } else {
129
+ ok = true;
130
+ for (let i = pIdx; i < pLen; i += 1) {
131
+ if (!segments[i]!.isGlobstar) {
132
+ ok = false;
133
+ break;
134
+ }
135
+ }
136
+ }
137
+ } else if (pIdx < pLen) {
138
+ const seg = segments[pIdx]!;
139
+ const name = pathSegments[sIdx]!;
140
+ if (seg.isGlobstar) {
141
+ // Under `{ dot: false }`, `**` matches zero or more non-dot segments.
142
+ ok =
143
+ visit(pIdx + 1, sIdx) ||
144
+ (!name.startsWith(".") && visit(pIdx, sIdx + 1));
145
+ } else if (segmentMatches(seg, name)) {
146
+ ok = visit(pIdx + 1, sIdx + 1);
147
+ }
148
+ }
149
+ memo[key] = ok ? 1 : -1;
150
+ return ok;
151
+ };
152
+ return visit(0, 0);
153
+ }
154
+
155
+ function hasDotSegment(relPath: string): boolean {
156
+ return relPath.startsWith(".") || relPath.includes("/.");
157
+ }
158
+
159
+ function branchMatchesPath(
160
+ branch: CompiledPatternBranch,
161
+ relPath: string
162
+ ): boolean {
163
+ if (!hasDotSegment(relPath)) {
164
+ return branch.glob.match(relPath);
165
+ }
166
+ if (!branch.hasExplicitDot) {
167
+ return false;
168
+ }
169
+ if (!branch.segments) {
170
+ return branch.glob.match(relPath);
171
+ }
172
+ return matchBranchSegments(branch.segments, relPath.split("/"), false);
173
+ }
174
+
175
+ function branchCanDescendDir(
176
+ branch: CompiledPatternBranch,
177
+ dirRelPath: string
178
+ ): boolean {
179
+ if (!hasDotSegment(dirRelPath)) {
180
+ return true;
181
+ }
182
+ if (!branch.hasExplicitDot) {
183
+ return false;
184
+ }
185
+ if (!branch.segments) {
186
+ return true;
187
+ }
188
+ return matchBranchSegments(branch.segments, dirRelPath.split("/"), true);
189
+ }
190
+
38
191
  /**
39
192
  * Regex to detect dangerous patterns with parent directory traversal.
40
193
  * Matches ".." at start, after "/", or after "\" (Windows).
@@ -155,52 +308,64 @@ async function safeRelPath(
155
308
  }
156
309
  }
157
310
 
158
- /**
159
- * Check if a file extension matches the include list.
160
- * Include list contains extensions like ".md" or "md" (normalized).
161
- * When include is empty, falls back to SUPPORTED_EXTENSIONS plus extensions
162
- * made convertible by explicit adapter configuration.
163
- */
164
- function matchesInclude(
165
- relPath: string,
166
- include: string[],
167
- additionalDefaultExtensions: string[]
168
- ): boolean {
169
- const ext = extname(relPath).toLowerCase();
170
- if (!ext) {
171
- return false;
172
- }
173
-
174
- if (include.length === 0 && SUPPORTED_EXTENSIONS.includes(ext)) {
175
- return true;
176
- }
177
-
178
- const effectiveInclude =
179
- include.length === 0 ? additionalDefaultExtensions : include;
180
-
181
- return effectiveInclude.some((inc) => {
182
- const normalizedInc = inc.startsWith(".")
183
- ? inc.toLowerCase()
184
- : `.${inc.toLowerCase()}`;
185
- return ext === normalizedInc;
186
- });
187
- }
188
-
189
311
  type PathEligibilityConfig = Pick<
190
312
  WalkConfig,
191
313
  "additionalDefaultExtensions" | "exclude" | "include" | "pattern"
192
314
  >;
193
315
 
194
- /**
195
- * Check collection-relative path eligibility without touching the filesystem.
196
- * This intentionally remains usable for deleted paths so incremental sync can
197
- * mark previously indexed documents inactive.
198
- */
199
- export function matchesWalkPath(
200
- relPath: string,
316
+ interface CompiledWalkMatcher {
317
+ matchPattern: ((normalizedPath: string) => boolean) | null;
318
+ exclusions: CompiledCollectionExclusions;
319
+ includeExtensions: ReadonlySet<string>;
320
+ }
321
+
322
+ const DEFAULT_SUPPORTED_EXTENSION_SET = new Set(
323
+ SUPPORTED_EXTENSIONS.map((ext) => ext.toLowerCase())
324
+ );
325
+
326
+ /** Pre-compile glob, exclusion rules, and extension set once per walk. */
327
+ function compileWalkMatcher(
201
328
  config: PathEligibilityConfig
329
+ ): CompiledWalkMatcher {
330
+ let matchPattern: ((normalizedPath: string) => boolean) | null = null;
331
+ try {
332
+ const glob = new Bun.Glob(config.pattern);
333
+ matchPattern = glob.match.bind(glob);
334
+ } catch {
335
+ matchPattern = null;
336
+ }
337
+ const exclusions = compileCollectionExclusions(config.exclude);
338
+ let includeExtensions: ReadonlySet<string>;
339
+ if (config.include.length === 0) {
340
+ const extra = config.additionalDefaultExtensions ?? [];
341
+ if (extra.length === 0) {
342
+ includeExtensions = DEFAULT_SUPPORTED_EXTENSION_SET;
343
+ } else {
344
+ const merged = new Set(DEFAULT_SUPPORTED_EXTENSION_SET);
345
+ for (const inc of extra) {
346
+ const lower = inc.toLowerCase();
347
+ merged.add(lower.startsWith(".") ? lower : `.${lower}`);
348
+ }
349
+ includeExtensions = merged;
350
+ }
351
+ } else {
352
+ const explicit = new Set<string>();
353
+ for (const inc of config.include) {
354
+ const lower = inc.toLowerCase();
355
+ explicit.add(lower.startsWith(".") ? lower : `.${lower}`);
356
+ }
357
+ includeExtensions = explicit;
358
+ }
359
+ return { matchPattern, exclusions, includeExtensions };
360
+ }
361
+
362
+ function matchesCompiledWalkPath(
363
+ relPath: string,
364
+ matcher: CompiledWalkMatcher
202
365
  ): boolean {
203
- const normalizedPath = relPath.replaceAll("\\", "/");
366
+ const normalizedPath = relPath.includes("\\")
367
+ ? relPath.replaceAll("\\", "/")
368
+ : relPath;
204
369
  if (
205
370
  isAbsolute(normalizedPath) ||
206
371
  DANGEROUS_PATTERN_REGEX.test(normalizedPath) ||
@@ -209,26 +374,47 @@ export function matchesWalkPath(
209
374
  ) {
210
375
  return false;
211
376
  }
212
-
213
- let matchesPattern = false;
214
- try {
215
- matchesPattern = new Bun.Glob(config.pattern).match(normalizedPath);
216
- } catch {
377
+ if (!matcher.matchPattern?.(normalizedPath)) {
217
378
  return false;
218
379
  }
219
- if (!matchesPattern) {
380
+ if (matchesCompiledExclusion(normalizedPath, matcher.exclusions)) {
220
381
  return false;
221
382
  }
222
-
223
- if (matchesCollectionExclusion(normalizedPath, config.exclude)) {
383
+ const ext = extname(normalizedPath).toLowerCase();
384
+ if (!ext) {
224
385
  return false;
225
386
  }
387
+ return matcher.includeExtensions.has(ext);
388
+ }
226
389
 
227
- return matchesInclude(
228
- normalizedPath,
229
- config.include,
230
- config.additionalDefaultExtensions ?? []
231
- );
390
+ /**
391
+ * Check collection-relative path eligibility without touching the filesystem.
392
+ * This intentionally remains usable for deleted paths so incremental sync can
393
+ * mark previously indexed documents inactive.
394
+ */
395
+ export function matchesWalkPath(
396
+ relPath: string,
397
+ config: PathEligibilityConfig
398
+ ): boolean {
399
+ return matchesCompiledWalkPath(relPath, compileWalkMatcher(config));
400
+ }
401
+
402
+ async function runBounded<T>(
403
+ items: readonly T[],
404
+ limit: number,
405
+ worker: (item: T) => Promise<void>
406
+ ): Promise<void> {
407
+ if (items.length === 0) return;
408
+ let nextIndex = 0;
409
+ const workerCount = Math.min(limit, items.length);
410
+ const runners = Array.from({ length: workerCount }, async () => {
411
+ while (nextIndex < items.length) {
412
+ const current = nextIndex;
413
+ nextIndex += 1;
414
+ await worker(items[current]!);
415
+ }
416
+ });
417
+ await Promise.all(runners);
232
418
  }
233
419
 
234
420
  function pushUnprovenDirectorySkip(
@@ -268,7 +454,12 @@ export class FileWalker implements WalkerPort {
268
454
  return this.walkAny(config);
269
455
  }
270
456
 
271
- /** Legacy Bun.Glob traversal — behaviorally unchanged for `any`. */
457
+ /**
458
+ * Bounded async readdir traversal for `any` mode: prunes excluded subtrees
459
+ * before descending, avoids redundant per-file `realpath()` for regular
460
+ * files inside canonical `rootReal`, and runs `stat()` with bounded
461
+ * concurrency. Symlinks continue through `safeRelPath` containment checks.
462
+ */
272
463
  private async walkAny(config: WalkConfig): Promise<{
273
464
  entries: WalkEntry[];
274
465
  skipped: SkippedEntry[];
@@ -302,69 +493,207 @@ export class FileWalker implements WalkerPort {
302
493
  return { entries, skipped };
303
494
  }
304
495
 
305
- const matches = new Set<string>();
306
- for (const pattern of patterns) {
307
- const glob = new Bun.Glob(pattern);
308
- for await (const match of glob.scan({
309
- cwd: rootReal,
310
- absolute: true,
311
- onlyFiles: true,
312
- followSymlinks: false,
313
- })) {
314
- matches.add(normalizePath(match));
315
- }
316
- }
317
-
318
- for (const matchedPath of [...matches].sort()) {
319
- // Security: Compute safe relative path (validates file is within root)
320
- const safePath = await safeRelPath(rootReal, matchedPath);
321
- if (safePath === null) {
322
- // File outside root or unresolvable - silently skip (security)
323
- continue;
496
+ const matcher = compileWalkMatcher(config);
497
+ const patternBranches = patterns.map((pattern) =>
498
+ compilePatternBranch(pattern)
499
+ );
500
+ const anyBranchHasSlashBrace = patternBranches.some(
501
+ (branch) => branch.segments === null
502
+ );
503
+ const anyBranchHasExplicitDot = patternBranches.some(
504
+ (branch) => branch.hasExplicitDot
505
+ );
506
+
507
+ const candidates: Array<{ absPath: string; relPath: string }> = [];
508
+ const seenAbsPaths = new Set<string>();
509
+ const symlinksToCheck: Array<{ absPath: string }> = [];
510
+
511
+ if (anyBranchHasSlashBrace) {
512
+ // Brace alternatives that span path segments (e.g., `**/{a/b,c}`) have
513
+ // Bun.Glob.scan()-specific semantics that differ from Bun.Glob.match().
514
+ // Delegate discovery to Bun.Glob.scan() for exact base parity.
515
+ for (const pattern of patterns) {
516
+ const glob = new Bun.Glob(pattern);
517
+ for await (const match of glob.scan({
518
+ cwd: rootReal,
519
+ onlyFiles: true,
520
+ followSymlinks: false,
521
+ dot: false,
522
+ })) {
523
+ const absPath = join(rootReal, match);
524
+ const safePath = await safeRelPath(rootReal, absPath);
525
+ if (safePath === null) continue;
526
+ if (seenAbsPaths.has(safePath.absPath)) continue;
527
+ seenAbsPaths.add(safePath.absPath);
528
+ if (!matchesCompiledWalkPath(safePath.relPath, matcher)) {
529
+ skipped.push({
530
+ absPath: safePath.absPath,
531
+ relPath: safePath.relPath,
532
+ reason: "EXCLUDED",
533
+ });
534
+ continue;
535
+ }
536
+ candidates.push(safePath);
537
+ }
324
538
  }
325
- const { absPath, relPath } = safePath;
326
-
327
- if (!matchesWalkPath(relPath, config)) {
328
- skipped.push({
329
- absPath,
330
- relPath,
331
- reason: "EXCLUDED",
539
+ } else {
540
+ let currentLevel: Array<{ absPath: string; relPath: string }> = [
541
+ { absPath: rootReal, relPath: "" },
542
+ ];
543
+
544
+ while (currentLevel.length > 0) {
545
+ const nextLevel: Array<{ absPath: string; relPath: string }> = [];
546
+ await runBounded(currentLevel, READDIR_CONCURRENCY, async (dir) => {
547
+ let dirents;
548
+ try {
549
+ dirents = await readdir(dir.absPath, { withFileTypes: true });
550
+ } catch (error) {
551
+ if (dir.relPath === "") {
552
+ throw error;
553
+ }
554
+ return;
555
+ }
556
+ for (const dirent of dirents) {
557
+ const name = dirent.name;
558
+ if (name === "" || name === "." || name === "..") continue;
559
+ if (name.includes("\0")) continue;
560
+ // Fast skip dot entries when no pattern branch explicitly targets dots.
561
+ if (!anyBranchHasExplicitDot && name.startsWith(".")) continue;
562
+
563
+ const childAbs = join(dir.absPath, name);
564
+ const childRel =
565
+ dir.relPath === "" ? name : `${dir.relPath}/${toPosixPath(name)}`;
566
+
567
+ if (dirent.isSymbolicLink()) {
568
+ // Never descend through directory symlinks; validate leaf symlinks
569
+ // via safeRelPath below.
570
+ symlinksToCheck.push({ absPath: childAbs });
571
+ continue;
572
+ }
573
+
574
+ if (dirent.isDirectory()) {
575
+ if (isRecordVirtualPath(childRel)) continue;
576
+ // Prune only strictly fully excluded subtrees without emitting
577
+ // synthetic directory EXCLUDED receipts that the include glob never selected.
578
+ if (
579
+ matchesCompiledStrictSubtreeExclusion(
580
+ childRel,
581
+ matcher.exclusions
582
+ )
583
+ ) {
584
+ continue;
585
+ }
586
+ if (
587
+ name.startsWith(".") &&
588
+ !patternBranches.some((branch) =>
589
+ branchCanDescendDir(branch, childRel)
590
+ )
591
+ ) {
592
+ continue;
593
+ }
594
+ nextLevel.push({ absPath: childAbs, relPath: childRel });
595
+ continue;
596
+ }
597
+
598
+ if (!dirent.isFile()) continue;
599
+
600
+ // Pattern gate preserves per-branch, per-segment Bun.Glob.scan({ dot: false }) semantics.
601
+ if (
602
+ !patternBranches.some((branch) =>
603
+ branchMatchesPath(branch, childRel)
604
+ )
605
+ ) {
606
+ continue;
607
+ }
608
+
609
+ // Regular file under canonical rootReal with no symlink ancestors:
610
+ // childAbs is already canonical and contained within rootReal.
611
+ if (seenAbsPaths.has(childAbs)) continue;
612
+ seenAbsPaths.add(childAbs);
613
+
614
+ if (!matchesCompiledWalkPath(childRel, matcher)) {
615
+ skipped.push({
616
+ absPath: childAbs,
617
+ relPath: childRel,
618
+ reason: "EXCLUDED",
619
+ });
620
+ continue;
621
+ }
622
+ candidates.push({ absPath: childAbs, relPath: childRel });
623
+ }
332
624
  });
333
- continue;
625
+ currentLevel = nextLevel;
334
626
  }
627
+ }
628
+
629
+ // Resolve and containment-check symlinks (matching Bun.Glob followSymlinks:false
630
+ // + safeRelPath semantics: escaping/broken/directory symlinks are skipped).
631
+ if (symlinksToCheck.length > 0) {
632
+ await runBounded(
633
+ symlinksToCheck,
634
+ STAT_CONCURRENCY,
635
+ async ({ absPath }) => {
636
+ const safePath = await safeRelPath(rootReal, absPath);
637
+ if (safePath === null) return;
638
+ if (
639
+ !patternBranches.some((branch) =>
640
+ branchMatchesPath(branch, safePath.relPath)
641
+ )
642
+ ) {
643
+ return;
644
+ }
645
+ if (seenAbsPaths.has(safePath.absPath)) return;
646
+ seenAbsPaths.add(safePath.absPath);
647
+ if (!matchesCompiledWalkPath(safePath.relPath, matcher)) {
648
+ skipped.push({
649
+ absPath: safePath.absPath,
650
+ relPath: safePath.relPath,
651
+ reason: "EXCLUDED",
652
+ });
653
+ return;
654
+ }
655
+ candidates.push(safePath);
656
+ }
657
+ );
658
+ }
335
659
 
336
- // Stat file
337
- const file = Bun.file(absPath);
338
- let stat: { size: number; mtime: Date; ctime?: Date; birthtime?: Date };
660
+ // Bounded concurrent lstat() across matched candidates: rejects entries
661
+ // swapped to a symlink after readdir without adding an extra syscall.
662
+ await runBounded(candidates, STAT_CONCURRENCY, async (candidate) => {
663
+ let fileStat: Awaited<ReturnType<typeof lstat>>;
339
664
  try {
340
- stat = await file.stat();
665
+ fileStat = await lstat(candidate.absPath);
341
666
  } catch {
342
- // Can't stat file, skip silently
343
- continue;
667
+ return;
344
668
  }
345
-
346
- // Check maxBytes BEFORE reading
347
- if (stat.size > config.maxBytes) {
669
+ if (!fileStat.isFile()) {
670
+ return;
671
+ }
672
+ if (fileStat.size > config.maxBytes) {
348
673
  skipped.push({
349
- absPath,
350
- relPath,
674
+ absPath: candidate.absPath,
675
+ relPath: candidate.relPath,
351
676
  reason: "TOO_LARGE",
352
- size: stat.size,
677
+ size: fileStat.size,
353
678
  });
354
- continue;
679
+ return;
355
680
  }
356
-
357
681
  entries.push({
358
- absPath,
359
- relPath,
360
- size: stat.size,
361
- mtime: stat.mtime.toISOString(),
362
- ctime: (stat.birthtime ?? stat.ctime ?? stat.mtime).toISOString(),
682
+ absPath: candidate.absPath,
683
+ relPath: candidate.relPath,
684
+ size: fileStat.size,
685
+ mtime: fileStat.mtime.toISOString(),
686
+ ctime: (
687
+ fileStat.birthtime ??
688
+ fileStat.ctime ??
689
+ fileStat.mtime
690
+ ).toISOString(),
363
691
  });
364
- }
692
+ });
365
693
 
366
694
  // Sort entries by relPath for deterministic output
367
695
  entries.sort((a, b) => a.relPath.localeCompare(b.relPath));
696
+ skipped.sort((a, b) => a.relPath.localeCompare(b.relPath));
368
697
 
369
698
  return { entries, skipped };
370
699
  }
@@ -426,6 +755,8 @@ export class FileWalker implements WalkerPort {
426
755
  }
427
756
  }
428
757
 
758
+ const matcher = compileWalkMatcher(config);
759
+ const regularCandidates: Array<{ absPath: string; relPath: string }> = [];
429
760
  const queue: Array<{ absPath: string; relPath: string }> = [
430
761
  { absPath: rootReal, relPath: "" },
431
762
  ];
@@ -473,7 +804,7 @@ export class FileWalker implements WalkerPort {
473
804
  // No-follow: symlinks are leaf candidates so the guarded content open
474
805
  // can refuse them with a receipt; never descend through them.
475
806
  if (dirent.isSymbolicLink()) {
476
- if (!matchesWalkPath(childRel, config)) {
807
+ if (!matchesCompiledWalkPath(childRel, matcher)) {
477
808
  skipped.push({
478
809
  absPath: childAbs,
479
810
  relPath: childRel,
@@ -507,7 +838,7 @@ export class FileWalker implements WalkerPort {
507
838
  }
508
839
 
509
840
  if (dirent.isDirectory()) {
510
- if (matchesCollectionSubtreeExclusion(childRel, config.exclude)) {
841
+ if (matchesCompiledSubtreeExclusion(childRel, matcher.exclusions)) {
511
842
  skipped.push({
512
843
  absPath: childAbs,
513
844
  relPath: childRel,
@@ -528,57 +859,53 @@ export class FileWalker implements WalkerPort {
528
859
  continue;
529
860
  }
530
861
 
531
- const safePath = await safeRelPath(rootReal, childAbs);
532
- if (safePath === null) {
533
- continue;
534
- }
535
- const { absPath, relPath } = safePath;
536
-
537
- if (!matchesWalkPath(relPath, config)) {
862
+ // Regular file inside canonical rootReal with no symlink ancestors:
863
+ // childAbs is already canonical and contained, skipping per-file realpath().
864
+ if (!matchesCompiledWalkPath(childRel, matcher)) {
538
865
  skipped.push({
539
- absPath,
540
- relPath,
866
+ absPath: childAbs,
867
+ relPath: childRel,
541
868
  reason: "EXCLUDED",
542
869
  });
543
870
  continue;
544
871
  }
872
+ regularCandidates.push({ absPath: childAbs, relPath: childRel });
873
+ }
874
+ }
545
875
 
546
- const file = Bun.file(absPath);
547
- let fileStat: {
548
- size: number;
549
- mtime: Date;
550
- ctime?: Date;
551
- birthtime?: Date;
552
- };
553
- try {
554
- fileStat = await file.stat();
555
- } catch {
556
- continue;
557
- }
558
-
559
- if (fileStat.size > config.maxBytes) {
560
- skipped.push({
561
- absPath,
562
- relPath,
563
- reason: "TOO_LARGE",
564
- size: fileStat.size,
565
- });
566
- continue;
567
- }
876
+ await runBounded(regularCandidates, STAT_CONCURRENCY, async (candidate) => {
877
+ let fileStat: Awaited<ReturnType<typeof lstat>>;
878
+ try {
879
+ fileStat = await lstat(candidate.absPath);
880
+ } catch {
881
+ return;
882
+ }
883
+ if (!fileStat.isFile()) {
884
+ return;
885
+ }
568
886
 
569
- entries.push({
570
- absPath,
571
- relPath,
887
+ if (fileStat.size > config.maxBytes) {
888
+ skipped.push({
889
+ absPath: candidate.absPath,
890
+ relPath: candidate.relPath,
891
+ reason: "TOO_LARGE",
572
892
  size: fileStat.size,
573
- mtime: fileStat.mtime.toISOString(),
574
- ctime: (
575
- fileStat.birthtime ??
576
- fileStat.ctime ??
577
- fileStat.mtime
578
- ).toISOString(),
579
893
  });
894
+ return;
580
895
  }
581
- }
896
+
897
+ entries.push({
898
+ absPath: candidate.absPath,
899
+ relPath: candidate.relPath,
900
+ size: fileStat.size,
901
+ mtime: fileStat.mtime.toISOString(),
902
+ ctime: (
903
+ fileStat.birthtime ??
904
+ fileStat.ctime ??
905
+ fileStat.mtime
906
+ ).toISOString(),
907
+ });
908
+ });
582
909
 
583
910
  entries.sort((a, b) => a.relPath.localeCompare(b.relPath));
584
911
  return { entries, skipped };