@mnemonik/shared 7.154.3 → 7.155.2

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 (46) hide show
  1. package/dist/ast/grammars.d.ts +4 -2
  2. package/dist/ast/grammars.d.ts.map +1 -1
  3. package/dist/ast/grammars.js +45 -3
  4. package/dist/ast/grammars.js.map +1 -1
  5. package/dist/codeScanner.d.ts +26 -329
  6. package/dist/codeScanner.d.ts.map +1 -1
  7. package/dist/codeScanner.js +65 -1141
  8. package/dist/codeScanner.js.map +1 -1
  9. package/dist/fileSelection.d.ts +451 -0
  10. package/dist/fileSelection.d.ts.map +1 -0
  11. package/dist/fileSelection.js +1256 -0
  12. package/dist/fileSelection.js.map +1 -0
  13. package/dist/hookTrace.d.ts +40 -0
  14. package/dist/hookTrace.d.ts.map +1 -1
  15. package/dist/hookTrace.js +126 -0
  16. package/dist/hookTrace.js.map +1 -1
  17. package/dist/index.d.ts +3 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/runtimeAssets.d.ts +12 -0
  22. package/dist/runtimeAssets.d.ts.map +1 -0
  23. package/dist/runtimeAssets.js +43 -0
  24. package/dist/runtimeAssets.js.map +1 -0
  25. package/dist/sourceRedaction.d.ts +45 -1
  26. package/dist/sourceRedaction.d.ts.map +1 -1
  27. package/dist/sourceRedaction.js +62 -22
  28. package/dist/sourceRedaction.js.map +1 -1
  29. package/dist/sourceRedactionPool.d.ts +198 -0
  30. package/dist/sourceRedactionPool.d.ts.map +1 -0
  31. package/dist/sourceRedactionPool.js +756 -0
  32. package/dist/sourceRedactionPool.js.map +1 -0
  33. package/dist/vueSource.d.ts +0 -2
  34. package/dist/vueSource.d.ts.map +1 -1
  35. package/dist/vueSource.js +8 -19
  36. package/dist/vueSource.js.map +1 -1
  37. package/package.json +5 -1
  38. package/src/ast/grammars.ts +52 -7
  39. package/src/codeScanner.ts +121 -1321
  40. package/src/fileSelection.ts +1440 -0
  41. package/src/hookTrace.ts +143 -0
  42. package/src/index.ts +31 -2
  43. package/src/runtimeAssets.ts +49 -0
  44. package/src/sourceRedaction.ts +85 -20
  45. package/src/sourceRedactionPool.ts +877 -0
  46. package/src/vueSource.ts +8 -23
@@ -0,0 +1,1256 @@
1
+ /**
2
+ * Which files the scanner indexes under a root: the walk, every ignore rule it
3
+ * applies (.gitignore, .mnemonikignore, .gitattributes, the built-in and soft
4
+ * defaults, secret files, protected paths, nested projects) and its limits.
5
+ *
6
+ * It is its own module, apart from codeScanner.ts, so a caller that only needs
7
+ * the selection (the CLI's estimate before the first scan) loads none of the
8
+ * chunker, the source redaction or the compilers behind it (26 Oct 2026: the
9
+ * public CLI bundled the Svelte and Vue compilers into its estimate). It is the
10
+ * scanner's own selection, not a copy: CodeScanner extends FileSelector.
11
+ * Exported alone as `@mnemonik/shared/file-selection`.
12
+ */
13
+ import { readdir, readFile, open, lstat, realpath } from 'fs/promises';
14
+ import { constants } from 'fs';
15
+ import { join, relative, extname, sep, resolve, dirname } from 'path';
16
+ import ignore from 'ignore';
17
+ import { debug as logDebug } from './logger.js';
18
+ import { isProtectedLocalPath, protectedLocalPaths } from './protectedPaths.js';
19
+ import { readIdentityFile } from './projectIdentityFile.js';
20
+ import { classifyForIndex, gitattributesCanReinclude, parseGitattributes, softDefaultForDirectory, } from './indexClassifier.js';
21
+ /**
22
+ * First budget for one filesystem operation (readdir, lstat, read). It keeps a
23
+ * hung mount (a dead network share, a stalled cloud placeholder) from holding
24
+ * the walk forever, which is why it has existed since the scanner did.
25
+ *
26
+ * Five seconds alone was the whole story until October 2026, and a slow but
27
+ * working filesystem (network home, WSL across the 9P bridge, a cloud drive
28
+ * fetching on demand) lost files in silence: the walk was merely marked
29
+ * incomplete. So an operation that runs out of this budget is tried once more
30
+ * with FILE_OP_RETRY_TIMEOUT_MS, and what still fails is counted in the walk's
31
+ * `unreadable` total, which the daemon reports to the server as a blind spot.
32
+ */
33
+ const FILE_OP_TIMEOUT_MS = 5000;
34
+ /** The second, last attempt at an operation the first budget did not cover. */
35
+ const FILE_OP_RETRY_TIMEOUT_MS = 30_000;
36
+ /** A filesystem operation that did not finish in its budget. */
37
+ class FileOpTimeoutError extends Error {
38
+ constructor(label, timeoutMs) {
39
+ super(`${label} timed out after ${timeoutMs} ms`);
40
+ this.name = 'FileOpTimeoutError';
41
+ }
42
+ }
43
+ function timedOp(op, timeoutMs, label) {
44
+ let timer;
45
+ return Promise.race([
46
+ op,
47
+ new Promise((_resolve, reject) => {
48
+ timer = setTimeout(() => reject(new FileOpTimeoutError(label, timeoutMs)), timeoutMs);
49
+ }),
50
+ ]).finally(() => clearTimeout(timer));
51
+ }
52
+ /**
53
+ * Run one filesystem operation within FILE_OP_TIMEOUT_MS, and once more within
54
+ * FILE_OP_RETRY_TIMEOUT_MS if the first attempt timed out. Other errors are not
55
+ * retried: ENOENT, EACCES and the containment refusals answer the same way twice.
56
+ */
57
+ export async function fileOp(op, label, budgets = {
58
+ first: FILE_OP_TIMEOUT_MS,
59
+ retry: FILE_OP_RETRY_TIMEOUT_MS,
60
+ }) {
61
+ try {
62
+ return await timedOp(op(), budgets.first, label);
63
+ }
64
+ catch (error) {
65
+ if (!(error instanceof FileOpTimeoutError))
66
+ throw error;
67
+ return timedOp(op(), budgets.retry, label);
68
+ }
69
+ }
70
+ export function statTuple(stats) {
71
+ return { size: stats.size, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs, ino: stats.ino };
72
+ }
73
+ /** How many unreadable entries a walk names (doctor shows them); the rest are counted. */
74
+ const UNREADABLE_SAMPLES = 5;
75
+ /** An entry the walk could not read: the walk is no longer complete, and it counts. */
76
+ export function markUnreadable(walk, path, error) {
77
+ walk.complete = false;
78
+ walk.unreadable = (walk.unreadable ?? 0) + 1;
79
+ walk.unreadableSamples ??= [];
80
+ if (walk.unreadableSamples.length < UNREADABLE_SAMPLES)
81
+ walk.unreadableSamples.push({
82
+ path,
83
+ reason: error?.code ??
84
+ (error instanceof Error ? error.message : 'unreadable'),
85
+ });
86
+ }
87
+ /**
88
+ * A directory's identity: device and inode as exact integers. Read with bigint
89
+ * stats because a 64-bit inode above 2^53 loses precision as a number, and two
90
+ * distinct directories could then share a key. Null where the filesystem
91
+ * reports no inode (some Windows filesystems), which cannot identify a loop.
92
+ */
93
+ async function directoryKey(path) {
94
+ const stats = await lstat(path, { bigint: true });
95
+ return stats.ino ? `${stats.dev}:${stats.ino}` : null;
96
+ }
97
+ /**
98
+ * Enter a directory unless it is one of its own ancestors. Returns the
99
+ * function that leaves it again (call it once its subtree is walked), or null
100
+ * for a cycle, which is not walked and makes the walk incomplete, so the
101
+ * removed-files diff never treats what it did not see as deleted.
102
+ */
103
+ export async function enterDirectory(walk, path) {
104
+ let key;
105
+ try {
106
+ key = await directoryKey(path);
107
+ }
108
+ catch {
109
+ key = null; // the walk's own lstat already succeeded; without a key, no loop can be shown
110
+ }
111
+ if (key === null)
112
+ return () => undefined;
113
+ walk.ancestors ??= new Set();
114
+ if (walk.ancestors.has(key)) {
115
+ markUnreadable(walk, path, Object.assign(new Error('directory cycle'), { code: 'ELOOP' }));
116
+ return null;
117
+ }
118
+ const entered = key;
119
+ walk.ancestors.add(entered);
120
+ return () => {
121
+ walk.ancestors?.delete(entered);
122
+ };
123
+ }
124
+ /**
125
+ * Directory basenames the scanner never indexes, across every ecosystem -
126
+ * generated output, package-manager/build caches, and vendored deps. SINGLE
127
+ * SOURCE OF TRUTH: the scanner package's discovery + watch walks import this
128
+ * (`packages/scanner/src/{discovery,watcher}.ts`) and `src/core/utils.ts`
129
+ * derives from it, so every ignore surface agrees instead of drifting (the
130
+ * pre-2026-07 state had four divergent copies). Add only UNAMBIGUOUS names -
131
+ * a project's own `.gitignore` / `.mnemonikignore` covers the ambiguous,
132
+ * project-specific cases (`vendor/`, custom dirs) hierarchically.
133
+ */
134
+ export const BUILT_IN_IGNORE_DIRS = [
135
+ // JS / web
136
+ 'node_modules',
137
+ '.next',
138
+ '.nuxt',
139
+ '.output',
140
+ 'dist',
141
+ 'build',
142
+ 'coverage',
143
+ '.turbo',
144
+ '.vercel',
145
+ '.svelte-kit',
146
+ '.angular',
147
+ '.astro',
148
+ '.parcel-cache',
149
+ 'bower_components',
150
+ // Python
151
+ 'venv',
152
+ '.venv',
153
+ 'env',
154
+ '__pycache__',
155
+ '.tox',
156
+ '.mypy_cache',
157
+ '.pytest_cache',
158
+ '.ruff_cache',
159
+ // Native mobile - iOS / Android / React Native / Flutter (2026-07-11 Pods incident)
160
+ 'Pods',
161
+ 'DerivedData',
162
+ '.gradle',
163
+ '.expo',
164
+ '.dart_tool',
165
+ // Infra / cloud
166
+ '.terraform',
167
+ 'cdk.out',
168
+ '.serverless',
169
+ // Build systems, caches, VCS
170
+ 'target',
171
+ 'bin',
172
+ 'obj',
173
+ '.cache',
174
+ '.git',
175
+ '.svn',
176
+ '.hg',
177
+ // The coding agent's captured shell environment, written as .sh files.
178
+ // Harmless while only source extensions were collected; the moment shell
179
+ // scripts became collectable these scanned as project code, which would put
180
+ // an agent's own shell state into the user's searchable memory.
181
+ //
182
+ // Scoped to this one directory name deliberately. `.claude/` at large holds
183
+ // real project content - `.claude/rules.md` is indexed on purpose
184
+ // (tests/CodeScannerIgnorePatterns.test.ts), and only `.claude/worktrees/`
185
+ // is suppressed, by the generic nested-git-boundary rule.
186
+ 'shell-snapshots',
187
+ ];
188
+ /**
189
+ * Non-directory built-in ignore patterns (files, globs, and the segment-
190
+ * anchored fixture rule), combined with BUILT_IN_IGNORE_DIRS to form
191
+ * DEFAULT_OPTIONS.ignorePatterns. See `shouldIgnore` for match semantics.
192
+ *
193
+ * `/tests/fixtures/*`: leading '/' = segment-anchored - matches tests/fixtures/
194
+ * at the path root or immediately after a '/', so nested packages/x/tests/
195
+ * fixtures/ are excluded but integration-tests/fixtures/ is NOT. Fixture
196
+ * snapshot dirs were being indexed as real source and outranking the genuine
197
+ * file in code_search. (Subprojects and linked worktrees are excluded
198
+ * generically by the isProjectBoundary rule below, not a path convention.)
199
+ */
200
+ export const BUILT_IN_IGNORE_FILE_PATTERNS = [
201
+ // NOTE: the `.env` family and every other secret-bearing FILE KIND lives in
202
+ // `isSecretFile` below, not here. This glob engine cannot express negation
203
+ // (`.env.example` must stay collectable) and its unanchored substring
204
+ // matching would make `.env.*` also swallow `.environment.ts`.
205
+ //
206
+ // `/tests/fixtures/*` used to live here. It is now a soft default in
207
+ // indexClassifier.ts (test fixtures, R2), which a project can re-include.
208
+ '.DS_Store',
209
+ '*.log',
210
+ '*.lock',
211
+ 'package-lock.json',
212
+ 'yarn.lock',
213
+ '*.min.js',
214
+ '*.min.css',
215
+ '*.bundle.js',
216
+ '*.legacy.js',
217
+ '*.map',
218
+ ];
219
+ /**
220
+ * Files whose CONTENT is a credential rather than code. Today these are
221
+ * excluded only INCIDENTALLY - `.pem`, `.key` and friends carry no
222
+ * allowlisted extension, so nothing chunks them. That protection evaporates
223
+ * the moment the extension allowlist widens (as it did for `.sh`/`.lua`), so
224
+ * the exclusion is made explicit here and becomes a defended invariant:
225
+ * unlike `ignorePatterns`, this predicate is NOT caller-overridable.
226
+ *
227
+ * Expressed as a predicate rather than glob strings because `shouldIgnore`'s
228
+ * engine has no negation and matches globs as unanchored substrings - neither
229
+ * property can state "every `.env.*` EXCEPT `.env.example`".
230
+ *
231
+ * Precision notes (over-exclusion is a fidelity failure in its own right):
232
+ * - `.env` family: `/^\.env(\..+)?$/` matches `.env`, `.env.local`,
233
+ * `.env.production` - and deliberately NOT `.envrc` or `.environment.ts`.
234
+ * - `.env.example` is carved out: it is authority-collected on purpose
235
+ * (AUTHORITY_FILE_MATCHERS) and holds placeholder values, not secrets.
236
+ * It is the doc-truth env_vars authority; excluding it would blind that
237
+ * extractor exactly as the old `process.env` over-scrub once did.
238
+ * - `credentials` is matched ONLY directly inside a dot-directory
239
+ * (`.aws/credentials`, `.docker/credentials`). A bare `credentials/` is a
240
+ * real, common SOURCE directory name (gRPC, auth libraries) and
241
+ * `shouldIgnore` cannot tell a file from a directory at its call sites -
242
+ * an unqualified rule would silently delete that subtree from the index.
243
+ * - `.tfvars` is excluded whole rather than per-basename: the credential file
244
+ * is conventionally `terraform.tfvars` but the name is free-form, and the
245
+ * variables that are NOT secret are visible in `.tf` anyway.
246
+ */
247
+ const SECRET_FILE_PLACEHOLDER_BASENAMES = new Set(['.env.example']);
248
+ const SECRET_FILE_BASENAME_PATTERNS = [
249
+ /^\.env(\..+)?$/i, // .env, .env.local, .env.production.local
250
+ /^id_(?:rsa|dsa|ecdsa|ed25519)/i, // ssh private keys (and .pub siblings)
251
+ /^\.(?:npmrc|netrc|pgpass)$/i, // registry / ftp / postgres password files
252
+ /^kubeconfig$/i,
253
+ /\.(?:pem|key|p12|pfx|keystore|jks|kubeconfig)$/i,
254
+ // Terraform variable files: `terraform.tfvars` is the conventional home for
255
+ // provider credentials, and unlike the entries above nothing else was
256
+ // keeping it out - it is excluded here rather than merely left off
257
+ // `DEFAULT_INCLUDE_EXTENSIONS`, so a future widening of the allowlist cannot
258
+ // quietly opt a project into embedding its own cloud keys.
259
+ /\.tfvars(\.json)?$/i,
260
+ ];
261
+ /**
262
+ * True when `relPath` names a file whose contents are credentials. Applied
263
+ * by `shouldIgnore` (every walker: directory scan, explicit file lists, and
264
+ * the authority-file walk) and by `makeIgnoreMatcher` (server-side backstop
265
+ * for older or misbehaving daemons). Accepts OS-native or POSIX separators.
266
+ */
267
+ export function isSecretFile(relPath) {
268
+ if (!relPath)
269
+ return false;
270
+ const segments = relPath.split(sep).join('/').split('/');
271
+ const base = segments[segments.length - 1] ?? '';
272
+ if (!base || SECRET_FILE_PLACEHOLDER_BASENAMES.has(base))
273
+ return false;
274
+ if (SECRET_FILE_BASENAME_PATTERNS.some((re) => re.test(base)))
275
+ return true;
276
+ const parent = segments[segments.length - 2];
277
+ return base === 'credentials' && parent !== undefined && parent.startsWith('.');
278
+ }
279
+ /**
280
+ * Per-directory ignore files the walkers honor, unioned. `.gitignore` is the
281
+ * project's own declaration of generated/vendored paths; `.mnemonikignore`
282
+ * (same gitignore syntax) is the user's Mnemonik-specific "never index this"
283
+ * list (e.g. `secrets/`). Matched hierarchically via the `ignore` package.
284
+ */
285
+ const IGNORE_FILE_NAMES = ['.gitignore', '.mnemonikignore'];
286
+ /** Per-directory attributes file: linguist overrides and binary marks (indexClassifier.ts). */
287
+ const ATTRIBUTES_FILE_NAME = '.gitattributes';
288
+ /**
289
+ * Every file type the scanner will chunk, by extension. Matched
290
+ * case-INSENSITIVELY (see `isIncludedExtension`), so lowercase spellings here
291
+ * also cover `.R`, `.SQL`, `.PS1` and the uppercase `.C`/`.H` of older trees.
292
+ *
293
+ * Exported because this list IS the product's language coverage: a project
294
+ * written in something absent from it indexes zero code, and `code_search`
295
+ * reports that as "no indexed matches" rather than "I do not read this
296
+ * language" - invisible to the developer and to us. Coverage is a separate
297
+ * dial from parse quality: a language with no structured extractor falls
298
+ * through to `chunkRaw`, which is what Go, Java and C already get in
299
+ * production, and crude chunks beat no chunks by an enormous margin.
300
+ *
301
+ * Data formats (`.json`, `.yaml`, `.toml`, `.lock`) are deliberately absent:
302
+ * the ones that carry meaning are already collected verbatim by
303
+ * `AUTHORITY_FILE_MATCHERS`, and blanket-indexing the extension would pull in
304
+ * lockfiles and generated output. `.tfvars` is absent for a different reason -
305
+ * `terraform.tfvars` is a conventional home for provider credentials and
306
+ * `isSecretFile` now excludes it outright.
307
+ */
308
+ export const DEFAULT_INCLUDE_EXTENSIONS = [
309
+ '.ts',
310
+ '.tsx',
311
+ '.js',
312
+ '.jsx',
313
+ '.py',
314
+ '.rs',
315
+ '.go',
316
+ '.java',
317
+ '.c',
318
+ '.cpp',
319
+ '.h',
320
+ '.cs',
321
+ '.rb',
322
+ '.php',
323
+ '.swift',
324
+ '.kt',
325
+ // Shell and Lua are the working languages of whole real projects -
326
+ // deployment tooling, container entrypoints, imapfilter/nginx/redis
327
+ // configuration. Omitting them meant such a project indexed ZERO code and
328
+ // code_search could not answer anything about it, while reporting that as
329
+ // "no indexed matches" rather than as missing coverage.
330
+ '.sh',
331
+ '.bash',
332
+ '.zsh',
333
+ '.lua',
334
+ '.md',
335
+ // -- Variants of languages already on the list. `.mjs`/`.cjs`/`.mts`/`.cts`/
336
+ // `.pyi` inherit their language string from a listed extension, so their
337
+ // absence was oversight rather than policy. The C++ spellings are a choice,
338
+ // not an inheritance: `.h` stays 'c' (C headers dominate, and reading a C++
339
+ // header as C is the safer default), while the unambiguously-C++ spellings
340
+ // resolve to 'cpp'.
341
+ '.mjs',
342
+ '.cjs',
343
+ '.mts',
344
+ '.cts',
345
+ '.pyi',
346
+ '.hpp',
347
+ '.hh',
348
+ '.hxx',
349
+ '.cc',
350
+ '.cxx',
351
+ '.kts',
352
+ // -- Languages the scanner could not read at all.
353
+ '.dart',
354
+ '.m',
355
+ '.mm',
356
+ '.scala',
357
+ '.sc',
358
+ '.ex',
359
+ '.exs',
360
+ '.erl',
361
+ '.hrl',
362
+ '.hs',
363
+ '.jl',
364
+ '.ml',
365
+ '.mli',
366
+ '.clj',
367
+ '.cljs',
368
+ '.cljc',
369
+ '.groovy',
370
+ '.gradle',
371
+ '.ps1',
372
+ '.psm1',
373
+ '.pl',
374
+ '.pm',
375
+ '.r',
376
+ '.sol',
377
+ '.zig',
378
+ '.vue',
379
+ '.svelte',
380
+ // -- Infrastructure and schema DSLs, where real logic lives and where "how
381
+ // is this deployed?" and "what does this table hold?" go unanswered today.
382
+ '.tf',
383
+ '.sql',
384
+ '.proto',
385
+ '.graphql',
386
+ '.gql',
387
+ '.cmake',
388
+ '.nix',
389
+ '.bzl',
390
+ ];
391
+ /**
392
+ * Cursor's rule files: `.cursorrules`, and any `.mdc` under `.cursor/rules/`.
393
+ * Cursor is a launch host, so these are instruction files, the same class as
394
+ * CLAUDE.md and AGENTS.md. Neither spelling can come in through
395
+ * `DEFAULT_INCLUDE_EXTENSIONS`: `.cursorrules` has no extension (`extname`
396
+ * answers ''), and `.mdc` is not a format this scanner reads anywhere else. So
397
+ * both are admitted by path at the chunking gate (`isChunkable`) and chunked as
398
+ * Markdown. They are not `.md` paths, so their whole-file content lands in
399
+ * project_source_content.
400
+ *
401
+ * Matched at any depth, because Cursor also reads nested `.cursor/rules`
402
+ * directories in a monorepo. Case-sensitive, as Cursor spells them. Accepts
403
+ * OS-native or POSIX separators.
404
+ */
405
+ export function isCursorRulePath(relPath) {
406
+ if (!relPath)
407
+ return false;
408
+ const posix = relPath.split(sep).join('/');
409
+ return /(^|\/)\.cursorrules$/.test(posix) || /(^|\/)\.cursor\/rules\/.+\.mdc$/.test(posix);
410
+ }
411
+ /**
412
+ * Extension -> language string, the value carried on every chunk and on the
413
+ * wire (`/scan/push` accepts any non-empty string up to 50 chars).
414
+ *
415
+ * A string no grammar claims is correct and expected: the AST layer resolves
416
+ * such a language to `null` and the heuristic chunker takes over. Keep this in
417
+ * sync with `DEFAULT_INCLUDE_EXTENSIONS` - an allowlisted extension that lands
418
+ * on 'unknown' still gets chunked, but nothing downstream can reason about it.
419
+ *
420
+ * Two extensions are genuinely ambiguous and are resolved rather than fudged:
421
+ * `.m` is Objective-C here, not MATLAB, because a repo carrying `.m` alongside
422
+ * `.h`/`.mm` is overwhelmingly an Apple-platform project; `.pl` is Perl, not
423
+ * Prolog, on the same frequency argument.
424
+ */
425
+ const EXTENSION_LANGUAGES = {
426
+ '.ts': 'typescript',
427
+ '.tsx': 'typescript',
428
+ '.mts': 'typescript',
429
+ '.cts': 'typescript',
430
+ '.js': 'javascript',
431
+ '.jsx': 'javascript',
432
+ '.mjs': 'javascript',
433
+ '.cjs': 'javascript',
434
+ '.py': 'python',
435
+ '.pyi': 'python',
436
+ '.rs': 'rust',
437
+ '.go': 'go',
438
+ '.java': 'java',
439
+ '.c': 'c',
440
+ '.h': 'c',
441
+ '.cpp': 'cpp',
442
+ '.cc': 'cpp',
443
+ '.cxx': 'cpp',
444
+ '.hpp': 'cpp',
445
+ '.hh': 'cpp',
446
+ '.hxx': 'cpp',
447
+ '.cs': 'csharp',
448
+ '.rb': 'ruby',
449
+ '.php': 'php',
450
+ '.swift': 'swift',
451
+ '.kt': 'kotlin',
452
+ '.kts': 'kotlin',
453
+ '.sh': 'shell',
454
+ '.bash': 'shell',
455
+ '.zsh': 'shell',
456
+ '.lua': 'lua',
457
+ '.md': 'markdown',
458
+ '.dart': 'dart',
459
+ '.m': 'objc',
460
+ '.mm': 'objc',
461
+ '.scala': 'scala',
462
+ '.sc': 'scala',
463
+ '.ex': 'elixir',
464
+ '.exs': 'elixir',
465
+ '.erl': 'erlang',
466
+ '.hrl': 'erlang',
467
+ '.hs': 'haskell',
468
+ '.jl': 'julia',
469
+ '.ml': 'ocaml',
470
+ '.mli': 'ocaml',
471
+ '.clj': 'clojure',
472
+ '.cljs': 'clojure',
473
+ '.cljc': 'clojure',
474
+ '.groovy': 'groovy',
475
+ '.gradle': 'groovy',
476
+ '.ps1': 'powershell',
477
+ '.psm1': 'powershell',
478
+ '.pl': 'perl',
479
+ '.pm': 'perl',
480
+ '.r': 'r',
481
+ '.sol': 'solidity',
482
+ '.zig': 'zig',
483
+ '.vue': 'vue',
484
+ '.svelte': 'svelte',
485
+ '.tf': 'terraform',
486
+ '.sql': 'sql',
487
+ '.proto': 'protobuf',
488
+ '.graphql': 'graphql',
489
+ '.gql': 'graphql',
490
+ '.cmake': 'cmake',
491
+ '.nix': 'nix',
492
+ '.bzl': 'starlark',
493
+ };
494
+ /**
495
+ * Language string for a file path or a bare extension, `'unknown'` when the
496
+ * extension is unmapped. A free function rather than a method because callers
497
+ * that never scan anything (AST grammar resolution, server-side symbol
498
+ * preference) need the same answer without constructing a scanner.
499
+ */
500
+ export function languageForExtension(filePathOrExt) {
501
+ if (isCmakeListsPath(filePathOrExt))
502
+ return 'cmake';
503
+ // `extname` FIRST. A dotfile that carries a real extension ('.eslintrc.js',
504
+ // '.mocharc.cjs', '.prettierrc.ts') starts with '.' and contains no '/', so
505
+ // a bare-extension-first reading swallowed the whole name and answered
506
+ // 'unknown' - while the same file spelled 'src/.eslintrc.js' answered
507
+ // 'javascript'. Those extensions are allowlisted, so the files are indexed
508
+ // and reach the server with exactly the root-relative spelling that failed.
509
+ const fromPath = EXTENSION_LANGUAGES[extname(filePathOrExt).toLowerCase()];
510
+ if (fromPath !== undefined)
511
+ return fromPath;
512
+ // Fallback: the argument IS the extension ('.dart'), for which `extname`
513
+ // returns ''. Every key contains a leading dot and no separator, so a real
514
+ // path can never collide here.
515
+ return EXTENSION_LANGUAGES[filePathOrExt.toLowerCase()] ?? 'unknown';
516
+ }
517
+ /**
518
+ * THE definition of "this path is a SQL migration the schema_columns authority
519
+ * collects verbatim". One predicate, referenced by both halves of the deal -
520
+ * `AUTHORITY_FILE_MATCHERS` (collect it) and `isAuthorityOnlyPath` (therefore
521
+ * do not chunk it) - because two hand-written regexes drifted once already and
522
+ * the failure is silent in both directions.
523
+ *
524
+ * Root-anchored and CASE-SENSITIVE on purpose: it mirrors the server-side
525
+ * extractor, which does `listFiles('migrations/')` (LIKE 'migrations/%') then
526
+ * `endsWith('.sql')`, both case-sensitive. `Migrations/001.sql` (the .NET/EF
527
+ * Core spelling) and `migrations/002.SQL` are NOT collected, so they must not
528
+ * be suppressed from chunking either - that would index them nowhere. Same
529
+ * reason a nested `packages/x/migrations/y.sql` is left alone.
530
+ */
531
+ const isMigrationSqlAuthorityPath = (posixRelPath) => /^migrations\/.*\.sql$/.test(posixRelPath);
532
+ /** Content-only build authority, shared by scanner collection and server admission. */
533
+ export const XCODE_AUTHORITY_PATH = /(?:^|\/)[^/]+\.xcodeproj\/project\.pbxproj$|\.xcconfig$/;
534
+ export const isXcodeAuthorityPath = (path) => XCODE_AUTHORITY_PATH.test(path);
535
+ /** Exact CMake build entrypoint; ordinary .txt files remain outside collection. */
536
+ export const CMAKE_LISTS_PATH = /(?:^|\/)CMakeLists\.txt$/;
537
+ export const isCmakeListsPath = (path) => CMAKE_LISTS_PATH.test(path);
538
+ /**
539
+ * Predicates for paths whose verbatim content is ALREADY shipped by
540
+ * `collectAuthorityFiles` and that carry no additional value as embedded code
541
+ * chunks. Checked at the extension gate rather than in `shouldIgnore`, because
542
+ * `shouldIgnore` also guards the authority walk and must keep letting these
543
+ * through.
544
+ *
545
+ * `migrations/**.sql` is the live case: adding `.sql` to the allowlist without
546
+ * this exclusion would dual-collect every migration - once verbatim, once
547
+ * chunked and embedded. On this repo alone that is 208 files of append-only
548
+ * DDL (140 forward, the rest rollback/manual), embedded to answer questions
549
+ * the authority path already answers exactly.
550
+ *
551
+ * INVARIANT: every predicate here must also appear in
552
+ * `AUTHORITY_FILE_MATCHERS`, so no path can be excluded from chunking unless
553
+ * the authority path definitely collects it.
554
+ */
555
+ const AUTHORITY_ONLY_PATH_PREDICATES = [
556
+ isMigrationSqlAuthorityPath,
557
+ isXcodeAuthorityPath,
558
+ isCmakeListsPath,
559
+ ];
560
+ /**
561
+ * True when `relPath` is collected verbatim as authority content and must not
562
+ * also be chunked. Accepts OS-native or POSIX separators.
563
+ */
564
+ export function isAuthorityOnlyPath(relPath) {
565
+ if (!relPath)
566
+ return false;
567
+ const posix = relPath.split(sep).join('/');
568
+ return AUTHORITY_ONLY_PATH_PREDICATES.some((matches) => matches(posix));
569
+ }
570
+ /**
571
+ * Matchers for authority manifest / config / CI files whose verbatim content
572
+ * is collected by `collectAuthorityFiles` and pushed to the server for
573
+ * doc-truth Fingerprint parsing. Operates on relative, forward-slash paths.
574
+ */
575
+ export const AUTHORITY_FILE_MATCHERS = [
576
+ (p) => p === 'package.json',
577
+ (p) => /^(packages|apps|services|tools)\/[^/]+\/package\.json$/.test(p),
578
+ (p) => p === 'tsconfig.json' || /^tsconfig\.[^/]+\.json$/.test(p),
579
+ (p) => p === 'pyproject.toml',
580
+ (p) => p === 'requirements.txt',
581
+ (p) => p === 'setup.py',
582
+ (p) => p === 'Cargo.toml',
583
+ (p) => p === 'Gemfile',
584
+ (p) => p === 'Makefile',
585
+ (p) => p === '.env.example',
586
+ (p) => /^\.github\/workflows\/[^/]+\.(yml|yaml)$/.test(p),
587
+ // SQL migrations: the schema_columns authority extractor reads every .sql
588
+ // under `migrations/` (listFiles('migrations/') -> LIKE 'migrations/%' then
589
+ // .endsWith('.sql')). Without collecting these, that authority is empty and
590
+ // every schema_table_enumeration claim falls to unverifiable. Shared with
591
+ // `AUTHORITY_ONLY_PATH_PREDICATES` by reference, not by a copied regex, so
592
+ // collection and the chunking exclusion cannot disagree.
593
+ isMigrationSqlAuthorityPath,
594
+ isXcodeAuthorityPath,
595
+ isCmakeListsPath,
596
+ ];
597
+ /**
598
+ * Segment-anchored match for `tests/fixtures/` - matches at the path root or
599
+ * immediately after a `/`. Indexing no longer uses it (the fixture rule is the
600
+ * soft default in indexClassifier.ts, which a project can override); it stays
601
+ * for query-time hygiene over rows indexed before that rule existed
602
+ * (`MemoryManager.searchCodePointers`).
603
+ */
604
+ export const FIXTURE_PATH_RE = /(^|\/)tests\/fixtures\//;
605
+ export function isFixturePath(path) {
606
+ return FIXTURE_PATH_RE.test(path);
607
+ }
608
+ const BUILT_IN_IGNORE_DIR_SET = new Set(BUILT_IN_IGNORE_DIRS);
609
+ /**
610
+ * Server-side ignore matcher for defense-in-depth path dropping on /scan/push,
611
+ * /scan/reconcile, and file_push. Combines the universal BUILT_IN_IGNORE_DIRS
612
+ * (segment-exact) with a project's uploaded .gitignore/.mnemonikignore patterns
613
+ * (gitignore syntax via the `ignore` package). Built once per request and reused
614
+ * across all pushed paths (root-relative, forward-slash). This does NOT replace
615
+ * the daemon's precise hierarchical walk - it backstops it so a buggy, stale, or
616
+ * malicious client cannot index a path the project ignores, making .mnemonikignore
617
+ * a hard guarantee rather than best-effort.
618
+ */
619
+ export function makeIgnoreMatcher(extraPatterns = []) {
620
+ const cleaned = extraPatterns.filter((p) => typeof p === 'string' && p.trim().length > 0);
621
+ const ig = cleaned.length > 0 ? ignore().add([...cleaned]) : null;
622
+ return (relPath) => {
623
+ if (!relPath)
624
+ return false;
625
+ const norm = relPath.split(sep).join('/');
626
+ if (norm.split('/').some((s) => BUILT_IN_IGNORE_DIR_SET.has(s)))
627
+ return true;
628
+ if (isSecretFile(norm))
629
+ return true;
630
+ if (ig) {
631
+ try {
632
+ return ig.ignores(norm);
633
+ }
634
+ catch {
635
+ // `ignore` throws on absolute/`..` paths (safeScanPath already rejects
636
+ // those upstream); built-ins were already checked, so fail open here.
637
+ return false;
638
+ }
639
+ }
640
+ return false;
641
+ };
642
+ }
643
+ /**
644
+ * True when `dirPath` is the root of a DIFFERENT repository than the one
645
+ * being scanned: it carries its own `.git` entry. A `.git` FILE marks a
646
+ * linked git worktree (wherever the user keeps them) or a submodule
647
+ * checkout; a `.git` DIRECTORY marks a nested clone. Files under such a
648
+ * boundary belong to that repository's own project identity - scanning them
649
+ * into the parent project is wrong attribution for any codebase, so the
650
+ * walkers skip these subtrees. Convention-free: this is git's own marker,
651
+ * not a host/tool path layout. The scan ROOT is exempt by construction
652
+ * (callers only test child directories).
653
+ */
654
+ export async function isGitBoundary(dirPath) {
655
+ try {
656
+ await fileOp(() => lstat(join(dirPath, '.git')), `lstat: ${join(dirPath, '.git')}`);
657
+ return true;
658
+ }
659
+ catch {
660
+ return false;
661
+ }
662
+ }
663
+ /**
664
+ * There is no depth limit on a project's walk. A cap of 10 folders guarded the
665
+ * first scanner (February 2026) against runaway recursion through symlinked
666
+ * trees; symlinks have long been skipped by every walker (confineSymlink,
667
+ * skipSymlink), and WalkState.ancestors ends a bind-mount cycle. The cap only hid
668
+ * ordinary deep files (Java and Kotlin package trees, Next.js monorepos), and the
669
+ * watcher, which had no cap, then pushed a deep file the next walk reported removed.
670
+ */
671
+ /**
672
+ * True when `dirPath` starts a subtree that is not this project's to index.
673
+ * A file belongs to the project of the nearest `.mnemonik.json` above it, so:
674
+ * - a folder with its own identity file is a subproject, indexed as its own
675
+ * project, never also into this one. A file naming the enclosing project
676
+ * (`enclosingProjectId`, a copy) is the same project, and a
677
+ * configuration-only file (no `projectId`) names none: neither is a
678
+ * boundary. A file that cannot be read as an identity still is, and so is
679
+ * a copy in a full clone (its own `.git` DIRECTORY): a second checkout of
680
+ * the project, whose files would otherwise be indexed twice;
681
+ * - a linked worktree (a `.git` FILE whose git directory has a `commondir`,
682
+ * or is missing) is another checkout of a project, indexed from its main
683
+ * checkout.
684
+ * A nested clone or a submodule without its own `.mnemonik.json` belongs to
685
+ * this project and is indexed with it (its `.git` directory is ignored by the
686
+ * built-in rules). The scan ROOT is exempt by construction (callers only test
687
+ * child directories).
688
+ */
689
+ export async function isProjectBoundary(dirPath, enclosingProjectId) {
690
+ if (await lstatWithin(join(dirPath, '.mnemonik.json'))) {
691
+ const identity = await fileOp(() => readIdentityFile(dirPath, { configurationOnlyAbsent: true }), `identity read: ${dirPath}`).catch(() => undefined);
692
+ if (!identity)
693
+ return true;
694
+ if (identity.kind === 'ok') {
695
+ if (identity.identity.projectId !== enclosingProjectId)
696
+ return true;
697
+ if ((await lstatWithin(join(dirPath, '.git')))?.isDirectory())
698
+ return true;
699
+ }
700
+ else if (identity.kind !== 'absent')
701
+ return true;
702
+ }
703
+ return isLinkedWorktreeCheckout(dirPath);
704
+ }
705
+ /**
706
+ * The project a scan root's own identity file names, or undefined: the
707
+ * enclosing project for isProjectBoundary.
708
+ */
709
+ export async function rootProjectId(rootPath) {
710
+ const identity = await fileOp(() => readIdentityFile(rootPath), `identity read: ${rootPath}`).catch(() => undefined);
711
+ return identity?.kind === 'ok' ? identity.identity.projectId : undefined;
712
+ }
713
+ const lstatWithin = (path) => fileOp(() => lstat(path), `lstat: ${path}`).catch(() => undefined);
714
+ /**
715
+ * True when `dirPath` is the top of a linked git worktree: its `.git` is a
716
+ * FILE pointing at a git directory that has a `commondir`, or at one that no
717
+ * longer exists (a pruned or moved worktree, or one made on another machine):
718
+ * nothing shows it is this project's own. A submodule's `.git` file points at
719
+ * `.git/modules/<name>`, which exists and has no `commondir`.
720
+ */
721
+ export async function isLinkedWorktreeCheckout(dirPath) {
722
+ const marker = await lstatWithin(join(dirPath, '.git'));
723
+ if (!marker?.isFile())
724
+ return false;
725
+ try {
726
+ const pointer = /^gitdir:\s*(.+?)\s*$/im.exec(await fileOp(() => readFile(join(dirPath, '.git'), 'utf8'), `read: ${join(dirPath, '.git')}`))?.[1];
727
+ if (!pointer)
728
+ return false;
729
+ const gitDirectory = resolve(dirPath, pointer);
730
+ if (!(await lstatWithin(gitDirectory)))
731
+ return true;
732
+ return !!(await lstatWithin(join(gitDirectory, 'commondir')));
733
+ }
734
+ catch {
735
+ return false;
736
+ }
737
+ }
738
+ /** The ignore patterns applied when a caller gives none. */
739
+ export const DEFAULT_IGNORE_PATTERNS = [
740
+ ...BUILT_IN_IGNORE_DIRS,
741
+ ...BUILT_IN_IGNORE_FILE_PATTERNS,
742
+ ];
743
+ /**
744
+ * The scanner's file selection. `listFilesWithStatus` is the inventory every
745
+ * scan and the CLI's estimate count; CodeScanner adds reading and chunking.
746
+ */
747
+ export class FileSelector {
748
+ selection;
749
+ protectedPaths;
750
+ /** Cumulative observations since this scanner started, including repeated walks. */
751
+ skipReasons = { symlink_skipped: 0 };
752
+ skipSymlink(stats) {
753
+ if (!stats.isSymbolicLink())
754
+ return false; // Includes Windows junctions.
755
+ this.skipReasons.symlink_skipped++;
756
+ return true;
757
+ }
758
+ /**
759
+ * `includeExtensions` folded to lowercase for matching. The gate used to
760
+ * compare `extname()` verbatim while `detectLanguage` lowercased, so a
761
+ * project spelling its files the canonical way - `.R` for R, `.SQL`/`.PS1`
762
+ * on Windows, `.C`/`.H` in older C trees - indexed zero of them and nothing
763
+ * said why.
764
+ */
765
+ includeExtensionSet;
766
+ constructor(options = {}) {
767
+ this.selection = {
768
+ ignorePatterns: [...DEFAULT_IGNORE_PATTERNS],
769
+ includeExtensions: [...DEFAULT_INCLUDE_EXTENSIONS],
770
+ protectedPaths: [],
771
+ ...options,
772
+ };
773
+ this.protectedPaths = [
774
+ ...new Set([...protectedLocalPaths(), ...(options.protectedPaths ?? [])]),
775
+ ];
776
+ this.includeExtensionSet = new Set(this.selection.includeExtensions.map((ext) => ext.toLowerCase()));
777
+ }
778
+ isProtected(path) {
779
+ return isProtectedLocalPath(path, this.protectedPaths);
780
+ }
781
+ async isProtectedRead(path) {
782
+ if (this.isProtected(path))
783
+ return true;
784
+ return isProtectedLocalPath(await realpath(path), this.protectedPaths);
785
+ }
786
+ /**
787
+ * The chunkable-file gate, shared by every walker and by the explicit
788
+ * file-list path so all three agree on what exists. `relPath` is the path
789
+ * relative to the scan root (OS-native separators accepted).
790
+ */
791
+ isChunkable(absOrRelPath, relPath) {
792
+ if (!this.includeExtensionSet.has(extname(absOrRelPath).toLowerCase()) &&
793
+ !isCursorRulePath(relPath)) {
794
+ return false;
795
+ }
796
+ if (isAuthorityOnlyPath(relPath)) {
797
+ logDebug('Skipping chunking for authority-collected path', { relPath });
798
+ return false;
799
+ }
800
+ return true;
801
+ }
802
+ /**
803
+ * Read `.gitignore` + `.mnemonikignore` + `.gitattributes` in `absDir` and
804
+ * compile them into one layer (the two ignore files are unioned -
805
+ * `.mnemonikignore` is just an additional gitignore-syntax exclusion list).
806
+ * Returns null when none of the three exists. FAIL-CLOSED: a non-ENOENT read
807
+ * error (EISDIR, EACCES, timeout) latches `walk.complete = false` so callers
808
+ * deriving *removals* from the walk treat it as untrustworthy rather than
809
+ * silently ignoring nothing.
810
+ */
811
+ async loadIgnoreLayer(absDir, baseRel, walk, rootPath) {
812
+ if (this.isProtected(absDir))
813
+ return null;
814
+ const read = async (name) => {
815
+ const filePath = join(absDir, name);
816
+ try {
817
+ const content = await fileOp(() => this.readConfined(filePath, rootPath), `readFile: ${filePath}`);
818
+ return content.split(/\r?\n/);
819
+ }
820
+ catch (err) {
821
+ if (err.message === 'symlink_skipped')
822
+ return null;
823
+ if (err?.code !== 'ENOENT') {
824
+ markUnreadable(walk, filePath, err);
825
+ logDebug('Rule-file read failed (fail-closed)', { path: filePath, err });
826
+ }
827
+ return null;
828
+ }
829
+ };
830
+ const patterns = [];
831
+ for (const name of IGNORE_FILE_NAMES) {
832
+ const lines = await read(name);
833
+ if (lines)
834
+ patterns.push(...lines);
835
+ }
836
+ const attributeLines = (await read(ATTRIBUTES_FILE_NAME)) ?? [];
837
+ if (patterns.length > 0 || attributeLines.length > 0) {
838
+ walk.rules?.set(baseRel, { ignore: patterns, attributes: attributeLines });
839
+ }
840
+ const attributes = attributeLines.length > 0 ? parseGitattributes(attributeLines.join('\n')) : [];
841
+ // `ignore` tolerates blank/comment lines; null when nothing meaningful.
842
+ if (patterns.length === 0 && attributes.length === 0)
843
+ return null;
844
+ return {
845
+ baseRel,
846
+ ig: patterns.length > 0 ? ignore().add(patterns) : null,
847
+ hasNegation: patterns.some((line) => line.trimStart().startsWith('!')),
848
+ attributes: attributes.length > 0 ? attributes : null,
849
+ };
850
+ }
851
+ /**
852
+ * What the .gitignore / .mnemonikignore layers in `stack` say about
853
+ * `entryRel` (relative to the scan root). Tested deepest-first: the first
854
+ * layer that explicitly ignores OR re-includes (via a `!negation`) wins,
855
+ * matching git's rule that a deeper `.gitignore` overrides a shallower one.
856
+ * Directories are tested with a trailing slash so `foo/` dir-only rules
857
+ * match the directory itself. `'unignored'` means a negation matched this
858
+ * path itself; a re-included parent directory leaves its files `'unmatched'`.
859
+ */
860
+ ignoreVerdict(entryRel, isDir, stack) {
861
+ for (let i = stack.length - 1; i >= 0; i--) {
862
+ const layer = stack[i];
863
+ if (!layer?.ig)
864
+ continue;
865
+ const { baseRel, ig } = layer;
866
+ let sub;
867
+ if (baseRel === '') {
868
+ sub = entryRel;
869
+ }
870
+ else if (entryRel === baseRel || !entryRel.startsWith(baseRel + '/')) {
871
+ continue; // this layer does not cover entryRel
872
+ }
873
+ else {
874
+ sub = entryRel.slice(baseRel.length + 1);
875
+ }
876
+ if (!sub)
877
+ continue;
878
+ const res = ig.test(isDir ? sub + '/' : sub);
879
+ if (res.ignored)
880
+ return 'ignored';
881
+ if (res.unignored)
882
+ return 'unignored';
883
+ }
884
+ return 'unmatched';
885
+ }
886
+ ignoredByStack(entryRel, isDir, stack) {
887
+ return this.ignoreVerdict(entryRel, isDir, stack) === 'ignored';
888
+ }
889
+ static attributeLayers(stack) {
890
+ return stack.flatMap((layer) => layer.attributes ? [{ baseRel: layer.baseRel, rules: layer.attributes }] : []);
891
+ }
892
+ /**
893
+ * Skip this directory? User-ignored directories are skipped as before. A
894
+ * directory a soft default excludes (vendor/, generated/, ...) is pruned too -
895
+ * nothing under it can be indexed - UNLESS a rule above it could re-include
896
+ * something inside it: a `!pattern` or a `-linguist-*` attribute. Then the
897
+ * walk descends and judges each file, so the override works. Rule files
898
+ * INSIDE a pruned directory are never read: a vendored library's own
899
+ * .gitignore negations are not the project's intent.
900
+ */
901
+ skipDirectory(relPath, stack) {
902
+ const posixRel = relPath.split(sep).join('/');
903
+ const verdict = this.ignoreVerdict(posixRel, true, stack);
904
+ if (verdict === 'ignored')
905
+ return true;
906
+ if (verdict === 'unignored')
907
+ return false;
908
+ if (!softDefaultForDirectory(posixRel))
909
+ return false;
910
+ const canReinclude = stack.some((layer) => layer.hasNegation) ||
911
+ gitattributesCanReinclude(FileSelector.attributeLayers(stack));
912
+ return !canReinclude;
913
+ }
914
+ /**
915
+ * The index decision for a file from its path and the rule stack: `null`
916
+ * when a user ignore rule excludes it, otherwise the classifier's answer
917
+ * (precedence in indexClassifier.ts). Content rules are the caller's next
918
+ * step for an included path without an `override`.
919
+ */
920
+ classifyEntry(relPath, stack) {
921
+ const posixRel = relPath.split(sep).join('/');
922
+ const verdict = this.ignoreVerdict(posixRel, false, stack);
923
+ if (verdict === 'ignored')
924
+ return null;
925
+ return classifyForIndex(posixRel, {
926
+ ignoreFileVerdict: verdict,
927
+ attributes: FileSelector.attributeLayers(stack),
928
+ });
929
+ }
930
+ /**
931
+ * Reconstruct the root->parent ignore-layer stack for a single file, for the
932
+ * incremental `scanFiles` path (which has a flat file list, not a recursive
933
+ * walk). Layers are memoized per directory in `cache` across a batch.
934
+ */
935
+ async buildIgnoreStackForFile(fileRel, rootPath, cache, walk) {
936
+ const dirs = [''];
937
+ let acc = '';
938
+ for (const seg of fileRel.split('/').slice(0, -1)) {
939
+ acc = acc === '' ? seg : `${acc}/${seg}`;
940
+ dirs.push(acc);
941
+ }
942
+ const stack = [];
943
+ for (const dir of dirs) {
944
+ let layer = cache.get(dir);
945
+ if (layer === undefined) {
946
+ layer = await this.loadIgnoreLayer(dir === '' ? rootPath : join(rootPath, dir), dir, walk, rootPath);
947
+ cache.set(dir, layer);
948
+ }
949
+ if (layer)
950
+ stack.push(layer);
951
+ }
952
+ return stack;
953
+ }
954
+ /**
955
+ * A predicate for walkers outside this class (the daemon's file watcher):
956
+ * true when the walk would descend into `absDir`, by the same rules
957
+ * `listFiles` applies - user ignore files and soft-default directories,
958
+ * with their overrides. Rule files are read once per directory for the life
959
+ * of the returned predicate; take a fresh one after a rule file changes.
960
+ * Directories outside `rootPath`, and the root itself, always pass.
961
+ */
962
+ directoryFilter(rootPath) {
963
+ const cache = new Map();
964
+ return async (absDir) => {
965
+ try {
966
+ const root = await this.canonicalRoot(rootPath);
967
+ const rel = relative(root, absDir).split(sep).join('/');
968
+ if (!rel || rel.startsWith('..'))
969
+ return true;
970
+ const stack = await this.buildIgnoreStackForFile(rel, root, cache, { complete: true });
971
+ return !this.skipDirectory(rel, stack);
972
+ }
973
+ catch {
974
+ // Fail open: watching a directory the walk would skip costs a watch
975
+ // handle; not watching one it would index loses changes.
976
+ return true;
977
+ }
978
+ };
979
+ }
980
+ /**
981
+ * True when any directory strictly between `rootPath` and `filePath`
982
+ * starts a subtree this project does not index (see isProjectBoundary). Paths that don't
983
+ * resolve under `rootPath` are not judged here (return false) - the
984
+ * server's path validation handles escapes.
985
+ */
986
+ async insideNestedGitBoundary(filePath, rootPath) {
987
+ const rel = relative(rootPath, filePath);
988
+ if (!rel || rel.startsWith('..'))
989
+ return false;
990
+ const segments = rel.split(sep);
991
+ let current = rootPath;
992
+ // Walk intermediate directories only (exclude the file itself).
993
+ for (let i = 0; i < segments.length - 1; i++) {
994
+ const segment = segments[i];
995
+ if (segment === undefined)
996
+ continue;
997
+ current = join(current, segment);
998
+ if (await this.isBoundary(current, rootPath))
999
+ return true;
1000
+ }
1001
+ return false;
1002
+ }
1003
+ rootProjectIds = new Map();
1004
+ /**
1005
+ * isProjectBoundary, with the scan root's own project as the enclosing one.
1006
+ * The root's file is read at most once a minute: a walk tests many folders,
1007
+ * and a project relinked since is seen on the next scan.
1008
+ */
1009
+ async isBoundary(dirPath, rootPath) {
1010
+ let cached = this.rootProjectIds.get(rootPath);
1011
+ if (!cached || Date.now() - cached.at > 60_000) {
1012
+ cached = { at: Date.now(), projectId: rootProjectId(rootPath) };
1013
+ this.rootProjectIds.set(rootPath, cached);
1014
+ }
1015
+ return isProjectBoundary(dirPath, await cached.projectId);
1016
+ }
1017
+ canonicalRoots = new Map();
1018
+ async canonicalRoot(root) {
1019
+ let canonical = this.canonicalRoots.get(root);
1020
+ if (!canonical) {
1021
+ canonical = await realpath(root);
1022
+ this.canonicalRoots.set(root, canonical);
1023
+ }
1024
+ return canonical;
1025
+ }
1026
+ static containsCanonical(candidate, root, paths = { sep, resolve }, caseInsensitive = process.platform === 'win32') {
1027
+ // realpath expands filesystem aliases (including Windows 8.3 names). Never guess a short name.
1028
+ candidate = paths.resolve(candidate);
1029
+ root = paths.resolve(root);
1030
+ if (caseInsensitive) {
1031
+ candidate = candidate.toLowerCase();
1032
+ root = root.toLowerCase();
1033
+ }
1034
+ return (candidate === root || candidate.startsWith(root.endsWith(paths.sep) ? root : root + paths.sep));
1035
+ }
1036
+ async confineSymlink(fullPath, canonicalRoot) {
1037
+ // Check each component: explicit-file callers must not bypass the walkers'
1038
+ // no-symlink policy by supplying a path through an in-root directory link.
1039
+ let path = resolve(fullPath);
1040
+ if (!FileSelector.containsCanonical(path, canonicalRoot))
1041
+ return false;
1042
+ for (;;) {
1043
+ if (this.skipSymlink(await lstat(path)))
1044
+ throw new Error('symlink_skipped');
1045
+ if (FileSelector.containsCanonical(canonicalRoot, path))
1046
+ break;
1047
+ path = dirname(path);
1048
+ }
1049
+ return FileSelector.containsCanonical(await realpath(fullPath), canonicalRoot);
1050
+ }
1051
+ async readConfined(fullPath, canonicalRoot, enumerated) {
1052
+ const expected = enumerated ?? (await lstat(fullPath));
1053
+ if (this.skipSymlink(expected))
1054
+ throw new Error('symlink_skipped');
1055
+ if (!expected.isFile())
1056
+ throw new Error('scanner_not_regular');
1057
+ if (!(await this.confineSymlink(fullPath, canonicalRoot)))
1058
+ throw new Error('scanner_containment');
1059
+ const canonical = await realpath(fullPath);
1060
+ if (!FileSelector.containsCanonical(canonical, canonicalRoot) ||
1061
+ (await this.isProtectedRead(canonical)))
1062
+ throw new Error('scanner_containment');
1063
+ // O_NONBLOCK also prevents a substituted FIFO from hanging before fstat.
1064
+ const flags = constants.O_RDONLY |
1065
+ (constants.O_NONBLOCK ?? 0) |
1066
+ (process.platform === 'win32' ? 0 : (constants.O_NOFOLLOW ?? 0));
1067
+ const handle = await open(fullPath, flags).catch((error) => {
1068
+ if (error.code === 'ELOOP') {
1069
+ this.skipReasons.symlink_skipped++;
1070
+ throw new Error('symlink_skipped');
1071
+ }
1072
+ throw error;
1073
+ });
1074
+ try {
1075
+ const actual = await handle.stat();
1076
+ if (!actual.isFile())
1077
+ throw new Error('scanner_not_regular');
1078
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino)
1079
+ throw new Error('scanner_identity_changed');
1080
+ // Windows has no O_NOFOLLOW; lstat is Node's junction/reparse-link check.
1081
+ if (process.platform === 'win32' && this.skipSymlink(await lstat(fullPath)))
1082
+ throw new Error('symlink_skipped');
1083
+ // Linux also proves the opened object is still at the checked path.
1084
+ if (process.platform === 'linux' &&
1085
+ (await realpath(`/proc/self/fd/${handle.fd}`)) !== canonical)
1086
+ throw new Error('scanner_containment');
1087
+ return await handle.readFile('utf-8');
1088
+ }
1089
+ finally {
1090
+ await handle.close();
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Enumerate scan-eligible relative file paths under `rootPath` without
1095
+ * reading or chunking content. Same walk + ignorePatterns + extension
1096
+ * filter as `scanDirectory`, but bounded to O(file count) directory ops
1097
+ * - cheap enough to call on every periodic reconcile tick.
1098
+ *
1099
+ * Returns relative paths normalized against `rootPath`, matching the
1100
+ * shape the server stores in `memories.metadata->>'filePath'`. Use this
1101
+ * for the scanner reconciliation channel (`POST /api/v1/scan/reconcile`).
1102
+ *
1103
+ * Defensive: skips any path whose `relative()` result contains a `..`
1104
+ * traversal segment (can happen when a symlink resolves under root but
1105
+ * the readdir entry path doesn't normalize cleanly). The server's
1106
+ * `safeScanPath` rejects such paths; filtering here keeps a single
1107
+ * malformed entry from failing the entire reconcile push.
1108
+ */
1109
+ async listFiles(rootPath) {
1110
+ const { paths } = await this.listFilesWithStatus(rootPath);
1111
+ return paths;
1112
+ }
1113
+ /**
1114
+ * Completeness-aware variant of `listFiles`. `complete === false` means
1115
+ * an fs error truncated part of the walk - the returned paths may be
1116
+ * missing files that still exist on disk. The daemon's reconcile channel
1117
+ * MUST NOT derive removedFiles from an incomplete inventory (a truncated
1118
+ * walk otherwise reads as mass deletion and deprecates live memories).
1119
+ */
1120
+ async listFilesWithStatus(rootPath) {
1121
+ rootPath = await this.canonicalRoot(rootPath);
1122
+ const paths = [];
1123
+ const overridden = new Set();
1124
+ const stats = new Map();
1125
+ const walk = { complete: true, rules: new Map() };
1126
+ await this.traversePaths(rootPath, rootPath, paths, 0, walk, [], overridden, stats);
1127
+ // Only a complete walk replaces the record: a partial one may be missing
1128
+ // rule files, and uploading it would tell the server fewer rules exist.
1129
+ if (walk.complete && walk.rules)
1130
+ this.ruleFilesByRoot.set(rootPath, walk.rules);
1131
+ return {
1132
+ paths: paths.filter((p) => !/(^|[/\\])\.\.([/\\]|$)/.test(p)),
1133
+ complete: walk.complete,
1134
+ overridden,
1135
+ unreadable: walk.unreadable ?? 0,
1136
+ unreadableSamples: walk.unreadableSamples ?? [],
1137
+ stats,
1138
+ };
1139
+ }
1140
+ /**
1141
+ * The rule files the last complete `listFilesWithStatus` walk of `rootPath`
1142
+ * applied, by directory ('' = root). Null before the first complete walk.
1143
+ * The daemon uploads these lines so the server judges paths as it did.
1144
+ */
1145
+ async indexRuleFiles(rootPath) {
1146
+ return this.ruleFilesByRoot.get(await this.canonicalRoot(rootPath)) ?? null;
1147
+ }
1148
+ ruleFilesByRoot = new Map();
1149
+ async traversePaths(currentPath, rootPath, out, depth, walk, stack = [], overridden, statsOut) {
1150
+ if (this.isProtected(currentPath))
1151
+ return;
1152
+ let entries;
1153
+ try {
1154
+ if (!(await this.confineSymlink(currentPath, rootPath)))
1155
+ throw new Error('scanner_containment');
1156
+ // The root is the first ancestor; every other directory enters before it recurses.
1157
+ if (depth === 0 && !(await enterDirectory(walk, currentPath)))
1158
+ return;
1159
+ entries = await fileOp(() => readdir(currentPath), `readdir: ${currentPath}`);
1160
+ }
1161
+ catch (error) {
1162
+ markUnreadable(walk, currentPath, error);
1163
+ logDebug('Error traversing directory (listFiles)', { path: currentPath, error });
1164
+ return;
1165
+ }
1166
+ const dirRel = currentPath === rootPath ? '' : relative(rootPath, currentPath).split(sep).join('/');
1167
+ const localLayer = await this.loadIgnoreLayer(currentPath, dirRel, walk, rootPath);
1168
+ const localStack = localLayer ? [...stack, localLayer] : stack;
1169
+ for (const entry of entries) {
1170
+ const fullPath = join(currentPath, entry);
1171
+ const relativePath = relative(rootPath, fullPath);
1172
+ if (this.isProtected(fullPath))
1173
+ continue;
1174
+ if (this.shouldIgnore(relativePath))
1175
+ continue;
1176
+ // Per-entry isolation: a single bad entry (dangling symlink, raced
1177
+ // deletion, permission denial, fs timeout) must not abort the rest of
1178
+ // the directory - but the inventory is no longer removal-trustworthy.
1179
+ try {
1180
+ const lstats = await fileOp(() => lstat(fullPath), `lstat: ${fullPath}`);
1181
+ if (this.skipSymlink(lstats))
1182
+ continue;
1183
+ const stats = lstats;
1184
+ if (stats.isDirectory()) {
1185
+ // .gitignore/.mnemonikignore, then soft-default directories
1186
+ if (this.skipDirectory(relativePath, localStack))
1187
+ continue;
1188
+ if (await this.isBoundary(fullPath, rootPath))
1189
+ continue; // a subproject or worktree
1190
+ const leave = await enterDirectory(walk, fullPath);
1191
+ if (!leave)
1192
+ continue;
1193
+ try {
1194
+ await this.traversePaths(fullPath, rootPath, out, depth + 1, walk, localStack, overridden, statsOut);
1195
+ }
1196
+ finally {
1197
+ leave();
1198
+ }
1199
+ }
1200
+ else if (stats.isFile()) {
1201
+ if (!this.isChunkable(fullPath, relativePath))
1202
+ continue;
1203
+ const decision = this.classifyEntry(relativePath, localStack);
1204
+ if (!decision?.include)
1205
+ continue;
1206
+ out.push(relativePath);
1207
+ statsOut?.set(relativePath, statTuple(stats));
1208
+ if (decision.override)
1209
+ overridden?.add(relativePath);
1210
+ }
1211
+ }
1212
+ catch (error) {
1213
+ markUnreadable(walk, fullPath, error);
1214
+ logDebug('Error traversing directory (listFiles)', { path: fullPath, error });
1215
+ }
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Check if path should be ignored
1220
+ * Fixed glob-to-regex conversion and substring matching.
1221
+ * - Escape regex special chars before replacing * with .*
1222
+ * - Replace ALL * occurrences (not just the first)
1223
+ * - For non-glob patterns, match on path segments to avoid false positives
1224
+ * (e.g., '.env' should not match '.environment.ts')
1225
+ */
1226
+ shouldIgnore(path) {
1227
+ // Credential-bearing file kinds first, and outside the overridable
1228
+ // `ignorePatterns` list - a caller-supplied pattern set must not be able
1229
+ // to opt a project back into indexing its own private keys.
1230
+ if (isSecretFile(path))
1231
+ return true;
1232
+ const segments = path.split('/');
1233
+ return this.selection.ignorePatterns.some((pattern) => {
1234
+ if (pattern.includes('*')) {
1235
+ // A leading '/' opts a glob pattern into SEGMENT-ANCHORED matching:
1236
+ // the pattern body must start at the beginning of the path or right
1237
+ // after a '/'. Without it, glob patterns keep their historical
1238
+ // unanchored substring semantics - anchoring is opt-in per pattern so
1239
+ // this change cannot alter any existing pattern's behavior.
1240
+ // (Motivating bug: unanchored 'tests/fixtures/*' also matched
1241
+ // 'integration-tests/fixtures/...' in every indexed project.)
1242
+ const anchored = pattern.startsWith('/');
1243
+ const body = anchored ? pattern.slice(1) : pattern;
1244
+ // Escape regex special chars, then replace all * with .*
1245
+ const escaped = body.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
1246
+ const source = escaped.replace(/\*/g, '.*');
1247
+ const regex = new RegExp(anchored ? `(^|/)${source}` : source);
1248
+ return regex.test(path);
1249
+ }
1250
+ // For non-glob patterns, check if any path segment matches exactly
1251
+ // or if the full path ends with the pattern (for extension-like patterns)
1252
+ return segments.some((segment) => segment === pattern) || path.endsWith('/' + pattern);
1253
+ });
1254
+ }
1255
+ }
1256
+ //# sourceMappingURL=fileSelection.js.map