index.ts 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. /**
  2. * Extraction Orchestrator
  3. *
  4. * Coordinates file scanning, parsing, and database storage.
  5. */
  6. import * as fs from 'fs';
  7. import * as fsp from 'fs/promises';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import * as crypto from 'crypto';
  11. import { execFileSync } from 'child_process';
  12. import {
  13. Language,
  14. FileRecord,
  15. ExtractionResult,
  16. ExtractionError,
  17. Node,
  18. Edge,
  19. UnresolvedReference,
  20. ReferenceKind,
  21. } from '../types';
  22. import { QueryBuilder } from '../db/queries';
  23. import { extractFromSource } from './tree-sitter';
  24. import { ParseWorkerPool, resolveParsePoolSize, resolveParseTimeoutMs } from './parse-pool';
  25. import { StoreWriter, StoreBundle, finalizeStoreBundle } from './store-writer';
  26. import { materializeKernelResult } from './kernel';
  27. import { detectLanguage, isSourceFile, isLanguageSupported, isFileLevelOnlyLanguage, initGrammars, loadGrammarsForLanguages, readGrammarWasmBytes } from './grammars';
  28. import { loadExtensionOverrides, loadIncludeIgnoredPatterns, loadExcludePatterns, loadIncludePatterns } from '../project-config';
  29. import { isCodeGraphDataDir } from '../directory';
  30. import { logDebug, logWarn } from '../errors';
  31. import { validatePathWithinRoot, normalizePath } from '../utils';
  32. import ignore, { Ignore } from 'ignore';
  33. import { detectFrameworks } from '../resolution/frameworks';
  34. import type { ResolutionContext } from '../resolution/types';
  35. import { createYielder, type MaybeYield } from '../resolution/cooperative-yield';
  36. /**
  37. * Number of files to read in parallel during indexing.
  38. * File reads are I/O-bound; batching overlaps I/O wait with CPU parse work.
  39. */
  40. const FILE_IO_BATCH_SIZE = 10;
  41. /**
  42. * How many files the `sync()` reconcile processes between cooperative yields to
  43. * the event loop. The reconcile runs two O(files) loops of synchronous `fs`
  44. * calls (existsSync for removals, statSync for adds/mods); on a very large repo
  45. * (~100k files) an un-yielded run wedges the main thread for minutes, which both
  46. * trips the liveness watchdog (it SIGKILLs a process whose loop stops turning)
  47. * and blocks the first MCP tool call behind the catch-up gate (issue #905).
  48. * Yielding every N files keeps the socket, the watchdog heartbeat, and any
  49. * concurrent read query responsive while the reconcile runs.
  50. */
  51. const SYNC_RECONCILE_YIELD_INTERVAL = 1000;
  52. // PARSER_RESET_INTERVAL moved to parse-worker.ts (runs in worker thread)
  53. /**
  54. * Maximum time (ms) to wait for a single file to parse in the worker thread.
  55. * If tree-sitter hangs or WASM runs out of memory, this prevents the entire
  56. * indexing run from freezing. The worker is restarted after a (hard) timeout.
  57. * Env-overridable via CODEGRAPH_PARSE_TIMEOUT_MS for slow storage (#1231).
  58. */
  59. const PARSE_TIMEOUT_MS = resolveParseTimeoutMs(process.env.CODEGRAPH_PARSE_TIMEOUT_MS);
  60. /**
  61. * Number of files to parse before recycling the worker thread.
  62. * WASM linear memory can grow but NEVER shrink (WebAssembly spec limitation).
  63. * The only way to reclaim tree-sitter's WASM heap is to destroy the entire
  64. * V8 isolate by terminating the worker thread and spawning a fresh one.
  65. * This interval balances memory usage against the cost of reloading grammars.
  66. */
  67. const WORKER_RECYCLE_INTERVAL = 250;
  68. /**
  69. * Progress callback for indexing operations
  70. */
  71. export interface IndexProgress {
  72. phase: 'scanning' | 'parsing' | 'storing' | 'resolving' | 'linking';
  73. current: number;
  74. total: number;
  75. currentFile?: string;
  76. }
  77. /**
  78. * Result of an indexing operation
  79. */
  80. export interface IndexResult {
  81. success: boolean;
  82. filesIndexed: number;
  83. filesSkipped: number;
  84. filesErrored: number;
  85. /**
  86. * How many indexable files the scan discovered — the ground truth the
  87. * indexed/skipped/errored tallies must add up to. A shortfall means files
  88. * were silently dropped mid-pipeline (e.g. a killed worker under load) and
  89. * the index is PARTIAL; callers surface that rather than trusting the
  90. * counts. Only set by full-index runs (indexAll), not indexFiles/sync.
  91. */
  92. filesDiscovered?: number;
  93. nodesCreated: number;
  94. edgesCreated: number;
  95. errors: ExtractionError[];
  96. durationMs: number;
  97. }
  98. /**
  99. * Result of a sync operation
  100. */
  101. export interface SyncResult {
  102. filesChecked: number;
  103. filesAdded: number;
  104. filesModified: number;
  105. filesRemoved: number;
  106. nodesUpdated: number;
  107. durationMs: number;
  108. changedFilePaths?: string[];
  109. }
  110. /**
  111. * Calculate SHA256 hash of file contents
  112. */
  113. export function hashContent(content: string): string {
  114. return crypto.createHash('sha256').update(content).digest('hex');
  115. }
  116. /**
  117. * Skip files larger than this (bytes). Generated bundles, minified JS, and
  118. * vendored blobs blow the WASM heap and the worker-recycle budget for no useful
  119. * symbols. 1 MB covers essentially all hand-written source.
  120. */
  121. const MAX_FILE_SIZE = 1024 * 1024;
  122. /**
  123. * Directory names that are dependency, build, cache, or tooling output across the
  124. * languages/frameworks CodeGraph supports — curated from the canonical
  125. * github/gitignore templates. Excluded by default so the graph reflects your code,
  126. * not third-party noise, without requiring a `.gitignore` (issue #407). The
  127. * exclusion applies uniformly (git or not, tracked or not); the only opt-in is an
  128. * explicit `.gitignore` negation (e.g. `!vendor/`). First-party-prone or generic
  129. * names (`packages`, `lib`, `app`, `bin`, `src`, `deps`, `env`, `tmp`, `storage`,
  130. * `Library`) are deliberately NOT listed, to avoid ever hiding real source.
  131. *
  132. * Only dirs that actually contain *indexable source* (or are enormous) earn a slot
  133. * — IDE/state dirs like `.idea`/`.vs` are omitted because CodeGraph indexes only
  134. * recognized source extensions, so they produce no symbols regardless.
  135. */
  136. const DEFAULT_IGNORE_DIRS: ReadonlySet<string> = new Set([
  137. // JS / TS — dependency directories
  138. 'node_modules', 'bower_components', 'jspm_packages', 'web_modules',
  139. '.yarn', '.pnpm-store',
  140. // JS / TS — framework & bundler build / cache / deploy output
  141. '.next', '.nuxt', '.svelte-kit', '.turbo', '.vite', '.parcel-cache', '.angular',
  142. '.docusaurus', 'storybook-static', '.vinxi', '.nitro', 'out-tsc',
  143. '.vercel', '.netlify', '.wrangler',
  144. // Build output (common across ecosystems)
  145. 'dist', 'build', 'out', '.output',
  146. // Test / coverage
  147. 'coverage', '.nyc_output',
  148. // Python
  149. '__pycache__', '__pypackages__', '.venv', 'venv', '.pixi', '.pdm-build',
  150. '.mypy_cache', '.pytest_cache', '.ruff_cache', '.tox', '.nox', '.hypothesis',
  151. '.ipynb_checkpoints', '.eggs',
  152. // Rust / JVM (Maven, Gradle, Scala)
  153. 'target', '.gradle',
  154. // .NET
  155. 'obj',
  156. // Vendored deps (Go, PHP/Composer, Ruby/Bundler)
  157. 'vendor',
  158. // Swift / iOS
  159. '.build', 'Pods', 'Carthage', 'DerivedData', '.swiftpm',
  160. // Dart / Flutter
  161. '.dart_tool', '.pub-cache',
  162. // Native (Android NDK, C/C++ deps)
  163. '.cxx', '.externalNativeBuild', 'vcpkg_installed',
  164. // Scala tooling
  165. '.bloop', '.metals',
  166. // Lua / Luau (LuaRocks)
  167. 'lua_modules', '.luarocks',
  168. // Delphi / RAD Studio IDE backups (duplicate .pas source — would double-count)
  169. '__history', '__recovery',
  170. // Generic cache
  171. '.cache',
  172. ]);
  173. /**
  174. * Android resource directory types. A `res/` tree holds ONLY non-code resources —
  175. * layouts, drawables, value bags (strings/colors/styles), menus, navigation
  176. * graphs — split into one typed subdirectory per kind, optionally density/locale/
  177. * version-qualified (`values-es`, `drawable-hdpi`, `layout-v21`, …). None of it
  178. * yields an extractable code symbol, yet on an Android app it DOMINATES the tree
  179. * (one report: 26k XML files = 97% of the project, 0 symbols), bloating the DB,
  180. * slowing indexing, and skewing both the file count and `codegraph_explore`
  181. * results (#1047). So these are excluded by default. The structure is
  182. * self-identifying — a non-Android project has no `res/layout/` etc., so it's
  183. * untouched — and the only XML that DOES produce symbols (MyBatis mappers) lives
  184. * under `src/main/resources/`, never `res/`, so nothing useful is dropped.
  185. * `res/raw/` is deliberately NOT here: it holds arbitrary bundled assets that can
  186. * be code-ish (a `.sql` schema, a `.js`), so we leave it indexed. Override any of
  187. * these with a `.gitignore` negation (e.g. `!res/values/`).
  188. */
  189. const ANDROID_RES_TYPES: readonly string[] = [
  190. 'anim', 'animator', 'color', 'drawable', 'font', 'layout',
  191. 'menu', 'mipmap', 'navigation', 'transition', 'values', 'xml',
  192. ];
  193. /** Gitignore-style patterns for the `ignore` matcher: the dirs above plus a few globs. */
  194. const DEFAULT_IGNORE_PATTERNS: string[] = [
  195. ...Array.from(DEFAULT_IGNORE_DIRS, (d) => `${d}/`),
  196. '*.egg-info/', // Python packaging metadata
  197. 'cmake-build-*/', // CLion / CMake build trees
  198. 'bazel-*/', // Bazel output symlink trees
  199. // Android resource dirs at any depth, with their qualifier variants (#1047).
  200. ...ANDROID_RES_TYPES.map((t) => `**/res/${t}*/`),
  201. ];
  202. /** True if `buf` decodes as strict UTF-8 (no invalid byte sequences). */
  203. function isValidUtf8(buf: Buffer): boolean {
  204. try {
  205. new TextDecoder('utf-8', { fatal: true }).decode(buf);
  206. return true;
  207. } catch {
  208. return false;
  209. }
  210. }
  211. /**
  212. * Read a `.gitignore` and return patterns safe to hand to the `ignore` matcher —
  213. * never throwing, even when the file isn't real gitignore text. Two failure
  214. * modes, both seen in the wild (issue #682):
  215. *
  216. * - The file isn't valid UTF-8 — e.g. transparently encrypted in place by
  217. * corporate DLP / endpoint-security software, leaving a UTF-16 header plus
  218. * ciphertext. None of it is meaningful patterns, so the whole file is skipped.
  219. * - The file is text but a single line can't be compiled to a regex by the
  220. * `ignore` library — `\\[` and friends throw "Unterminated character class".
  221. * Crucially the throw is LAZY (at match time, not `.add()`), so it would
  222. * otherwise escape mid-scan. That one pattern is dropped; the rest are kept.
  223. *
  224. * Either way a warning that NAMES the file is logged (the reporter couldn't tell
  225. * which `.gitignore` was at fault) and indexing continues instead of aborting.
  226. * Returns '' when there's nothing usable.
  227. */
  228. function readGitignorePatterns(giPath: string): string {
  229. let buf: Buffer;
  230. try {
  231. buf = fs.readFileSync(giPath);
  232. } catch {
  233. return ''; // unreadable (permissions / race) — treat as absent
  234. }
  235. // A NUL byte never appears in real gitignore text, and a fatal UTF-8 decode
  236. // catches the rest. Such a file isn't ignore patterns at all.
  237. if (buf.includes(0) || !isValidUtf8(buf)) {
  238. logWarn(
  239. 'Ignoring a .gitignore that is not valid UTF-8 text — it may have been encrypted ' +
  240. 'in place by endpoint-security software. Indexing continues without it.',
  241. { file: giPath },
  242. );
  243. return '';
  244. }
  245. const content = buf.toString('utf-8');
  246. // Fast path: one `.ignores()` call forces the library to compile EVERY rule,
  247. // so if it doesn't throw, the whole file is safe to use verbatim.
  248. try {
  249. ignore().add(content).ignores('.codegraph-probe');
  250. return content;
  251. } catch {
  252. // Fall through: a line is uncompilable — keep the good ones, drop the bad.
  253. }
  254. const kept: string[] = [];
  255. let dropped = 0;
  256. for (const line of content.split(/\r?\n/)) {
  257. try {
  258. ignore().add(line).ignores('.codegraph-probe');
  259. kept.push(line);
  260. } catch {
  261. dropped++;
  262. }
  263. }
  264. if (dropped > 0) {
  265. logWarn(
  266. `Skipped ${dropped} unparseable pattern(s) in a .gitignore; the rest are applied.`,
  267. { file: giPath },
  268. );
  269. }
  270. return kept.join('\n');
  271. }
  272. /**
  273. * An `ignore` matcher seeded with the built-in defaults, merged with the project's
  274. * root .gitignore so a negation there (e.g. `!vendor/`) overrides a default. Shared
  275. * by both enumeration paths so behavior is identical with or without git — and so
  276. * the defaults apply to tracked files too (committing a dependency dir doesn't make
  277. * it project code; the explicit `.gitignore` negation is the only opt-in).
  278. */
  279. export function buildDefaultIgnore(rootDir: string): Ignore {
  280. const ig = ignore().add(DEFAULT_IGNORE_PATTERNS);
  281. const rootGitignore = path.join(rootDir, '.gitignore');
  282. if (fs.existsSync(rootGitignore)) ig.add(readGitignorePatterns(rootGitignore));
  283. return ig;
  284. }
  285. /**
  286. * Defaults-only ignore matcher (no root `.gitignore` merged). Used wherever the
  287. * parent repo's own ignore rules must NOT apply — inside embedded child repos,
  288. * whose gitignore semantics their own `git ls-files` already enforced (#514).
  289. */
  290. function defaultsOnlyIgnore(): Ignore {
  291. return ignore().add(DEFAULT_IGNORE_PATTERNS);
  292. }
  293. /**
  294. * Matcher for the project's `codegraph.json` `includeIgnored` patterns — the
  295. * explicit opt-in to index embedded git repos living inside gitignored
  296. * directories (#622, #699). Returns `null` when the project opted in nothing,
  297. * which is the zero-config DEFAULT: `.gitignore` is then fully respected and a
  298. * gitignored directory (even one holding nested repos) is never walked or
  299. * indexed (#970, #976). Built once per scan/sync/scope operation from the scan
  300. * root and threaded down — never global, so multi-project daemons stay isolated.
  301. */
  302. function loadIncludeIgnoredMatcher(rootDir: string): Ignore | null {
  303. const patterns = loadIncludeIgnoredPatterns(rootDir);
  304. return patterns.length > 0 ? ignore().add(patterns) : null;
  305. }
  306. /**
  307. * Matcher for the project's `codegraph.json` `exclude` patterns — paths to keep
  308. * OUT of the index even when git-tracked, which `.gitignore` cannot do (#999).
  309. * The escape hatch for a committed vendor/theme/SDK directory. Returns `null`
  310. * when nothing is excluded (the zero-config default → no overhead). Matched
  311. * against project-root-relative paths, so it applies uniformly across the whole
  312. * workspace, including inside embedded repos (excluding `static/` means gone
  313. * everywhere). Built once per scan/sync/scope operation from the scan root.
  314. */
  315. function loadExcludeMatcher(rootDir: string): Ignore | null {
  316. const patterns = loadExcludePatterns(rootDir);
  317. return patterns.length > 0 ? ignore().add(patterns) : null;
  318. }
  319. /**
  320. * Matcher for the project's `codegraph.json` `include` patterns — first-party
  321. * source to force INTO the index even when `.gitignore` drops it (the general
  322. * whitelist `includeIgnored` never was — that one only revives *embedded git
  323. * repos*). The case it exists for: a project under a second VCS (SVN/Perforce)
  324. * `.gitignore`s its own real source so it stays out of Git, yet we still want it
  325. * indexed. Returns `null` when nothing is force-included (the zero-config
  326. * default → no overhead, no extra walk). Built once per scan/sync/scope
  327. * operation from the scan root.
  328. */
  329. function loadIncludeMatcher(rootDir: string): Ignore | null {
  330. const patterns = loadIncludePatterns(rootDir);
  331. return patterns.length > 0 ? ignore().add(patterns) : null;
  332. }
  333. /** Glob metacharacters that end the static (literal) prefix of an `include` pattern. */
  334. const GLOB_META = /[*?[\]{}!]/;
  335. /**
  336. * The static directory prefix of each `include` pattern — the literal leading
  337. * path up to the first glob segment — trailing-slashed, used to (a) walk only
  338. * the opted-in subtrees in `collectIncludedFiles` and (b) let `ScopeIgnore` keep
  339. * the watcher descending toward them. `Tools/` stays `Tools/`; a recursive
  340. * `Tools/**` glob yields `Tools/`; `src/local/file.ts` yields `src/local/` (the
  341. * file's dir); a pattern that starts with a glob (like a leading `**`) yields
  342. * `''`, meaning "no static root — walk the whole tree". Duplicates and roots
  343. * nested under a broader root are collapsed so each subtree is walked once.
  344. */
  345. function includeStaticRoots(patterns: string[]): string[] {
  346. const roots = new Set<string>();
  347. for (const pattern of patterns) {
  348. let p = pattern.replace(/^\/+/, '');
  349. const trailingSlash = p.endsWith('/');
  350. if (trailingSlash) p = p.slice(0, -1);
  351. const segs = p.split('/').filter(Boolean);
  352. const lead: string[] = [];
  353. for (const s of segs) {
  354. if (GLOB_META.test(s)) break;
  355. lead.push(s);
  356. }
  357. const hadWildcard = lead.length < segs.length;
  358. // A wholly-literal pattern with no trailing slash names a file (or a dir we
  359. // can't tell apart) — drop its last segment so we walk the containing dir
  360. // and let the matcher pick the file. A trailing slash or a glob means the
  361. // remaining `lead` is already the directory to walk.
  362. if (!hadWildcard && !trailingSlash && lead.length > 0) lead.pop();
  363. if (lead.length === 0) {
  364. roots.clear();
  365. roots.add('');
  366. return ['']; // a top-level glob forces a whole-tree walk; nothing narrower matters
  367. }
  368. roots.add(lead.join('/') + '/');
  369. }
  370. // Collapse roots nested under a broader one (e.g. drop `a/b/` if `a/` is present).
  371. const all = [...roots];
  372. return all.filter((r) => !all.some((other) => other !== r && r.startsWith(other)));
  373. }
  374. /**
  375. * Actively discover the source files an `include` whitelist forces in. `git
  376. * ls-files` never lists gitignored files, so a filtered filesystem walk of just
  377. * the opted-in subtrees (`includeStaticRoots`) is the only way to find them.
  378. * Returns project-root-relative, normalized source-file paths.
  379. *
  380. * A file is collected when it MATCHES `include`, is NOT hit by `exclude` (an
  381. * explicit exclude always wins), is a recognized source file, and does not live
  382. * under a built-in default-ignored dir (`node_modules`, `dist`, …), `.git`, or
  383. * CodeGraph's data dir — those are never resurfaced, mirroring `ScopeIgnore`.
  384. * `.gitignore` is deliberately NOT consulted: overriding it is the whole point.
  385. */
  386. function collectIncludedFiles(
  387. rootDir: string,
  388. include: Ignore,
  389. exclude: Ignore | null,
  390. roots: string[],
  391. overrides: Record<string, Language>,
  392. ): Set<string> {
  393. const out = new Set<string>();
  394. const defaults = defaultsOnlyIgnore();
  395. const visited = new Set<string>();
  396. const consider = (abs: string, rel: string, isDir: boolean): void => {
  397. if (isDir) {
  398. if (defaults.ignores(rel + '/')) return; // never node_modules/dist/… via include
  399. // An explicit `exclude` always wins over `include`; prune the whole subtree
  400. // here so a large excluded dir (a committed frontend's own vendored deps,
  401. // build output, …) is never walked — the per-file guard below still catches
  402. // anything a directory pattern doesn't, so this is a pure efficiency win.
  403. if (exclude && exclude.ignores(rel + '/')) return;
  404. walk(abs);
  405. } else {
  406. if (defaults.ignores(rel)) return;
  407. if (!include.ignores(rel)) return;
  408. if (exclude && exclude.ignores(rel)) return;
  409. if (!isSourceFile(rel, overrides)) return;
  410. out.add(rel);
  411. }
  412. };
  413. function walk(absDir: string): void {
  414. let realDir: string;
  415. try {
  416. realDir = fs.realpathSync(absDir);
  417. } catch {
  418. return;
  419. }
  420. if (visited.has(realDir)) return; // symlink-cycle guard
  421. visited.add(realDir);
  422. let entries: fs.Dirent[];
  423. try {
  424. entries = fs.readdirSync(absDir, { withFileTypes: true });
  425. } catch {
  426. return;
  427. }
  428. for (const entry of entries) {
  429. if (entry.name === '.git' || isCodeGraphDataDir(entry.name)) continue;
  430. const abs = path.join(absDir, entry.name);
  431. const rel = normalizePath(path.relative(rootDir, abs));
  432. if (!rel || rel.startsWith('..')) continue;
  433. if (entry.isSymbolicLink()) {
  434. try {
  435. const st = fs.statSync(fs.realpathSync(abs));
  436. consider(abs, rel, st.isDirectory());
  437. } catch {
  438. // broken symlink — skip
  439. }
  440. continue;
  441. }
  442. consider(abs, rel, entry.isDirectory());
  443. }
  444. }
  445. for (const root of roots) {
  446. walk(root === '' ? rootDir : path.join(rootDir, root));
  447. }
  448. return out;
  449. }
  450. /**
  451. * The included source files (`codegraph.json` `include`) for a scan root, or an
  452. * empty set when nothing is force-included. Centralizes loading the matcher,
  453. * roots, exclude, and overrides so both enumeration paths (git and filesystem
  454. * walk) add the same files.
  455. */
  456. function collectIncludedFilesForRoot(rootDir: string): Set<string> {
  457. const include = loadIncludeMatcher(rootDir);
  458. if (!include) return new Set();
  459. const roots = includeStaticRoots(loadIncludePatterns(rootDir));
  460. return collectIncludedFiles(rootDir, include, loadExcludeMatcher(rootDir), roots, loadExtensionOverrides(rootDir));
  461. }
  462. /**
  463. * `git ls-files --directory` collapses a wholly-untracked/ignored directory into
  464. * one entry — and when the command's own cwd is such a directory (the indexed
  465. * root is itself a git-ignored subdir of an enclosing repo), git emits the
  466. * literal `./` meaning "this entire directory". That sentinel is not a real
  467. * nested path: feeding it to the `ignore` matcher throws ("path should be a
  468. * `path.relative()`d string, but got "./""), which used to abort `buildScopeIgnore`
  469. * and so break the MCP daemon's watcher/auto-sync on connect; and joining it back
  470. * onto `repoDir` would just re-point at the cwd. Drop it wherever we consume
  471. * `--directory` output. (#936)
  472. */
  473. function isWholeCwdEntry(entry: string): boolean {
  474. return entry === './' || entry === '.' || entry === '';
  475. }
  476. /**
  477. * List the gitignored DIRECTORIES of a repo (collapsed, trailing-slash form),
  478. * relative to `repoDir`. These are invisible to every other `git ls-files` /
  479. * `git status` mode — and in a multi-repo workspace they are exactly where the
  480. * nested project repos live (a super-repo `.gitignore`s its child repos to keep
  481. * `git status` quiet; that does not make them third-party code). (#514)
  482. */
  483. function listIgnoredDirs(repoDir: string): string[] {
  484. try {
  485. const out = execFileSync(
  486. 'git',
  487. ['ls-files', '-z', '-o', '-i', '--exclude-standard', '--directory'],
  488. { cwd: repoDir, encoding: 'utf-8' as const, timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'] as ['pipe', 'pipe', 'pipe'], windowsHide: true }
  489. );
  490. return out.split('\0').filter((e) => e.endsWith('/') && !isWholeCwdEntry(e));
  491. } catch {
  492. return [];
  493. }
  494. }
  495. /** Max directory depth searched below an ignored dir for nested `.git` roots. */
  496. const EMBEDDED_REPO_SEARCH_DEPTH = 4;
  497. /** Max directories examined per search — a huge ignored data dir must never stall a scan/sync. */
  498. const EMBEDDED_REPO_SEARCH_ENTRIES = 2000;
  499. /**
  500. * Classify a directory's `.git` entry for embedded-repo discovery.
  501. *
  502. * - A `.git` **directory** is an embedded clone — distinct first-party code a
  503. * super-repo merely hides from git; index it (#193, #514).
  504. * - A `.git` **file** is a pointer (`gitdir: …`). A git **worktree** points into
  505. * the host repo's own `.git/worktrees/<name>`, so it is a second working view
  506. * of a repo CodeGraph already indexes — indexing it just duplicates the whole
  507. * graph N times; skip it (#848). A **submodule worktree** points into
  508. * `.git/modules/<module>/worktrees/<name>` — same duplication, so skip it too
  509. * (#945). A **submodule** checkout points into `.git/modules/<module>` (no
  510. * `worktrees/` segment) and is distinct code, so index it as before.
  511. *
  512. * Returns `'none'` when there is no `.git` entry here.
  513. */
  514. function classifyGitDir(absDir: string): 'embedded' | 'worktree' | 'none' {
  515. let st: fs.Stats;
  516. try {
  517. st = fs.statSync(path.join(absDir, '.git'));
  518. } catch {
  519. return 'none';
  520. }
  521. if (st.isDirectory()) return 'embedded';
  522. if (!st.isFile()) return 'none';
  523. try {
  524. const gitdir = fs.readFileSync(path.join(absDir, '.git'), 'utf8').match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
  525. // A worktree's gitdir lives under some repo's `.git/worktrees/<name>` —
  526. // either the top-level repo's (`.git/worktrees/`) or, for a worktree of a
  527. // submodule, that submodule's gitdir (`.git/modules/<module>/worktrees/`).
  528. // The optional `modules/<module>` segment covers the submodule case (#945).
  529. // Match both separators so a Windows-style pointer is recognized too.
  530. if (gitdir && /(^|[\\/])\.git[\\/](modules[\\/][^\\/]+[\\/])?worktrees[\\/]/.test(gitdir)) return 'worktree';
  531. } catch {
  532. // Unreadable `.git` pointer — fall back to the prior "index it" behavior.
  533. }
  534. return 'embedded';
  535. }
  536. /**
  537. * Find git repositories nested under `absDir` (inclusive), shallow bounded BFS.
  538. * Stops descending at each repo root found — contents belong to that repo's own
  539. * enumeration. Skips default-ignored dirs (`node_modules` can contain `.git`
  540. * from npm git-dependencies — that never makes it project code) and CodeGraph
  541. * data dirs. Depth- and entry-capped so a huge ignored tree can't stall the scan.
  542. */
  543. function findNestedGitRepos(absDir: string, relPrefix: string): string[] {
  544. const found: string[] = [];
  545. const defaults = defaultsOnlyIgnore();
  546. const queue: Array<{ abs: string; rel: string; depth: number }> = [
  547. { abs: absDir, rel: relPrefix, depth: 0 },
  548. ];
  549. let examined = 0;
  550. while (queue.length > 0) {
  551. const { abs, rel, depth } = queue.shift()!;
  552. if (++examined > EMBEDDED_REPO_SEARCH_ENTRIES) {
  553. logDebug('Embedded-repo search entry cap hit — deeper repos (if any) not discovered', { under: relPrefix });
  554. break;
  555. }
  556. const cls = classifyGitDir(abs);
  557. if (cls === 'worktree') {
  558. continue; // a git worktree duplicates an already-indexed repo (#848) — skip
  559. }
  560. if (cls === 'embedded') {
  561. found.push(rel);
  562. continue; // its own git handles everything below
  563. }
  564. if (depth >= EMBEDDED_REPO_SEARCH_DEPTH) continue;
  565. let entries: fs.Dirent[];
  566. try {
  567. entries = fs.readdirSync(abs, { withFileTypes: true });
  568. } catch {
  569. continue;
  570. }
  571. for (const entry of entries) {
  572. if (!entry.isDirectory()) continue;
  573. if (entry.name === '.git' || isCodeGraphDataDir(entry.name)) continue;
  574. const childRel = rel + entry.name + '/';
  575. if (defaults.ignores(childRel)) continue;
  576. queue.push({ abs: path.join(abs, entry.name), rel: childRel, depth: depth + 1 });
  577. }
  578. }
  579. return found;
  580. }
  581. /**
  582. * Workspace-scope ignore matcher. Ordinary paths get the root's matcher
  583. * (built-in defaults + root `.gitignore`); paths inside an EMBEDDED repo get
  584. * that repo's own matcher (defaults + its root `.gitignore`) — the parent's
  585. * `.gitignore` hides a child repo from git, not from the index (#514). A
  586. * directory path (trailing slash) that is an ANCESTOR of an embedded root is
  587. * never ignored, so directory-pruning callers (the Linux per-directory
  588. * watcher) still descend to reach the embedded repos.
  589. *
  590. * Single source of truth for indexer and watcher scope — they must not diverge.
  591. */
  592. export class ScopeIgnore {
  593. private embedded: Array<{ root: string; matcher: Ignore }>;
  594. private defaults: Ignore = defaultsOnlyIgnore();
  595. constructor(
  596. private rootMatcher: Ignore,
  597. embedded: Array<{ root: string; matcher: Ignore }>,
  598. /**
  599. * Project `codegraph.json` `exclude` patterns (#999), matched against the
  600. * full root-relative path. Wins over everything else — an explicit user
  601. * exclude applies even to tracked files and even inside embedded repos.
  602. */
  603. private exclude: Ignore | null = null,
  604. /**
  605. * Project `codegraph.json` `include` patterns — first-party source forced
  606. * INTO the index despite `.gitignore`. When a path matches, it is NOT
  607. * ignored (so the watcher watches it), overriding `.gitignore`/`rootMatcher`
  608. * — but never `exclude` (checked first) and never a built-in default-ignored
  609. * dir. `includeRoots` are the static prefixes so a gitignored ANCESTOR
  610. * directory of an included subtree still isn't pruned by the directory
  611. * walker/watcher.
  612. */
  613. private include: Ignore | null = null,
  614. private includeRoots: string[] = [],
  615. ) {
  616. // Longest root first so paths in nested embedded repos hit the innermost matcher.
  617. this.embedded = [...embedded].sort((a, b) => b.root.length - a.root.length);
  618. }
  619. ignores(rel: string): boolean {
  620. // User `exclude` (#999) is checked first and against the full root-relative
  621. // path: it must drop git-TRACKED paths (which `.gitignore` can't) and apply
  622. // everywhere, including ancestors of embedded repos.
  623. if (this.exclude && this.exclude.ignores(rel)) return true;
  624. // User `include`: force first-party source in despite `.gitignore`. Never
  625. // resurfaces a built-in default-ignored dir (node_modules/dist/…), so an
  626. // include pattern can't accidentally pull in dependency/build trees.
  627. if (this.include && !this.defaults.ignores(rel)) {
  628. if (rel.endsWith('/')) {
  629. // A directory on (or leading to) an included subtree must stay walkable
  630. // so the watcher/walker descends to reach the forced-in files.
  631. if (this.includeRoots.some((r) => r.startsWith(rel) || rel.startsWith(r))) return false;
  632. } else if (this.include.ignores(rel)) {
  633. return false;
  634. }
  635. }
  636. for (const { root, matcher } of this.embedded) {
  637. if (rel.startsWith(root)) {
  638. const inner = rel.slice(root.length);
  639. if (inner === '') return false;
  640. // Built-in defaults apply to the FULL path uniformly (#407) — an
  641. // embedded repo inside node_modules (an npm git-dependency) must stay
  642. // excluded even though its own rules wouldn't ignore its files.
  643. return this.defaults.ignores(rel) || matcher.ignores(inner);
  644. }
  645. }
  646. // Never prune a directory that leads to an embedded repo.
  647. if (rel.endsWith('/') && this.embedded.some(({ root }) => root.startsWith(rel))) {
  648. return false;
  649. }
  650. return this.rootMatcher.ignores(rel);
  651. }
  652. }
  653. /**
  654. * Build the workspace-scope matcher. When the caller already knows the
  655. * embedded roots (the scanner discovers them during collection), pass them to
  656. * skip rediscovery; otherwise they're discovered here (the watcher path).
  657. */
  658. export function buildScopeIgnore(rootDir: string, embeddedRoots?: Iterable<string>): ScopeIgnore {
  659. const roots = embeddedRoots ? [...embeddedRoots] : discoverEmbeddedRepoRoots(rootDir);
  660. const include = loadIncludeMatcher(rootDir);
  661. return new ScopeIgnore(
  662. buildDefaultIgnore(rootDir),
  663. roots.map((root) => ({ root, matcher: buildDefaultIgnore(path.join(rootDir, root)) })),
  664. loadExcludeMatcher(rootDir),
  665. include,
  666. include ? includeStaticRoots(loadIncludePatterns(rootDir)) : [],
  667. );
  668. }
  669. /**
  670. * Whether an embedded repo found as a tracked gitlink (mode 160000, #1031/#1033)
  671. * must be SKIPPED rather than indexed. A gitlink is tracked, so `.gitignore`
  672. * can't untrack it — but the discovery passes for it must still honor the same
  673. * scope rules as every other path, or a gitignored reference/data dir full of
  674. * `git add`ed clones gets pulled into the index against the user's stated intent
  675. * (#1065). Two reasons to skip:
  676. * 1. It sits in a built-in default-ignored location — an npm git-dependency
  677. * under `node_modules` is never project code; not even an explicit opt-in
  678. * revives it (matches `findIgnoredEmbeddedRepos`).
  679. * 2. The parent repo's own `.gitignore` covers its path and the project did
  680. * NOT opt that path in via `codegraph.json` `includeIgnored`. The gitignore
  681. * rule is the user's stated intent to keep that path out of scope, exactly
  682. * as for an UNtracked embedded repo — respect it by default, opt back in
  683. * with `includeIgnored` (#514, #970, #976).
  684. * `relDir` is repoDir-relative (trailing-slashed); `prefix` is repoDir's
  685. * scan-root-relative path so the `includeIgnored` pattern is matched on the full
  686. * scan-root-relative path. `defaults` is `defaultsOnlyIgnore()` and `repoIgnore`
  687. * is `buildDefaultIgnore(repoDir)` (defaults + the repo's own `.gitignore`),
  688. * both passed in so they're built once per repo level rather than per gitlink.
  689. */
  690. function gitlinkEmbeddedRepoSkipped(
  691. relDir: string,
  692. prefix: string,
  693. defaults: Ignore,
  694. repoIgnore: Ignore,
  695. includeIgnored: Ignore | null,
  696. ): boolean {
  697. if (defaults.ignores(relDir)) return true; // default-ignored — never index, opt-in can't revive
  698. if (!repoIgnore.ignores(relDir)) return false; // not ignored at all — index as before (#1031/#1033)
  699. // Gitignored by the repo's own rules — skip unless the project opted it in.
  700. return !includeIgnored?.ignores(normalizePath(prefix + relDir));
  701. }
  702. /**
  703. * Standalone discovery of every embedded repo root under `rootDir` (relative,
  704. * trailing-slashed) — the untracked kind (#193) always, and the gitignored kind
  705. * (#514) only for directories the project opted in via `codegraph.json`
  706. * `includeIgnored` (#622, #699); otherwise `.gitignore` is respected and they
  707. * are not discovered (#970, #976). Recursive (an embedded repo can embed further
  708. * repos). Returns [] for non-git roots: the filesystem walk handles nested repos
  709. * there already.
  710. */
  711. export function discoverEmbeddedRepoRoots(rootDir: string): string[] {
  712. try {
  713. execFileSync('git', ['rev-parse', '--git-dir'], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
  714. } catch {
  715. return [];
  716. }
  717. const out: string[] = [];
  718. const defaults = defaultsOnlyIgnore();
  719. const includeIgnored = loadIncludeIgnoredMatcher(rootDir);
  720. const visit = (repoAbs: string, prefix: string): void => {
  721. const candidates: string[] = [];
  722. try {
  723. const o = execFileSync(
  724. 'git',
  725. ['ls-files', '-z', '-o', '--exclude-standard', '--directory'],
  726. { cwd: repoAbs, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }
  727. );
  728. for (const e of o.split('\0')) {
  729. if (e.endsWith('/') && !isWholeCwdEntry(e) && !defaults.ignores(e)) {
  730. candidates.push(...findNestedGitRepos(path.join(repoAbs, e), e));
  731. }
  732. }
  733. } catch { /* untracked listing failed — ignored-side discovery still runs */ }
  734. // Unexpanded gitlinks (mode 160000) with a real checkout on disk — embedded
  735. // repos `git add`ed without `.gitmodules`, or submodules not active here. The
  736. // untracked listing above can't see them (they're tracked), so find them the
  737. // same way collectGitFiles does, keeping watcher scope == indexer scope.
  738. // (#1031, #1033)
  739. try {
  740. const staged = execFileSync(
  741. 'git',
  742. ['ls-files', '-z', '-s', '--recurse-submodules'],
  743. { cwd: repoAbs, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }
  744. );
  745. const repoIgnore = buildDefaultIgnore(repoAbs);
  746. for (const entry of staged.split('\0')) {
  747. if (!entry || entry.slice(0, 6) !== '160000') continue;
  748. const tab = entry.indexOf('\t');
  749. if (tab === -1) continue;
  750. const rel = entry.slice(tab + 1);
  751. const relDir = rel.endsWith('/') ? rel : rel + '/';
  752. // A gitlink under a gitignored path is respected (not indexed) unless the
  753. // project opted it in — same rule as the untracked-ignored kind (#1065).
  754. if (gitlinkEmbeddedRepoSkipped(relDir, prefix, defaults, repoIgnore, includeIgnored)) continue;
  755. if (classifyGitDir(path.join(repoAbs, rel)) === 'embedded') candidates.push(relDir);
  756. }
  757. } catch { /* staged listing failed — other discovery still runs */ }
  758. candidates.push(...findIgnoredEmbeddedRepos(repoAbs, includeIgnored, prefix));
  759. for (const rel of candidates) {
  760. const full = normalizePath(prefix + rel);
  761. out.push(full);
  762. visit(path.join(repoAbs, rel), full);
  763. }
  764. };
  765. visit(rootDir, '');
  766. return out;
  767. }
  768. /**
  769. * Cap on how many skipped gitignored repos the CLI hint enumerates — a huge
  770. * gitignored data dir full of clones must never turn the hint scan into a long
  771. * walk. Enough to make the point; the caller says "+N more" past this.
  772. */
  773. const UNINDEXED_IGNORED_REPO_HINT_CAP = 100;
  774. /**
  775. * The INVERSE of the gitignored side of {@link discoverEmbeddedRepoRoots}:
  776. * nested git repositories under a gitignored directory that the project has NOT
  777. * opted into via `codegraph.json` `includeIgnored`. These are real repos the
  778. * default `init`/`index` deliberately skips because `.gitignore` excludes them
  779. * (#970, #976) — most visibly the "super-repo `.gitignore`s its child repos"
  780. * layout (#1156), where `init` at the parent correctly indexes ~nothing while
  781. * `init` inside each child works. The CLI uses this to turn that silent empty
  782. * index into an actionable hint: it names the skipped repos and offers to opt
  783. * them in. Paths are `rootDir`-relative and trailing-slashed (valid
  784. * `includeIgnored` patterns as-is). Returns `[]` for a non-git root (a
  785. * filesystem walk already descends into nested repos there), skips built-in
  786. * default-ignored dirs (`node_modules`, …), and is bounded so it never stalls
  787. * on a giant ignored tree.
  788. */
  789. export function findUnindexedIgnoredRepos(rootDir: string): string[] {
  790. try {
  791. execFileSync('git', ['rev-parse', '--git-dir'], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
  792. } catch {
  793. return [];
  794. }
  795. const defaults = defaultsOnlyIgnore();
  796. const includeIgnored = loadIncludeIgnoredMatcher(rootDir);
  797. const repos: string[] = [];
  798. for (const dir of listIgnoredDirs(rootDir)) {
  799. if (defaults.ignores(dir)) continue; // node_modules etc. — never project code
  800. if (includeIgnored?.ignores(normalizePath(dir))) continue; // already opted in — nothing to nag about
  801. for (const repo of findNestedGitRepos(path.join(rootDir, dir), dir)) {
  802. // Per-repo opt-in check, mirroring findIgnoredEmbeddedRepos: a child
  803. // pattern (`repos/a/`) doesn't match the parent dir above but DOES
  804. // cover this repo — it's indexed, so don't nag about it (#1295).
  805. if (includeIgnored?.ignores(normalizePath(repo))) continue;
  806. repos.push(repo);
  807. if (repos.length >= UNINDEXED_IGNORED_REPO_HINT_CAP) return repos;
  808. }
  809. }
  810. return repos;
  811. }
  812. /**
  813. * Discover embedded repos hidden by `repoDir`'s OWN gitignore rules: for each
  814. * gitignored directory, search for nested `.git` roots. Returns repo paths
  815. * relative to `repoDir`, trailing-slashed.
  816. *
  817. * OPT-IN ONLY. Walking into a gitignored directory contradicts what every other
  818. * tool (and CodeGraph's own `git ls-files` foundation) does — `.gitignore`
  819. * excludes. So this returns `[]` unless the project opted the directory in via
  820. * `codegraph.json` `includeIgnored`; without that, a gitignored dir — including
  821. * a huge reference/data dir full of nested clones — is left untouched (#970,
  822. * #976). When opted in, it restores the super-repo-of-clones behavior (#622,
  823. * #699). `prefix` is the scan-root-relative path of `repoDir`, so a pattern like
  824. * `services/` opts that whole subtree in at any recursion depth. Built-in
  825. * default excludes (`node_modules`, …) are always skipped.
  826. */
  827. function findIgnoredEmbeddedRepos(repoDir: string, includeIgnored: Ignore | null, prefix: string): string[] {
  828. if (!includeIgnored) return [];
  829. const defaults = defaultsOnlyIgnore();
  830. const repos: string[] = [];
  831. for (const dir of listIgnoredDirs(repoDir)) {
  832. if (defaults.ignores(dir)) continue;
  833. const nested = findNestedGitRepos(path.join(repoDir, dir), dir);
  834. if (includeIgnored.ignores(normalizePath(prefix + dir))) {
  835. // The whole ignored dir is opted in — every nested repo under it counts.
  836. repos.push(...nested);
  837. } else {
  838. // A single gitignore rule often covers the PARENT of the opted-in
  839. // repos: `.gitignore: /repos/` lists `repos/` as ONE ignored entry,
  840. // while `includeIgnored: ["repos/a/"]` (the CLI hint's own suggested
  841. // spelling) names the child — which never matches the parent path, so
  842. // the opt-in silently did nothing (#1295). Match each nested repo
  843. // root individually so both spellings work. The walk is bounded
  844. // (depth/entry caps in findNestedGitRepos) and only runs when
  845. // includeIgnored is configured at all.
  846. repos.push(...nested.filter((r) => includeIgnored.ignores(normalizePath(prefix + r))));
  847. }
  848. }
  849. return repos;
  850. }
  851. /**
  852. * Collect git-visible files (tracked + untracked, .gitignore-respected) from the
  853. * git repository rooted at `repoDir`, adding each to `files` with `prefix`
  854. * prepended so paths stay relative to the original scan root.
  855. *
  856. * Recurses into embedded git repositories — nested repos that are NOT submodules
  857. * (independent clones living inside the workspace, common in CMake "super-repo"
  858. * layouts). The parent repo's `git ls-files` cannot see into them: tracked output
  859. * skips them entirely, and untracked output reports them only as an opaque
  860. * "subdir/" entry (trailing slash) rather than expanding their files. Each
  861. * embedded repo is its own git boundary, so we re-run `git ls-files` inside it.
  862. * (See issue #193.) GITIGNORED embedded repos are invisible even to that; they
  863. * are discovered separately via `findIgnoredEmbeddedRepos` (#514) but ONLY for
  864. * directories the project opted in through `codegraph.json` `includeIgnored`
  865. * (`includeIgnored` here, threaded from the scan root) — by default `.gitignore`
  866. * is respected and they stay out (#970, #976). Every embedded repo root (however
  867. * found) is recorded in `embeddedRoots` so callers can exempt its files from the
  868. * parent's own gitignore rules.
  869. */
  870. function collectGitFiles(repoDir: string, prefix: string, files: Set<string>, embeddedRoots?: Set<string>, includeIgnored: Ignore | null = null): void {
  871. const gitOpts = { cwd: repoDir, encoding: 'utf-8' as const, timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'] as ['pipe', 'pipe', 'pipe'], windowsHide: true };
  872. // Tracked files. --recurse-submodules pulls in files from active submodules,
  873. // which the index would otherwise represent only as a commit pointer.
  874. // Without this, monorepos using submodules index 0 files. (See issue #147.)
  875. // Note: --recurse-submodules only supports -c/--cached and --stage modes — it
  876. // can't be combined with -o, so untracked files are gathered separately below.
  877. //
  878. // We use --stage (-s) rather than -c so each entry carries its file mode. That
  879. // lets us spot gitlink entries (mode 160000) that --recurse-submodules did NOT
  880. // expand: a nested repo `git add`ed without a `.gitmodules` entry, or a
  881. // submodule that isn't active/initialized in this checkout. Such a gitlink
  882. // falls through every pass — it's tracked, so the untracked `-o` listing below
  883. // never reports it, and --recurse-submodules only expands ACTIVE submodules —
  884. // so its source would be silently skipped, leaving only the super-repo's own
  885. // files indexed. We collect those gitlinks here and recurse into them below.
  886. // (An active submodule is expanded inline by --recurse-submodules and so never
  887. // surfaces as a 160000 entry — only the unhandled gitlinks do.) (#1031, #1033)
  888. //
  889. // -z gives NUL-separated, unquoted output so non-ASCII (e.g. CJK) paths
  890. // survive verbatim. Without it git octal-escapes and double-quotes such paths
  891. // (the core.quotepath default), and the quoted form never matches a real file
  892. // on disk → those files are silently dropped from the index. (#541) With -s the
  893. // path follows a TAB after the `<mode> <object> <stage>` prefix.
  894. const gitlinkRels: string[] = [];
  895. const tracked = execFileSync('git', ['ls-files', '-z', '-s', '--recurse-submodules'], gitOpts);
  896. for (const entry of tracked.split('\0')) {
  897. if (!entry) continue;
  898. const tab = entry.indexOf('\t');
  899. if (tab === -1) continue; // --stage always emits "<mode> <object> <stage>\t<path>"
  900. const rel = entry.slice(tab + 1);
  901. if (entry.slice(0, 6) === '160000') {
  902. gitlinkRels.push(rel); // an unexpanded gitlink — recursed into below, not a source file itself
  903. continue;
  904. }
  905. files.add(normalizePath(prefix + rel));
  906. }
  907. // Untracked files (submodules manage their own untracked state). Embedded git
  908. // repos surface here as a single "subdir/" entry that git refuses to descend
  909. // into — recurse into those as their own repos so their source gets indexed.
  910. const untracked = execFileSync('git', ['ls-files', '-z', '-o', '--exclude-standard'], gitOpts);
  911. for (const rel of untracked.split('\0')) {
  912. if (!rel) continue;
  913. if (rel.endsWith('/')) {
  914. // git only emits a trailing-slash directory entry for an embedded repo.
  915. // Guard with a .git check anyway, and skip anything else exactly as git
  916. // itself skips it (we never descend into a non-repo opaque dir). Never
  917. // descend into default-ignored locations — an embedded repo inside
  918. // node_modules is an npm git-dependency, not project code.
  919. const childDir = path.join(repoDir, rel);
  920. // A git worktree surfaces here as an opaque untracked dir too — skip it,
  921. // it's a duplicate working view of an already-indexed repo (#848).
  922. if (classifyGitDir(childDir) === 'embedded' && !defaultsOnlyIgnore().ignores(rel)) {
  923. embeddedRoots?.add(normalizePath(prefix + rel));
  924. collectGitFiles(childDir, prefix + rel, files, embeddedRoots, includeIgnored);
  925. }
  926. continue;
  927. }
  928. files.add(normalizePath(prefix + rel));
  929. }
  930. // Gitlink entries (mode 160000) that --recurse-submodules left unexpanded —
  931. // an embedded repo `git add`ed without `.gitmodules`, or a submodule not
  932. // active/initialized in this checkout. When such a gitlink has a real working
  933. // tree on disk it is distinct first-party code we must index as its own
  934. // embedded repo: the tracked pass skipped its contents and the untracked pass
  935. // never sees it (it's tracked, not "other"). A gitlink with no checkout on disk
  936. // (an uninitialized submodule — empty dir, no `.git`) has nothing to index and
  937. // is left alone, as is a submodule worktree (a duplicate view, #945). (#1031, #1033)
  938. if (gitlinkRels.length > 0) {
  939. const defaults = defaultsOnlyIgnore();
  940. const repoIgnore = buildDefaultIgnore(repoDir);
  941. for (const rel of gitlinkRels) {
  942. const relDir = rel.endsWith('/') ? rel : rel + '/';
  943. // A gitlink under a gitignored path is respected (not indexed) unless the
  944. // project opted it in via `includeIgnored` — keep tracked gitlinks under
  945. // the same scope rule as the untracked-ignored kind below (#1065).
  946. if (gitlinkEmbeddedRepoSkipped(relDir, prefix, defaults, repoIgnore, includeIgnored)) continue;
  947. const childDir = path.join(repoDir, rel);
  948. // 'embedded' = a real .git checkout on disk; 'worktree' and 'none' are skipped.
  949. if (classifyGitDir(childDir) !== 'embedded') continue;
  950. embeddedRoots?.add(normalizePath(prefix + relDir));
  951. collectGitFiles(childDir, prefix + relDir, files, embeddedRoots, includeIgnored);
  952. }
  953. }
  954. // Embedded repos hidden by THIS repo's ignore rules (`/packages/` in a
  955. // super-repo .gitignore) never appear in any listing above. By default they
  956. // stay hidden — `.gitignore` is respected (#970, #976). They are recursed into
  957. // only when the project opted the directory in via `codegraph.json`
  958. // `includeIgnored` (#622, #699), which `findIgnoredEmbeddedRepos` enforces.
  959. for (const rel of findIgnoredEmbeddedRepos(repoDir, includeIgnored, prefix)) {
  960. embeddedRoots?.add(normalizePath(prefix + rel));
  961. collectGitFiles(path.join(repoDir, rel), prefix + rel, files, embeddedRoots, includeIgnored);
  962. }
  963. }
  964. /**
  965. * Get all files visible to git (tracked + untracked but not ignored).
  966. * Respects .gitignore at all levels (root, subdirectories) and descends into
  967. * embedded (nested, non-submodule) git repos. Returns null on failure
  968. * (non-git project) so callers can fall back to a filesystem walk.
  969. */
  970. function getGitVisibleFiles(rootDir: string): Set<string> | null {
  971. try {
  972. // Check if the project directory is gitignored by a parent repo.
  973. // When rootDir lives inside a parent git repo that ignores it,
  974. // `git ls-files` returns nothing — fall back to filesystem walk.
  975. const gitRoot = execFileSync(
  976. 'git',
  977. ['rev-parse', '--show-toplevel'],
  978. { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }
  979. ).trim();
  980. if (path.resolve(gitRoot) !== path.resolve(rootDir)) {
  981. try {
  982. // git check-ignore exits 0 if the path IS ignored, 1 if not
  983. execFileSync(
  984. 'git',
  985. ['check-ignore', '-q', path.resolve(rootDir)],
  986. { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }
  987. );
  988. // Directory is gitignored by parent repo — fall back to filesystem walk
  989. return null;
  990. } catch {
  991. // Not ignored — safe to use git ls-files
  992. }
  993. }
  994. const files = new Set<string>();
  995. const embeddedRoots = new Set<string>();
  996. collectGitFiles(rootDir, '', files, embeddedRoots, loadIncludeIgnoredMatcher(rootDir));
  997. // Apply built-in default ignores uniformly — to tracked files too, since
  998. // committing a dependency/build dir doesn't make it project code. A
  999. // `.gitignore` negation (e.g. `!vendor/`) is the explicit opt-in. (issue #407)
  1000. // Files inside an EMBEDDED repo are matched against that repo's own rules,
  1001. // not the parent's: the parent's .gitignore hides the child repo from git,
  1002. // not from the index. (#514)
  1003. const ig = buildScopeIgnore(rootDir, embeddedRoots);
  1004. const visible = new Set([...files].filter((f) => !ig.ignores(f)));
  1005. // Force-include first-party source the project whitelisted in
  1006. // `codegraph.json` `include`. These are gitignored, so `git ls-files` never
  1007. // listed them above — discover them directly off disk and add them. (The
  1008. // common SVN+Git dual-VCS case: source committed to SVN, gitignored out of
  1009. // Git, but still wanted in the graph.)
  1010. for (const f of collectIncludedFilesForRoot(rootDir)) visible.add(f);
  1011. return visible;
  1012. } catch {
  1013. return null;
  1014. }
  1015. }
  1016. /**
  1017. * Result of git-based change detection.
  1018. * Returns null when git is unavailable (non-git project or command failure),
  1019. * signaling the caller to fall back to full filesystem scan.
  1020. */
  1021. interface GitChanges {
  1022. modified: string[]; // M, MM, AM — files to re-hash + re-index
  1023. added: string[]; // ?? — new untracked files to index
  1024. deleted: string[]; // D — files to remove from DB
  1025. }
  1026. /**
  1027. * Use `git status` to detect changed files instead of scanning every file.
  1028. * Returns null on failure so callers fall back to full scan.
  1029. *
  1030. * Recurses into embedded repos — the untracked kind (#193: the parent's status
  1031. * collapses them to an opaque `?? subdir/` entry) always, and the gitignored
  1032. * kind (#514: they never appear in the parent's status at all) only for
  1033. * directories opted in via `codegraph.json` `includeIgnored` (#622, #699) —
  1034. * running `git status` inside each, so changes in a multi-repo workspace sync
  1035. * without a full rescan. By default a gitignored dir is left alone, matching the
  1036. * full-index scan (#970, #976). Deleting an ENTIRE embedded repo dir is the one
  1037. * case this cannot see (the child status that would report the deletions is gone
  1038. * with it); a full `codegraph index` reconciles that.
  1039. */
  1040. function getGitChangedFiles(rootDir: string): GitChanges | null {
  1041. try {
  1042. const changes: GitChanges = { modified: [], added: [], deleted: [] };
  1043. // Custom extension → language overrides from the project's codegraph.json,
  1044. // so change detection sees the same custom-extension files the full index does.
  1045. const overrides = loadExtensionOverrides(rootDir);
  1046. collectGitStatus(rootDir, '', changes, overrides, loadIncludeIgnoredMatcher(rootDir), loadExcludeMatcher(rootDir));
  1047. return changes;
  1048. } catch {
  1049. return null;
  1050. }
  1051. }
  1052. function collectGitStatus(repoDir: string, prefix: string, out: GitChanges, overrides?: Record<string, Language>, includeIgnored: Ignore | null = null, exclude: Ignore | null = null): void {
  1053. const output = execFileSync(
  1054. 'git',
  1055. ['status', '--porcelain', '--no-renames'],
  1056. { cwd: repoDir, encoding: 'utf-8', timeout: 10000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }
  1057. );
  1058. // This repo's own ignore rules — built-in defaults (#407) plus its .gitignore.
  1059. // Change detection must exclude the SAME files the full index does, but git
  1060. // status hides neither: it ignores nothing for *tracked* paths, and the
  1061. // built-in defaults aren't gitignore at all. Without this filter a committed
  1062. // vendor/ dir, or a tracked file under a .gitignored dir, surfaces here as a
  1063. // change — so `codegraph status` (which reads getChangedFiles) reports a
  1064. // pending edit the full index never tracks and `sync` never clears. Matching
  1065. // repo-relative `rel` at each recursion level mirrors getGitVisibleFiles'
  1066. // ScopeIgnore: every embedded repo is judged by ITS OWN rules, never the
  1067. // parent's. (#766)
  1068. const ig = buildDefaultIgnore(repoDir);
  1069. const untrackedDirs: string[] = [];
  1070. for (const line of output.split('\n')) {
  1071. if (line.length < 4) continue; // Minimum: "XY file"
  1072. const statusCode = line.substring(0, 2);
  1073. const rel = normalizePath(line.substring(3));
  1074. // Untracked directory entries (trailing slash) may hide an embedded repo —
  1075. // collect for the recursion below instead of treating as a file.
  1076. if (statusCode === '??' && rel.endsWith('/')) {
  1077. untrackedDirs.push(rel);
  1078. continue;
  1079. }
  1080. const filePath = normalizePath(prefix + rel);
  1081. if (!isSourceFile(filePath, overrides)) continue;
  1082. if (statusCode.includes('D')) {
  1083. // Deletions stay unfiltered: getChangedFiles acts on one only when the
  1084. // path is already tracked in the DB, where removal is always correct — and
  1085. // that lets a newly-excluded dir's stale rows clean themselves up. (#766)
  1086. out.deleted.push(filePath);
  1087. continue;
  1088. }
  1089. // Added (`??`) / modified files inside an excluded dir must not enter the
  1090. // index — match against the repo-relative path, same as the full scan. (#766)
  1091. if (ig.ignores(rel)) continue;
  1092. // User `codegraph.json` `exclude` (#999) is project-root-relative, so it's
  1093. // matched against the full path — sync must not re-add a tracked file the
  1094. // full index now keeps out. Deletions above stay unfiltered so a file that
  1095. // WAS indexed before an exclude was added still cleans itself out.
  1096. if (exclude && exclude.ignores(filePath)) continue;
  1097. if (statusCode === '??') {
  1098. out.added.push(filePath);
  1099. } else {
  1100. // M, MM, AM, A (staged), etc. — treat as modified
  1101. out.modified.push(filePath);
  1102. }
  1103. }
  1104. // Recurse embedded repos found under untracked dirs (at the dir itself or
  1105. // nested deeper). Gitignored dirs are walked only for the directories the
  1106. // project opted in via `includeIgnored`; by default `.gitignore` is respected
  1107. // and they are left alone (#970, #976), mirroring the full-index scan.
  1108. for (const rel of untrackedDirs) {
  1109. for (const repoRel of findNestedGitRepos(path.join(repoDir, rel), rel)) {
  1110. collectGitStatus(path.join(repoDir, repoRel), prefix + repoRel, out, overrides, includeIgnored, exclude);
  1111. }
  1112. }
  1113. for (const rel of findIgnoredEmbeddedRepos(repoDir, includeIgnored, prefix)) {
  1114. collectGitStatus(path.join(repoDir, rel), prefix + rel, out, overrides, includeIgnored, exclude);
  1115. }
  1116. }
  1117. /**
  1118. * Recursively scan a directory for source files.
  1119. *
  1120. * In git repos, uses `git ls-files` (inherently respects .gitignore at all
  1121. * levels), then keeps files with a supported source extension. For non-git
  1122. * projects, falls back to a filesystem walk that parses .gitignore itself.
  1123. */
  1124. export function scanDirectory(
  1125. rootDir: string,
  1126. onProgress?: (current: number, file: string) => void
  1127. ): string[] {
  1128. // Custom extension → language overrides from the project's codegraph.json.
  1129. const overrides = loadExtensionOverrides(rootDir);
  1130. // Fast path: use git to get all visible files (respects .gitignore everywhere)
  1131. const gitFiles = getGitVisibleFiles(rootDir);
  1132. if (gitFiles) {
  1133. const files: string[] = [];
  1134. let count = 0;
  1135. for (const filePath of gitFiles) {
  1136. if (isSourceFile(filePath, overrides)) {
  1137. files.push(filePath);
  1138. count++;
  1139. onProgress?.(count, filePath);
  1140. }
  1141. }
  1142. return files;
  1143. }
  1144. // Fallback: walk filesystem for non-git projects
  1145. return scanDirectoryWalk(rootDir, onProgress);
  1146. }
  1147. /**
  1148. * Async variant of scanDirectory that yields to the event loop periodically,
  1149. * allowing worker threads to receive and render progress messages.
  1150. */
  1151. export async function scanDirectoryAsync(
  1152. rootDir: string,
  1153. onProgress?: (current: number, file: string) => void
  1154. ): Promise<string[]> {
  1155. // Custom extension → language overrides from the project's codegraph.json.
  1156. const overrides = loadExtensionOverrides(rootDir);
  1157. const gitFiles = getGitVisibleFiles(rootDir);
  1158. if (gitFiles) {
  1159. const files: string[] = [];
  1160. let count = 0;
  1161. for (const filePath of gitFiles) {
  1162. if (isSourceFile(filePath, overrides)) {
  1163. files.push(filePath);
  1164. count++;
  1165. onProgress?.(count, filePath);
  1166. // Yield every 100 files so worker threads can render progress
  1167. if (count % 100 === 0) {
  1168. await new Promise<void>(r => setImmediate(r));
  1169. }
  1170. }
  1171. }
  1172. return files;
  1173. }
  1174. return scanDirectoryWalk(rootDir, onProgress);
  1175. }
  1176. /**
  1177. * Filesystem walk fallback for non-git projects.
  1178. */
  1179. function scanDirectoryWalk(
  1180. rootDir: string,
  1181. onProgress?: (current: number, file: string) => void
  1182. ): string[] {
  1183. const files: string[] = [];
  1184. let count = 0;
  1185. const visitedDirs = new Set<string>();
  1186. // Custom extension → language overrides from the project's codegraph.json.
  1187. const overrides = loadExtensionOverrides(rootDir);
  1188. // A .gitignore matcher scoped to the directory that declared it. Patterns in
  1189. // a nested .gitignore are relative to that directory, so we keep the dir
  1190. // alongside the matcher and test paths relative to it — mirroring how git
  1191. // applies .gitignore files at every level.
  1192. interface ScopedIgnore {
  1193. dir: string;
  1194. ig: Ignore;
  1195. }
  1196. const loadIgnore = (dir: string): ScopedIgnore | null => {
  1197. const giPath = path.join(dir, '.gitignore');
  1198. if (!fs.existsSync(giPath)) return null;
  1199. // readGitignorePatterns is defensive: a non-UTF-8 (DLP-encrypted) or
  1200. // uncompilable .gitignore is skipped/filtered with a warning, never thrown
  1201. // (issue #682) — so the per-file `.ignores()` calls below can't crash.
  1202. const patterns = readGitignorePatterns(giPath);
  1203. return patterns ? { dir, ig: ignore().add(patterns) } : null;
  1204. };
  1205. const isIgnored = (fullPath: string, isDir: boolean, matchers: ScopedIgnore[]): boolean => {
  1206. for (const { dir, ig } of matchers) {
  1207. let rel = normalizePath(path.relative(dir, fullPath));
  1208. if (!rel || rel.startsWith('..')) continue; // not under this matcher's dir
  1209. if (isDir) rel += '/'; // dir-only rules (e.g. `build/`) only match with the slash
  1210. if (ig.ignores(rel)) return true;
  1211. }
  1212. return false;
  1213. };
  1214. function walk(dir: string, matchers: ScopedIgnore[]): void {
  1215. let realDir: string;
  1216. try {
  1217. realDir = fs.realpathSync(dir);
  1218. } catch {
  1219. logDebug('Skipping unresolvable directory', { dir });
  1220. return;
  1221. }
  1222. if (visitedDirs.has(realDir)) {
  1223. logDebug('Skipping already-visited directory (symlink cycle)', { dir, realDir });
  1224. return;
  1225. }
  1226. visitedDirs.add(realDir);
  1227. // This directory's own .gitignore (if present) applies to everything below it.
  1228. // The root's .gitignore is already merged into the seeded base matcher (so a
  1229. // negation there can override a built-in default), so skip it here.
  1230. const own = dir === rootDir ? null : loadIgnore(dir);
  1231. const active = own ? [...matchers, own] : matchers;
  1232. let entries: fs.Dirent[];
  1233. try {
  1234. entries = fs.readdirSync(dir, { withFileTypes: true });
  1235. } catch (error) {
  1236. logDebug('Skipping unreadable directory', { dir, error: String(error) });
  1237. return;
  1238. }
  1239. for (const entry of entries) {
  1240. // Never descend into git internals or any CodeGraph data directory
  1241. // (the active one or a sibling another environment created — #636).
  1242. if (entry.name === '.git' || isCodeGraphDataDir(entry.name)) continue;
  1243. const fullPath = path.join(dir, entry.name);
  1244. const relativePath = normalizePath(path.relative(rootDir, fullPath));
  1245. if (entry.isSymbolicLink()) {
  1246. try {
  1247. const realTarget = fs.realpathSync(fullPath);
  1248. const stat = fs.statSync(realTarget);
  1249. if (stat.isDirectory()) {
  1250. if (!isIgnored(fullPath, true, active)) {
  1251. walk(fullPath, active);
  1252. }
  1253. } else if (stat.isFile()) {
  1254. if (!isIgnored(fullPath, false, active) && isSourceFile(relativePath, overrides)) {
  1255. files.push(relativePath);
  1256. count++;
  1257. onProgress?.(count, relativePath);
  1258. }
  1259. }
  1260. } catch {
  1261. logDebug('Skipping broken symlink', { path: fullPath });
  1262. }
  1263. continue;
  1264. }
  1265. if (entry.isDirectory()) {
  1266. if (!isIgnored(fullPath, true, active)) {
  1267. walk(fullPath, active);
  1268. }
  1269. } else if (entry.isFile()) {
  1270. if (!isIgnored(fullPath, false, active) && isSourceFile(relativePath, overrides)) {
  1271. files.push(relativePath);
  1272. count++;
  1273. onProgress?.(count, relativePath);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. // Seed a base matcher with the built-in default ignores (merged with the root
  1279. // .gitignore so a negation can override). Nested .gitignores still layer per-dir.
  1280. const baseMatchers: ScopedIgnore[] = [{ dir: rootDir, ig: buildDefaultIgnore(rootDir) }];
  1281. // Project `codegraph.json` `exclude` patterns (#999), rooted at the project so
  1282. // `isIgnored` matches them against root-relative paths — same coverage the
  1283. // git path gets via ScopeIgnore, for non-git projects.
  1284. const exclude = loadExcludeMatcher(rootDir);
  1285. if (exclude) baseMatchers.push({ dir: rootDir, ig: exclude });
  1286. walk(rootDir, baseMatchers);
  1287. // Force-include first-party source whitelisted in `codegraph.json` `include`
  1288. // — the walk above honours `.gitignore`, so anything gitignored was dropped;
  1289. // add it back here (deduped). Mirrors the git path's union.
  1290. const included = collectIncludedFilesForRoot(rootDir);
  1291. if (included.size > 0) {
  1292. const seen = new Set(files);
  1293. for (const f of included) {
  1294. if (!seen.has(f)) {
  1295. files.push(f);
  1296. seen.add(f);
  1297. }
  1298. }
  1299. }
  1300. return files;
  1301. }
  1302. /**
  1303. * Resurrect a resolution edge that is about to be dropped (its target symbol
  1304. * was removed, renamed, or its whole file deleted) as the ORIGINAL unresolved
  1305. * reference that created it, read from the refName/refKind stamp
  1306. * `createEdges` writes into edge metadata. Inserted as status='pending', the
  1307. * ref is consumed by the same sync's resolution sweep: it rebinds to an
  1308. * alternative definition if one exists, or parks as status='failed' where the
  1309. * #1240 retry finds it if the symbol later reappears.
  1310. *
  1311. * Returns null — drop silently, the pre-#1240 behavior — for edges without a
  1312. * refName stamp (created before the stamp existed, or synthesized): rebuilding
  1313. * a ref from the target's plain node name would strip the receiver/qualifier
  1314. * context the original text carried (`h.greet` → `greet`) and could rebind
  1315. * somewhere a full re-index never would. Silent beats wrong.
  1316. */
  1317. function resurrectRefFromDroppedEdge(
  1318. e: Edge & { sourceFilePath: string; sourceLanguage: Language }
  1319. ): UnresolvedReference | null {
  1320. const refName = e.metadata?.refName;
  1321. if (typeof refName !== 'string' || refName.length === 0) return null;
  1322. const refKind = typeof e.metadata?.refKind === 'string' ? (e.metadata.refKind as ReferenceKind) : e.kind;
  1323. return {
  1324. fromNodeId: e.source,
  1325. referenceName: refName,
  1326. referenceKind: refKind,
  1327. line: e.line ?? 0,
  1328. column: e.column ?? 0,
  1329. filePath: e.sourceFilePath,
  1330. language: e.sourceLanguage,
  1331. };
  1332. }
  1333. /**
  1334. * Extraction orchestrator
  1335. */
  1336. export class ExtractionOrchestrator {
  1337. private rootDir: string;
  1338. private queries: QueryBuilder;
  1339. /**
  1340. * Names of frameworks detected for this project, populated by indexAll().
  1341. * Passed to extractFromSource so framework-specific extractors (route nodes,
  1342. * middleware, etc.) run after the tree-sitter pass. Cleared if detection
  1343. * hasn't run yet so single-file re-index paths can detect on the spot.
  1344. */
  1345. private detectedFrameworkNames: string[] | null = null;
  1346. constructor(rootDir: string, queries: QueryBuilder) {
  1347. this.rootDir = rootDir;
  1348. this.queries = queries;
  1349. }
  1350. /**
  1351. * Build a filesystem-backed ResolutionContext sufficient for framework
  1352. * detection. Graph-query methods (getNodesByName etc.) return empty because
  1353. * the DB hasn't been populated yet, but detect() only uses readFile,
  1354. * fileExists, and getAllFiles, so that's fine.
  1355. */
  1356. private buildDetectionContext(files: string[]): ResolutionContext {
  1357. const rootDir = this.rootDir;
  1358. return {
  1359. getNodesInFile: () => [],
  1360. getNodesByName: () => [],
  1361. getNodesByQualifiedName: () => [],
  1362. getNodesByKind: () => [],
  1363. getNodesByLowerName: () => [],
  1364. getImportMappings: () => [],
  1365. getAllFiles: () => files,
  1366. getProjectRoot: () => rootDir,
  1367. fileExists: (relativePath: string) => {
  1368. const full = validatePathWithinRoot(rootDir, relativePath);
  1369. if (!full) return false;
  1370. try {
  1371. return fs.existsSync(full);
  1372. } catch {
  1373. return false;
  1374. }
  1375. },
  1376. readFile: (relativePath: string) => {
  1377. const full = validatePathWithinRoot(rootDir, relativePath);
  1378. if (!full) return null;
  1379. try {
  1380. return fs.readFileSync(full, 'utf-8');
  1381. } catch {
  1382. return null;
  1383. }
  1384. },
  1385. // Monorepo support — needed by framework detect()s that probe
  1386. // subpackage manifests (e.g. fabric-view looking at
  1387. // packages/<sub>/package.json when the root manifest is just a
  1388. // workspace declaration). Matches the resolver-context shape.
  1389. listDirectories: (relativePath: string) => {
  1390. const target =
  1391. relativePath === '.' || relativePath === ''
  1392. ? rootDir
  1393. : path.join(rootDir, relativePath);
  1394. try {
  1395. return fs
  1396. .readdirSync(target, { withFileTypes: true })
  1397. .filter((entry) => entry.isDirectory())
  1398. .map((entry) => entry.name);
  1399. } catch {
  1400. return [];
  1401. }
  1402. },
  1403. };
  1404. }
  1405. /**
  1406. * Detect frameworks on demand using the current scanned files (or a fresh
  1407. * scan if none are provided). Cached on the orchestrator so repeat calls
  1408. * inside a single run don't re-scan.
  1409. */
  1410. private ensureDetectedFrameworks(files?: string[]): string[] {
  1411. if (this.detectedFrameworkNames !== null) return this.detectedFrameworkNames;
  1412. const fileList = files ?? scanDirectory(this.rootDir);
  1413. const context = this.buildDetectionContext(fileList);
  1414. this.detectedFrameworkNames = detectFrameworks(context).map((r) => r.name);
  1415. return this.detectedFrameworkNames;
  1416. }
  1417. /**
  1418. * Index all files in the project
  1419. */
  1420. async indexAll(
  1421. onProgress?: (progress: IndexProgress) => void,
  1422. signal?: AbortSignal,
  1423. verbose?: boolean,
  1424. // Writer-side backstop for deferred WAL checkpointing (#1231): returns
  1425. // null in the normal case, or a promise to await (at this safe,
  1426. // between-transactions boundary) when the WAL has outrun the off-thread
  1427. // checkpointer past its hard cap. See db/wal-valve.ts.
  1428. walBackpressure?: () => Promise<void> | null,
  1429. // Fresh-DB store offload (perf): when set, per-file store bundles are
  1430. // applied by a dedicated writer thread instead of the main thread. Only
  1431. // passed for a COMPLETELY fresh database, where the main thread performs
  1432. // no reads/writes during the parse loop, so one writer applying bundles
  1433. // in file order preserves the #1015 determinism exactly.
  1434. storeWriterOpts?: { dbPath: string; fastInit: boolean } | null
  1435. ): Promise<IndexResult> {
  1436. const tGrammar = Date.now();
  1437. await initGrammars();
  1438. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] grammar-init: ${Date.now() - tGrammar}ms`);
  1439. const startTime = Date.now();
  1440. const errors: ExtractionError[] = [];
  1441. let filesIndexed = 0;
  1442. let filesSkipped = 0;
  1443. let filesErrored = 0;
  1444. let totalNodes = 0;
  1445. let totalEdges = 0;
  1446. // Custom extension → language overrides from the project's codegraph.json.
  1447. // Threaded into language detection so custom-extension files load the right
  1448. // grammar and store under the mapped language.
  1449. const overrides = loadExtensionOverrides(this.rootDir);
  1450. const log = verbose
  1451. ? (msg: string) => { console.log(`[worker] ${msg}`); }
  1452. : (_msg: string) => {};
  1453. // Phase 1: Scan for files
  1454. onProgress?.({
  1455. phase: 'scanning',
  1456. current: 0,
  1457. total: 0,
  1458. });
  1459. // Phase attribution to stderr (same opt-in as the synthesis timings):
  1460. // early-run 5-10s single stalls were observed on 95k-file repos but never
  1461. // attributed — these labels settle scan vs framework-detect vs grammars.
  1462. const tScan = Date.now();
  1463. const files = await scanDirectoryAsync(this.rootDir, (current, file) => {
  1464. onProgress?.({
  1465. phase: 'scanning',
  1466. current,
  1467. total: 0,
  1468. currentFile: file,
  1469. });
  1470. });
  1471. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] scan: ${Date.now() - tScan}ms (${files.length} files)`);
  1472. // Detect frameworks once per indexAll run using the scanned file list.
  1473. // Names are passed to each parse call so framework-specific extractors
  1474. // (route nodes, middleware, etc.) run after the tree-sitter pass.
  1475. // Framework detection is reset each run so adding e.g. requirements.txt
  1476. // between runs is picked up without restarting the process.
  1477. this.detectedFrameworkNames = null;
  1478. const tFw = Date.now();
  1479. const frameworkNames = this.ensureDetectedFrameworks(files);
  1480. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] framework-detect: ${Date.now() - tFw}ms`);
  1481. if (signal?.aborted) {
  1482. return {
  1483. success: false,
  1484. filesIndexed: 0,
  1485. filesSkipped: 0,
  1486. filesErrored: 0,
  1487. nodesCreated: 0,
  1488. edgesCreated: 0,
  1489. errors: [{ message: 'Aborted', severity: 'error' }],
  1490. durationMs: Date.now() - startTime,
  1491. };
  1492. }
  1493. // Phase 2: Parse files in a worker thread (keeps main thread unblocked for UI)
  1494. const total = files.length;
  1495. let processed = 0;
  1496. // Emit parsing phase immediately so the progress bar appears during worker setup.
  1497. // The yield lets the shimmer worker flush the phase transition to stdout before
  1498. // the main thread starts synchronous grammar detection work.
  1499. onProgress?.({
  1500. phase: 'parsing',
  1501. current: 0,
  1502. total,
  1503. });
  1504. await new Promise(resolve => setImmediate(resolve));
  1505. // Detect needed languages and load grammars in the parse worker
  1506. const neededLanguages = [...new Set(files.map((f) => detectLanguage(f, undefined, overrides)))];
  1507. // .h files default to 'c' but may be C++ — ensure cpp grammar is loaded when c is needed
  1508. if (neededLanguages.includes('c') && !neededLanguages.includes('cpp')) {
  1509. neededLanguages.push('cpp');
  1510. }
  1511. // Parse files on a pool of worker threads (keeps the main thread free for UI
  1512. // and uses every core). Falls back to in-process parsing when the compiled
  1513. // worker is unavailable (e.g. running from source in tests).
  1514. const parseWorkerPath = path.join(__dirname, 'parse-worker.js');
  1515. const useWorker = fs.existsSync(parseWorkerPath);
  1516. let pool: ParseWorkerPool | null = null;
  1517. if (useWorker) {
  1518. // CODEGRAPH_PARSE_WORKERS: explicit worker count; 1 = the old single-worker
  1519. // behaviour (the conservative rollback). Unset → clamp(cores-1, 1, 8),
  1520. // with cores from availableParallelism — cpuset/affinity-honest, where
  1521. // os.cpus() enumerates the host's CPUs and spawned 8 wasm workers (and
  1522. // their grammar heaps) inside a 2-CPU container for zero extra
  1523. // throughput (§7a.1). Floored so a 2-core box still gets 2 workers:
  1524. // parse is worker-side CPU, and 1 worker measured 34% slower than the
  1525. // old oversubscribed pool on the kernel-scale 2-cpuset envelope
  1526. // (493s vs 369s) — main + store-worker don't fill the second core.
  1527. const poolSize = resolveParsePoolSize(process.env.CODEGRAPH_PARSE_WORKERS, Math.max(3, os.availableParallelism()));
  1528. // Read each needed grammar's WASM ONCE here and hand the bytes to every
  1529. // worker, so spawns/respawns load grammars from memory instead of
  1530. // re-reading them from disk (#1231: on an HDD, respawn re-reads amplify
  1531. // the very I/O contention that caused the respawn).
  1532. const grammarBuffers = await readGrammarWasmBytes(neededLanguages);
  1533. pool = new ParseWorkerPool({
  1534. languages: neededLanguages,
  1535. size: poolSize,
  1536. workerScriptPath: parseWorkerPath,
  1537. recycleInterval: WORKER_RECYCLE_INTERVAL,
  1538. parseTimeoutMs: PARSE_TIMEOUT_MS,
  1539. log,
  1540. grammarBuffers,
  1541. });
  1542. log(`Parse worker pool: ${poolSize} worker(s)`);
  1543. // Bulk index: every core will be needed — spawn the whole pool now so
  1544. // worker boot overlaps the first read batches instead of trickling in
  1545. // behind queue-pressure growth.
  1546. pool.prewarm();
  1547. } else {
  1548. // In-process fallback: load grammars locally and parse on the main thread.
  1549. await loadGrammarsForLanguages(neededLanguages);
  1550. }
  1551. // Dedicated store writer thread (fresh DB only — see the parameter doc).
  1552. // Same availability rule as the parse pool: needs the compiled worker
  1553. // (absent when running from source in tests → main-thread fallback).
  1554. const storeWorkerPath = path.join(__dirname, 'store-worker.js');
  1555. let storeWriter: StoreWriter | null = null;
  1556. if (
  1557. storeWriterOpts &&
  1558. process.env.CODEGRAPH_NO_STORE_WORKER !== '1' &&
  1559. fs.existsSync(storeWorkerPath)
  1560. ) {
  1561. // Deliberately NOT awaiting ready(): worker_threads delivers messages in
  1562. // order, so bundles posted while the worker is still booting queue
  1563. // behind 'open'. A boot failure surfaces at the first drain() — same
  1564. // propagation point as a store error.
  1565. storeWriter = new StoreWriter(storeWorkerPath, storeWriterOpts.dbPath, storeWriterOpts.fastInit);
  1566. log('Store writer thread active');
  1567. }
  1568. /** Queue-depth bound for un-acked bundles (bundles hold whole node/edge arrays). */
  1569. const STORE_WRITER_WINDOW = 64;
  1570. /**
  1571. * Parse one file: on the pool when available (the promise REJECTS on a worker
  1572. * crash/timeout — the caller records it and the retry pass re-attempts), or
  1573. * in-process synchronously as the no-worker fallback. The language is resolved
  1574. * here on the main thread, where the codegraph.json overrides are loaded.
  1575. */
  1576. const parseFile = (filePath: string, content: string): Promise<ExtractionResult> => {
  1577. const language = detectLanguage(filePath, content, overrides);
  1578. if (!pool) return Promise.resolve(extractFromSource(filePath, content, language, frameworkNames));
  1579. return pool.requestParse({ filePath, content, language, frameworkNames });
  1580. };
  1581. // --- Bounded rolling-window dispatch, ordered commit ---
  1582. // Reads stay batched/parallel; parses run concurrently across the pool; the
  1583. // SQLite store stays on the main thread (it isn't thread-safe). Crucially we
  1584. // COMMIT results in original file order, not parse-completion order: the
  1585. // resolution phase (run after indexing) resolves an ambiguous reference to one
  1586. // of several same-named candidates by the nodes' DB insertion order, so a
  1587. // stable commit order keeps the resulting graph deterministic — byte-identical
  1588. // to the single-worker path — instead of drifting with parse timing. The
  1589. // `completed` buffer holds at most ~windowSize out-of-order results, so memory
  1590. // stays bounded.
  1591. const windowSize = pool ? Math.max(4, pool.size * 2) : 1;
  1592. const inFlight = new Set<Promise<void>>();
  1593. const completed = new Map<number,
  1594. | { ok: true; filePath: string; content: string; stats: fs.Stats; result: ExtractionResult }
  1595. | { ok: false; filePath: string; err: unknown }>();
  1596. let nextSeq = 0; // file-order sequence assigned at dispatch
  1597. let nextToStore = 0; // cursor: next sequence to commit
  1598. let aborted = false;
  1599. // Yielder for the in-order commit path: a single giant generated file's
  1600. // store is otherwise one unyielding multi-second transaction span on the
  1601. // main thread (5–14s single stalls measured on llvm-project), starving
  1602. // the #850 watchdog heartbeat on slow hardware.
  1603. const commitYield = createYielder();
  1604. const storeResult = async (filePath: string, content: string, stats: fs.Stats, result: ExtractionResult): Promise<void> => {
  1605. processed++;
  1606. // WAL hard-cap backstop: between files (never mid-transaction), pause
  1607. // the store until the off-thread checkpoint catches up. Resolves to
  1608. // null in the normal case — a single size check, no cost.
  1609. const bp = walBackpressure?.();
  1610. if (bp) await bp;
  1611. // Kernel deferred-decode results carry table sizes in kernelCounts
  1612. // (their object arrays are empty — decode happens at the store).
  1613. const nodeCount = result.kernelCounts?.nodes ?? result.nodes.length;
  1614. const edgeCount = result.kernelCounts?.edges ?? result.edges.length;
  1615. // Store: on the writer thread when active (fresh DB — bundles applied
  1616. // in the same file order this chain dispatches them), else on the main
  1617. // thread (SQLite connections are per-thread).
  1618. if (nodeCount > 0 || result.errors.length === 0) {
  1619. const language = detectLanguage(filePath, content, overrides);
  1620. if (storeWriter) {
  1621. if (result.kernelBuffers) {
  1622. // Buffers go to the writer as-is; the worker decodes + finalizes.
  1623. // The main thread's only per-file work stays O(1) + the content hash.
  1624. storeWriter.send({
  1625. kernel: true,
  1626. filePath,
  1627. language,
  1628. buffers: result.kernelBuffers,
  1629. file: this.buildFileRecord(filePath, content, language, stats, nodeCount, result.errors),
  1630. });
  1631. } else {
  1632. storeWriter.send(this.buildFreshStoreBundle(filePath, content, language, stats, result));
  1633. }
  1634. await storeWriter.waitBelow(STORE_WRITER_WINDOW);
  1635. } else {
  1636. const materialized = materializeKernelResult(result, filePath, language);
  1637. await this.storeExtractionResult(filePath, content, language, stats, materialized, commitYield);
  1638. }
  1639. }
  1640. if (result.errors.length > 0) {
  1641. for (const err of result.errors) {
  1642. if (!err.filePath) err.filePath = filePath;
  1643. }
  1644. errors.push(...result.errors);
  1645. }
  1646. if (nodeCount > 0) {
  1647. filesIndexed++;
  1648. totalNodes += nodeCount;
  1649. totalEdges += edgeCount;
  1650. } else if (result.errors.some((e) => e.severity === 'error')) {
  1651. filesErrored++;
  1652. } else {
  1653. // Files with no symbols but no errors (yaml, twig, properties) are
  1654. // tracked at the file level — count them as indexed so the CLI doesn't
  1655. // misleadingly report "No files found to index".
  1656. const lang = detectLanguage(filePath, content, overrides);
  1657. if (isFileLevelOnlyLanguage(lang)) {
  1658. filesIndexed++;
  1659. } else {
  1660. filesSkipped++;
  1661. }
  1662. }
  1663. onProgress?.({ phase: 'parsing', current: processed, total, currentFile: filePath });
  1664. };
  1665. const recordParseFailure = (filePath: string, err: unknown): void => {
  1666. processed++;
  1667. filesErrored++;
  1668. errors.push({
  1669. message: err instanceof Error ? err.message : String(err),
  1670. filePath,
  1671. severity: 'error',
  1672. code: 'parse_error',
  1673. });
  1674. onProgress?.({ phase: 'parsing', current: processed, total });
  1675. };
  1676. // Commit buffered parses to the DB in file order, advancing the cursor over
  1677. // contiguous completed results. Runs after each parse settles (and once more
  1678. // after the drain). storeResult is now async (it yields between chunked
  1679. // inserts), so commits are SERIALIZED on a promise chain — concurrent parse
  1680. // completions append to the chain instead of interleaving mid-store, which
  1681. // preserves both the file-order commit invariant (#1015: resolution
  1682. // disambiguates same-named candidates by insertion order) and the
  1683. // single-writer discipline for SQLite. Errors are recorded and re-thrown
  1684. // at the drain, matching the old synchronous propagation.
  1685. let flushChain: Promise<void> = Promise.resolve();
  1686. let flushError: unknown = null;
  1687. const flushOrdered = (): Promise<void> => {
  1688. flushChain = flushChain.then(async () => {
  1689. if (aborted || flushError) return;
  1690. try {
  1691. while (completed.has(nextToStore)) {
  1692. const item = completed.get(nextToStore)!;
  1693. completed.delete(nextToStore);
  1694. nextToStore++;
  1695. if (item.ok) await storeResult(item.filePath, item.content, item.stats, item.result);
  1696. else recordParseFailure(item.filePath, item.err);
  1697. }
  1698. } catch (err) {
  1699. flushError = err;
  1700. }
  1701. });
  1702. return flushChain;
  1703. };
  1704. // Dispatch one file's parse (parses run concurrently across the pool), tagged
  1705. // with its file-order sequence so flushOrdered commits results in order. The
  1706. // backpressure below bounds how far parsing runs ahead of the in-order commit.
  1707. const feed = async (filePath: string, content: string, stats: fs.Stats): Promise<void> => {
  1708. const seq = nextSeq++;
  1709. const p = (async () => {
  1710. try {
  1711. const result = await parseFile(filePath, content);
  1712. completed.set(seq, { ok: true, filePath, content, stats, result });
  1713. } catch (parseErr) {
  1714. completed.set(seq, { ok: false, filePath, err: parseErr });
  1715. }
  1716. flushOrdered();
  1717. })();
  1718. const tracked = p.finally(() => { inFlight.delete(tracked); });
  1719. inFlight.add(tracked);
  1720. // Backpressure on the dispatched-but-not-yet-committed count (in-flight +
  1721. // buffered), not just in-flight: a slow file sitting at the commit cursor
  1722. // lets later parses finish and buffer, which would otherwise grow without
  1723. // bound. Wait for parses to settle (each may advance the cursor) until the
  1724. // window has room. When nothing is in flight but the window is still full,
  1725. // the async commit chain is what's behind — await it so the cursor
  1726. // advances (buffered items hold whole file contents, so this bound is
  1727. // load-bearing for memory).
  1728. while (nextSeq - nextToStore >= windowSize) {
  1729. if (inFlight.size > 0) await Promise.race(inFlight);
  1730. else await flushOrdered();
  1731. }
  1732. };
  1733. const tParseLoop = Date.now();
  1734. for (let i = 0; i < files.length; i += FILE_IO_BATCH_SIZE) {
  1735. if (signal?.aborted) { aborted = true; break; }
  1736. const batch = files.slice(i, i + FILE_IO_BATCH_SIZE);
  1737. // Read files in parallel (with path validation before any I/O)
  1738. const fileContents = await Promise.all(
  1739. batch.map(async (fp) => {
  1740. try {
  1741. // Indexing read: follow in-root symlinks the directory walk already
  1742. // descended into (the `../` guard still applies) so files reached
  1743. // via an in-root symlink-to-outside still index (#935).
  1744. const fullPath = validatePathWithinRoot(this.rootDir, fp, { allowSymlinkEscape: true });
  1745. if (!fullPath) {
  1746. logWarn('Path traversal blocked in batch reader', { filePath: fp });
  1747. return { filePath: fp, content: null as string | null, stats: null as fs.Stats | null, error: new Error('Path traversal blocked') };
  1748. }
  1749. const content = await fsp.readFile(fullPath, 'utf-8');
  1750. const stats = await fsp.stat(fullPath);
  1751. return { filePath: fp, content, stats, error: null as Error | null };
  1752. } catch (err) {
  1753. return { filePath: fp, content: null as string | null, stats: null as fs.Stats | null, error: err as Error };
  1754. }
  1755. })
  1756. );
  1757. // Dispatch each readable file into the bounded parse window; the window
  1758. // stores results on the main thread as they arrive.
  1759. for (const { filePath, content, stats, error } of fileContents) {
  1760. if (signal?.aborted) { aborted = true; break; }
  1761. if (error || content === null || stats === null) {
  1762. processed++;
  1763. filesErrored++;
  1764. errors.push({
  1765. message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
  1766. filePath,
  1767. severity: 'error',
  1768. code: 'read_error',
  1769. });
  1770. onProgress?.({ phase: 'parsing', current: processed, total });
  1771. continue;
  1772. }
  1773. // Honour MAX_FILE_SIZE. Without this check, vendored generated
  1774. // headers, minified bundles, and other multi-MB files get indexed,
  1775. // wasting WASM heap and the worker recycle budget on inputs with no
  1776. // useful symbols. The single-file extractFile path already enforces
  1777. // this; the bulk path used to silently skip the check.
  1778. if (stats.size > MAX_FILE_SIZE) {
  1779. processed++;
  1780. filesSkipped++;
  1781. errors.push({
  1782. message: `File exceeds max size (${stats.size} > ${MAX_FILE_SIZE})`,
  1783. filePath,
  1784. severity: 'warning',
  1785. code: 'size_exceeded',
  1786. });
  1787. onProgress?.({ phase: 'parsing', current: processed, total });
  1788. continue;
  1789. }
  1790. // Parse on the pool (main thread stays unblocked). Errors/timeouts are
  1791. // handled inside feed() → recordParseFailure, feeding the retry pass.
  1792. await feed(filePath, content, stats);
  1793. }
  1794. if (aborted) break;
  1795. }
  1796. // Drain parses still in flight (skip on abort — we tear down below instead),
  1797. // then commit any results the cursor hasn't reached yet.
  1798. if (!aborted) {
  1799. await Promise.all(inFlight);
  1800. await flushOrdered();
  1801. if (flushError) {
  1802. if (storeWriter) await storeWriter.close();
  1803. throw flushError;
  1804. }
  1805. // All bundles are posted; wait for the writer to apply them, then close
  1806. // its connection BEFORE any main-thread DB work below (retry pass,
  1807. // resolution) so exactly one connection writes at a time.
  1808. if (storeWriter) {
  1809. try {
  1810. await storeWriter.drain();
  1811. } finally {
  1812. await storeWriter.close();
  1813. storeWriter = null;
  1814. }
  1815. }
  1816. }
  1817. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] parse-loop: ${Date.now() - tParseLoop}ms`);
  1818. if (signal?.aborted || aborted) {
  1819. if (storeWriter) await storeWriter.close();
  1820. if (pool) await pool.destroy();
  1821. return {
  1822. success: false,
  1823. filesIndexed,
  1824. filesSkipped,
  1825. filesErrored,
  1826. filesDiscovered: total,
  1827. nodesCreated: totalNodes,
  1828. edgesCreated: totalEdges,
  1829. errors: [{ message: 'Aborted', severity: 'error' }, ...errors],
  1830. durationMs: Date.now() - startTime,
  1831. };
  1832. }
  1833. // Report 100% so the progress bar doesn't hang at 99%
  1834. onProgress?.({
  1835. phase: 'parsing',
  1836. current: total,
  1837. total,
  1838. });
  1839. // Yield so the shimmer worker's buffered stdout writes can flush.
  1840. // Worker thread stdout is proxied through the main thread's event loop,
  1841. // so synchronous work here blocks the animation from rendering.
  1842. await new Promise(resolve => setImmediate(resolve));
  1843. // Retry pass: files that failed due to WASM memory corruption may succeed
  1844. // on a fresh worker with a clean heap. Recycle before each attempt so
  1845. // every file gets the absolute cleanest WASM state possible. Timeouts are
  1846. // retried too (#1231): most are main-thread-stall artifacts, not slow
  1847. // parses, and this pass parses one file at a time with the store strictly
  1848. // after each parse resolves, so the stall window can't recur here.
  1849. const retryableErrors = errors.filter(
  1850. (e) => e.code === 'parse_error' && e.filePath &&
  1851. (e.message.includes('Worker exited') ||
  1852. e.message.includes('memory access out of bounds') ||
  1853. e.message.includes('timed out'))
  1854. );
  1855. if (retryableErrors.length > 0 && pool) {
  1856. log(`Retrying ${retryableErrors.length} files that failed due to WASM memory errors or timeouts...`);
  1857. // Fresh WASM heaps for the retry phase. A retry that still crashes its
  1858. // worker makes the pool respawn it, so later retries keep landing on clean
  1859. // workers too.
  1860. pool.recycleAll();
  1861. const stillFailing: typeof retryableErrors = [];
  1862. for (const errEntry of retryableErrors) {
  1863. const filePath = errEntry.filePath!;
  1864. if (signal?.aborted) break;
  1865. let content: string;
  1866. try {
  1867. const fullPath = validatePathWithinRoot(this.rootDir, filePath);
  1868. if (!fullPath) continue;
  1869. content = await fsp.readFile(fullPath, 'utf-8');
  1870. } catch {
  1871. continue;
  1872. }
  1873. let result: ExtractionResult;
  1874. try {
  1875. result = await parseFile(filePath, content);
  1876. } catch {
  1877. stillFailing.push(errEntry);
  1878. continue;
  1879. }
  1880. if (result.nodes.length > 0 || result.errors.length === 0) {
  1881. const language = detectLanguage(filePath, content, overrides);
  1882. const stats = await fsp.stat(path.join(this.rootDir, filePath));
  1883. await this.storeExtractionResult(filePath, content, language, stats, result, commitYield);
  1884. const idx = errors.indexOf(errEntry);
  1885. if (idx >= 0) errors.splice(idx, 1);
  1886. filesErrored--;
  1887. filesIndexed++;
  1888. totalNodes += result.nodes.length;
  1889. totalEdges += result.edges.length;
  1890. log(`Retry OK: ${filePath} (${result.nodes.length} nodes)`);
  1891. }
  1892. }
  1893. // Last resort: for files that still crash on a clean worker, strip
  1894. // comment-only lines to reduce WASM memory pressure. Many compiler
  1895. // test files are 90%+ comments (CHECK directives) that don't contribute
  1896. // code nodes but consume parser memory.
  1897. if (stillFailing.length > 0) {
  1898. log(`${stillFailing.length} files still failing — retrying with comments stripped...`);
  1899. pool.recycleAll();
  1900. for (const errEntry of stillFailing) {
  1901. const filePath = errEntry.filePath!;
  1902. if (signal?.aborted) break;
  1903. let fullContent: string;
  1904. try {
  1905. const fullPath = validatePathWithinRoot(this.rootDir, filePath);
  1906. if (!fullPath) continue;
  1907. fullContent = await fsp.readFile(fullPath, 'utf-8');
  1908. } catch {
  1909. continue;
  1910. }
  1911. // Strip lines that are entirely comments (preserving line numbers
  1912. // by replacing with empty lines so node positions stay correct)
  1913. const stripped = fullContent
  1914. .split('\n')
  1915. .map(line => /^\s*\/\//.test(line) ? '' : line)
  1916. .join('\n');
  1917. let result: ExtractionResult;
  1918. try {
  1919. result = await parseFile(filePath, stripped);
  1920. } catch {
  1921. continue;
  1922. }
  1923. if (result.nodes.length > 0 || result.errors.length === 0) {
  1924. const language = detectLanguage(filePath, fullContent, overrides);
  1925. const stats = await fsp.stat(path.join(this.rootDir, filePath));
  1926. await this.storeExtractionResult(filePath, fullContent, language, stats, result, commitYield);
  1927. const idx = errors.indexOf(errEntry);
  1928. if (idx >= 0) errors.splice(idx, 1);
  1929. filesErrored--;
  1930. filesIndexed++;
  1931. totalNodes += result.nodes.length;
  1932. totalEdges += result.edges.length;
  1933. log(`Retry (stripped) OK: ${filePath} (${result.nodes.length} nodes)`);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. // Shut down the parse worker pool.
  1939. if (pool) await pool.destroy();
  1940. return {
  1941. success: filesIndexed > 0 || errors.filter((e) => e.severity === 'error').length === 0,
  1942. filesIndexed,
  1943. filesSkipped,
  1944. filesErrored,
  1945. filesDiscovered: total,
  1946. nodesCreated: totalNodes,
  1947. edgesCreated: totalEdges,
  1948. errors,
  1949. durationMs: Date.now() - startTime,
  1950. };
  1951. }
  1952. /**
  1953. * Index specific files
  1954. */
  1955. async indexFiles(filePaths: string[]): Promise<IndexResult> {
  1956. const startTime = Date.now();
  1957. const errors: ExtractionError[] = [];
  1958. let filesIndexed = 0;
  1959. let filesSkipped = 0;
  1960. let filesErrored = 0;
  1961. let totalNodes = 0;
  1962. let totalEdges = 0;
  1963. for (const filePath of filePaths) {
  1964. const result = await this.indexFile(filePath);
  1965. if (result.errors.length > 0) {
  1966. errors.push(...result.errors);
  1967. }
  1968. if (result.nodes.length > 0) {
  1969. filesIndexed++;
  1970. totalNodes += result.nodes.length;
  1971. totalEdges += result.edges.length;
  1972. } else if (result.errors.some((e) => e.severity === 'error')) {
  1973. filesErrored++;
  1974. } else {
  1975. const tracked = this.queries.getFileByPath(filePath);
  1976. if (tracked && isFileLevelOnlyLanguage(tracked.language)) {
  1977. filesIndexed++;
  1978. } else {
  1979. filesSkipped++;
  1980. }
  1981. }
  1982. }
  1983. return {
  1984. success: filesIndexed > 0 || errors.filter((e) => e.severity === 'error').length === 0,
  1985. filesIndexed,
  1986. filesSkipped,
  1987. filesErrored,
  1988. nodesCreated: totalNodes,
  1989. edgesCreated: totalEdges,
  1990. errors,
  1991. durationMs: Date.now() - startTime,
  1992. };
  1993. }
  1994. /**
  1995. * Index a single file
  1996. */
  1997. async indexFile(relativePath: string): Promise<ExtractionResult> {
  1998. // Indexing read: follow in-root symlinks (the `../` guard still applies), #935.
  1999. const fullPath = validatePathWithinRoot(this.rootDir, relativePath, { allowSymlinkEscape: true });
  2000. if (!fullPath) {
  2001. return {
  2002. nodes: [],
  2003. edges: [],
  2004. unresolvedReferences: [],
  2005. errors: [{ message: `Path traversal blocked: ${relativePath}`, filePath: relativePath, severity: 'error', code: 'path_traversal' }],
  2006. durationMs: 0,
  2007. };
  2008. }
  2009. // Read file content and stats
  2010. let content: string;
  2011. let stats: fs.Stats;
  2012. try {
  2013. stats = await fsp.stat(fullPath);
  2014. content = await fsp.readFile(fullPath, 'utf-8');
  2015. } catch (error) {
  2016. return {
  2017. nodes: [],
  2018. edges: [],
  2019. unresolvedReferences: [],
  2020. errors: [
  2021. {
  2022. message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
  2023. filePath: relativePath,
  2024. severity: 'error',
  2025. code: 'read_error',
  2026. },
  2027. ],
  2028. durationMs: 0,
  2029. };
  2030. }
  2031. return this.indexFileWithContent(relativePath, content, stats);
  2032. }
  2033. /**
  2034. * Index a single file with pre-read content and stats.
  2035. * Used by the parallel batch reader to avoid redundant file I/O.
  2036. */
  2037. async indexFileWithContent(
  2038. relativePath: string,
  2039. content: string,
  2040. stats: fs.Stats
  2041. ): Promise<ExtractionResult> {
  2042. // Prevent `../` traversal; follow in-root symlinks like the directory walk (#935).
  2043. const fullPath = validatePathWithinRoot(this.rootDir, relativePath, { allowSymlinkEscape: true });
  2044. if (!fullPath) {
  2045. logWarn('Path traversal blocked in indexFileWithContent', { relativePath });
  2046. return {
  2047. nodes: [],
  2048. edges: [],
  2049. unresolvedReferences: [],
  2050. errors: [{ message: 'Path traversal blocked', filePath: relativePath, severity: 'error', code: 'path_traversal' }],
  2051. durationMs: 0,
  2052. };
  2053. }
  2054. // Check file size
  2055. if (stats.size > MAX_FILE_SIZE) {
  2056. return {
  2057. nodes: [],
  2058. edges: [],
  2059. unresolvedReferences: [],
  2060. errors: [
  2061. {
  2062. message: `File exceeds max size (${stats.size} > ${MAX_FILE_SIZE})`,
  2063. filePath: relativePath,
  2064. severity: 'warning',
  2065. code: 'size_exceeded',
  2066. },
  2067. ],
  2068. durationMs: 0,
  2069. };
  2070. }
  2071. // Detect language (honoring the project's codegraph.json extension overrides)
  2072. const language = detectLanguage(relativePath, content, loadExtensionOverrides(this.rootDir));
  2073. if (!isLanguageSupported(language)) {
  2074. return {
  2075. nodes: [],
  2076. edges: [],
  2077. unresolvedReferences: [],
  2078. errors: [],
  2079. durationMs: 0,
  2080. };
  2081. }
  2082. // Extract from source. Use cached framework names if indexAll has run,
  2083. // otherwise detect on the spot so single-file re-index paths still emit
  2084. // route nodes / middleware / etc.
  2085. const frameworkNames = this.ensureDetectedFrameworks();
  2086. const result = extractFromSource(relativePath, content, language, frameworkNames);
  2087. // Store in database
  2088. if (result.nodes.length > 0 || result.errors.length === 0) {
  2089. await this.storeExtractionResult(relativePath, content, language, stats, result, createYielder());
  2090. }
  2091. return result;
  2092. }
  2093. /**
  2094. * Store extraction result in database
  2095. */
  2096. private async storeExtractionResult(
  2097. filePath: string,
  2098. content: string,
  2099. language: Language,
  2100. stats: fs.Stats,
  2101. result: ExtractionResult,
  2102. onYield?: MaybeYield
  2103. ): Promise<void> {
  2104. // Bulk inserts run in bounded sub-transactions with a yield between, so a
  2105. // giant generated file (tens of thousands of symbols) can't block the
  2106. // event loop — and the #850 watchdog heartbeat — for the whole store.
  2107. // The file was NEVER one atomic transaction (each insert call has its
  2108. // own), and the files-table record still lands last, so crash recovery
  2109. // is unchanged: a partially-stored file has no record and re-indexes.
  2110. const STORE_CHUNK = 2000;
  2111. const contentHash = hashContent(content);
  2112. // Check if file already exists and hasn't changed
  2113. const existingFile = this.queries.getFileByPath(filePath);
  2114. if (existingFile && existingFile.contentHash === contentHash) {
  2115. return; // No changes
  2116. }
  2117. // Snapshot incoming cross-file edges BEFORE deleting this file's nodes.
  2118. // `deleteFile` cascades to delete every edge whose source OR target is a
  2119. // node in this file (edges.FK ... ON DELETE CASCADE). Edges whose SOURCE is
  2120. // in this file are re-emitted by the extractor below, but edges whose SOURCE
  2121. // is in a *different* (unchanged) file are not — they would be silently
  2122. // dropped, which is issue #899: re-indexing a callee file severs `calls`/
  2123. // `references` edges from callers that import it via module-attribute
  2124. // access (`pkg.mod.fn(...)`).
  2125. //
  2126. // We snapshot the edge plus the target node's (name, kind) so we can
  2127. // re-resolve to the re-indexed target's NEW id. Node ids are
  2128. // `sha256(filePath:kind:name:line)`, so any line shift in the callee file
  2129. // (e.g. a docstring-only edit above the symbol) changes every target id and
  2130. // a naive re-insert by old id would silently drop every edge. Matching by
  2131. // (filePath, kind, name) is stable across line shifts; if the symbol was
  2132. // renamed/removed, no match is found and the edge stays dropped (correct).
  2133. const crossFileIncomingEdges = existingFile
  2134. ? this.queries.getCrossFileIncomingEdgesWithTarget(filePath)
  2135. : [];
  2136. // Delete existing data for this file
  2137. if (existingFile) {
  2138. this.queries.deleteFile(filePath);
  2139. }
  2140. // Filter out nodes with missing required fields before insertion.
  2141. // This prevents FK violations when edges reference nodes that would
  2142. // be silently skipped by insertNode() (see issue #42).
  2143. const validNodes = result.nodes.filter((n) => n.id && n.kind && n.name && n.filePath && n.language);
  2144. const insertedIds = new Set(validNodes.map((n) => n.id));
  2145. const validEdges = result.edges.filter(
  2146. (e) => insertedIds.has(e.source) && insertedIds.has(e.target)
  2147. );
  2148. const validRefs = result.unresolvedReferences
  2149. .filter((ref) => insertedIds.has(ref.fromNodeId))
  2150. .map((ref) => ({
  2151. ...ref,
  2152. filePath: ref.filePath ?? filePath,
  2153. language: ref.language ?? language,
  2154. }));
  2155. // Fast path for the common case (everything fits one chunk): the whole
  2156. // file — nodes, edges, refs, file record — lands in ONE transaction with
  2157. // no event-loop yields in between. Giant generated files keep the chunked
  2158. // + yielding path below so the #850 watchdog heartbeat stays serviced.
  2159. const fitsOneChunk =
  2160. validNodes.length <= STORE_CHUNK &&
  2161. validEdges.length <= STORE_CHUNK &&
  2162. validRefs.length <= STORE_CHUNK;
  2163. if (fitsOneChunk) {
  2164. // Snapshot/re-resolution of cross-file incoming edges (below) still runs
  2165. // for the sync path; on a fresh bulk index crossFileIncomingEdges is [].
  2166. this.queries.storeFileBundle({
  2167. nodes: validNodes,
  2168. edges: validEdges,
  2169. refs: validRefs,
  2170. file: {
  2171. path: filePath,
  2172. contentHash,
  2173. language,
  2174. size: stats.size,
  2175. modifiedAt: stats.mtimeMs,
  2176. indexedAt: Date.now(),
  2177. nodeCount: result.nodes.length,
  2178. errors: result.errors.length > 0 ? result.errors : undefined,
  2179. },
  2180. });
  2181. if (crossFileIncomingEdges.length > 0) {
  2182. this.reattachCrossFileEdges(crossFileIncomingEdges, validNodes);
  2183. }
  2184. return;
  2185. }
  2186. // Insert nodes (chunked — see STORE_CHUNK above)
  2187. for (let i = 0; i < validNodes.length; i += STORE_CHUNK) {
  2188. this.queries.insertNodes(validNodes.slice(i, i + STORE_CHUNK));
  2189. await onYield?.();
  2190. }
  2191. // Filter edges to only reference nodes that were actually inserted
  2192. if (validEdges.length > 0) {
  2193. for (let i = 0; i < validEdges.length; i += STORE_CHUNK) {
  2194. this.queries.insertEdges(validEdges.slice(i, i + STORE_CHUNK));
  2195. await onYield?.();
  2196. }
  2197. }
  2198. // Re-insert cross-file incoming edges snapshotted before the delete,
  2199. // re-resolving each edge's target to the re-indexed node's new id by
  2200. // (filePath, kind, name). Node ids include the source line, so any line
  2201. // shift in the callee file (e.g. a docstring-only edit above the symbol)
  2202. // changes every target id and a naive re-insert by old id would drop them
  2203. // all. `insertEdges` still filters to endpoints that exist. This closes
  2204. // the #899 edge-drop on `sync`.
  2205. //
  2206. // Edges whose callee (target) was renamed/removed during the re-index (no
  2207. // match in `newNodesByKindName`) are not silently dropped anymore: each is
  2208. // resurrected as its ORIGINAL unresolved ref (stamped on the edge as
  2209. // metadata.refName/refKind at creation) so the same sync's resolution
  2210. // sweep can rebind it to an alternative definition elsewhere, or park it
  2211. // as status='failed' to be retried when the symbol reappears — the
  2212. // removal-side counterpart of #1240. Edges without refName (built before
  2213. // the stamp existed, or synthesized) still drop silently: reconstructing
  2214. // a ref from the target's plain name would strip receiver/qualifier
  2215. // context and risk a rebind a full re-index would never make.
  2216. if (crossFileIncomingEdges.length > 0) {
  2217. this.reattachCrossFileEdges(crossFileIncomingEdges, validNodes);
  2218. }
  2219. // Insert unresolved references in batch with denormalized filePath/language
  2220. for (let i = 0; i < validRefs.length; i += STORE_CHUNK) {
  2221. this.queries.insertUnresolvedRefsBatch(validRefs.slice(i, i + STORE_CHUNK));
  2222. await onYield?.();
  2223. }
  2224. // Insert file record
  2225. const fileRecord: FileRecord = {
  2226. path: filePath,
  2227. contentHash,
  2228. language,
  2229. size: stats.size,
  2230. modifiedAt: stats.mtimeMs,
  2231. indexedAt: Date.now(),
  2232. nodeCount: result.nodes.length,
  2233. errors: result.errors.length > 0 ? result.errors : undefined,
  2234. };
  2235. this.queries.upsertFile(fileRecord);
  2236. }
  2237. /**
  2238. * Build one file's store bundle for the FRESH-DB path: no existing-file
  2239. * check, no cross-file edge snapshot (both are re-index concerns — a fresh
  2240. * database has neither). Filters mirror storeExtractionResult exactly.
  2241. */
  2242. /** The FileRecord for a fresh-index store (nodeCount is the PRE-filter count). */
  2243. private buildFileRecord(
  2244. filePath: string,
  2245. content: string,
  2246. language: Language,
  2247. stats: fs.Stats,
  2248. nodeCount: number,
  2249. resultErrors: ExtractionResult['errors']
  2250. ): FileRecord {
  2251. return {
  2252. path: filePath,
  2253. contentHash: hashContent(content),
  2254. language,
  2255. size: stats.size,
  2256. modifiedAt: stats.mtimeMs,
  2257. indexedAt: Date.now(),
  2258. nodeCount,
  2259. errors: resultErrors.length > 0 ? resultErrors : undefined,
  2260. };
  2261. }
  2262. private buildFreshStoreBundle(
  2263. filePath: string,
  2264. content: string,
  2265. language: Language,
  2266. stats: fs.Stats,
  2267. result: ExtractionResult
  2268. ): StoreBundle {
  2269. return finalizeStoreBundle(
  2270. result,
  2271. filePath,
  2272. language,
  2273. this.buildFileRecord(filePath, content, language, stats, result.nodes.length, result.errors)
  2274. );
  2275. }
  2276. /**
  2277. * Re-attach cross-file incoming edges snapshotted before a re-index delete
  2278. * (#899): re-resolve each edge's target to the re-indexed node's new id by
  2279. * (kind, name); targets that vanished are resurrected as their original
  2280. * unresolved ref (#1240's removal-side counterpart) when the edge carries
  2281. * its refName stamp.
  2282. */
  2283. private reattachCrossFileEdges(
  2284. crossFileIncomingEdges: Array<Edge & { targetKind: string; targetName: string; sourceFilePath: string; sourceLanguage: Language }>,
  2285. validNodes: Node[]
  2286. ): void {
  2287. const newNodesByKindName = new Map<string, string>();
  2288. for (const n of validNodes) {
  2289. newNodesByKindName.set(`${n.kind}\0${n.name}`, n.id);
  2290. }
  2291. const reinserted: Edge[] = [];
  2292. const resurrected: UnresolvedReference[] = [];
  2293. for (const e of crossFileIncomingEdges) {
  2294. const newTargetId = newNodesByKindName.get(`${e.targetKind}\0${e.targetName}`);
  2295. if (newTargetId) {
  2296. reinserted.push({ source: e.source, target: newTargetId, kind: e.kind, metadata: e.metadata, line: e.line, column: e.column, provenance: e.provenance });
  2297. } else {
  2298. const ref = resurrectRefFromDroppedEdge(e);
  2299. if (ref) resurrected.push(ref);
  2300. }
  2301. }
  2302. if (reinserted.length > 0) {
  2303. this.queries.insertEdges(reinserted);
  2304. }
  2305. if (resurrected.length > 0) {
  2306. this.queries.insertUnresolvedRefsBatch(resurrected);
  2307. }
  2308. }
  2309. /**
  2310. * Sync the index with the current file state.
  2311. *
  2312. * Change detection is filesystem-based, never git: a (size, mtime) stat
  2313. * pre-filter skips unchanged files, then a content-hash compare confirms real
  2314. * changes. This works in non-git projects and catches committed changes from
  2315. * `git pull`/`checkout`/`merge`/`rebase` that `git status` cannot see.
  2316. */
  2317. async sync(onProgress?: (progress: IndexProgress) => void): Promise<SyncResult> {
  2318. await initGrammars(); // Initialize WASM runtime (grammars loaded lazily below)
  2319. const startTime = Date.now();
  2320. let filesChecked = 0;
  2321. let filesAdded = 0;
  2322. let filesModified = 0;
  2323. let filesRemoved = 0;
  2324. let nodesUpdated = 0;
  2325. const changedFilePaths: string[] = [];
  2326. onProgress?.({
  2327. phase: 'scanning',
  2328. current: 0,
  2329. total: 0,
  2330. });
  2331. const filesToIndex: string[] = [];
  2332. // === Filesystem reconcile (git-independent) ===
  2333. // The source of truth for "what changed" is the filesystem vs the indexed
  2334. // state — never git. We enumerate the current source files and reconcile
  2335. // each against the DB. A cheap (size, mtime) stat pre-filter skips unchanged
  2336. // files without reading or hashing them, so the expensive read+hash+parse
  2337. // only runs for files that actually changed. This catches edits/adds/deletes
  2338. // whether or not the project uses git, and crucially also catches committed
  2339. // changes from `git pull`/`checkout`/`merge`/`rebase` — which `git status`
  2340. // cannot see, because the working tree is clean afterward.
  2341. const tSyncScan = Date.now();
  2342. const currentFiles = await scanDirectoryAsync(this.rootDir);
  2343. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-scan: ${Date.now() - tSyncScan}ms (${currentFiles.length} files)`);
  2344. filesChecked = currentFiles.length;
  2345. const currentSet = new Set(currentFiles);
  2346. const tTracked = Date.now();
  2347. const trackedFiles = this.queries.getAllFiles();
  2348. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-tracked-load: ${Date.now() - tTracked}ms (${trackedFiles.length} tracked)`);
  2349. const trackedMap = new Map<string, FileRecord>();
  2350. for (const f of trackedFiles) {
  2351. trackedMap.set(f.path, f);
  2352. }
  2353. // Removals: tracked in the DB but no longer a present source file. Check the
  2354. // filesystem directly — `scanDirectory` (via `git ls-files`) still lists a
  2355. // file deleted from disk but not yet staged, so set membership alone misses it.
  2356. // `reconcileChecks` drives the cooperative yield shared with the adds/mods loop
  2357. // below (see SYNC_RECONCILE_YIELD_INTERVAL / issue #905).
  2358. let reconcileChecks = 0;
  2359. for (const tracked of trackedFiles) {
  2360. if (!currentSet.has(tracked.path) || !fs.existsSync(path.join(this.rootDir, tracked.path))) {
  2361. // Before the cascade deletes them, resurrect incoming cross-file
  2362. // resolution edges as their original refs (#1240 removal case): the
  2363. // callers live in files this sync will NOT revisit, so this is their
  2364. // only chance to rebind to an alternative definition — or to park as
  2365. // failed until the symbol reappears somewhere. (A deleted file whose
  2366. // CALLERS are also being deleted is fine: their nodes cascade later
  2367. // in this loop and take the resurrected rows with them.)
  2368. const incoming = this.queries.getCrossFileIncomingEdgesWithTarget(tracked.path);
  2369. if (incoming.length > 0) {
  2370. const resurrected = incoming
  2371. .map((e) => resurrectRefFromDroppedEdge(e))
  2372. .filter((r): r is UnresolvedReference => r !== null);
  2373. if (resurrected.length > 0) {
  2374. this.queries.insertUnresolvedRefsBatch(resurrected);
  2375. }
  2376. }
  2377. this.queries.deleteFile(tracked.path);
  2378. filesRemoved++;
  2379. }
  2380. if (++reconcileChecks % SYNC_RECONCILE_YIELD_INTERVAL === 0) {
  2381. await new Promise<void>((resolve) => setImmediate(resolve));
  2382. }
  2383. }
  2384. // Adds / modifications.
  2385. for (const filePath of currentFiles) {
  2386. // Same cooperative yield as the removals loop — this is the other O(files)
  2387. // synchronous-stat loop that wedges the main thread on a large repo (#905).
  2388. // Yield at the top of the body so the `continue` fast-paths below still hit it.
  2389. if (++reconcileChecks % SYNC_RECONCILE_YIELD_INTERVAL === 0) {
  2390. await new Promise<void>((resolve) => setImmediate(resolve));
  2391. }
  2392. const fullPath = path.join(this.rootDir, filePath);
  2393. const tracked = trackedMap.get(filePath);
  2394. // Cheap pre-filter: an already-indexed file whose size AND mtime both match
  2395. // the DB is unchanged — skip it without reading or hashing. (A content
  2396. // change that preserves both exactly is the blind spot every mtime-based
  2397. // incremental tool accepts; `index --force` is the escape hatch. Git bumps
  2398. // mtime on every file it writes during checkout/merge, so pulls are caught.)
  2399. if (tracked) {
  2400. try {
  2401. const stat = fs.statSync(fullPath);
  2402. if (stat.size === tracked.size && Math.floor(stat.mtimeMs) === Math.floor(tracked.modifiedAt)) {
  2403. continue;
  2404. }
  2405. } catch (error) {
  2406. logDebug('Skipping unstattable file during sync', { filePath, error: String(error) });
  2407. continue;
  2408. }
  2409. }
  2410. // New, or size/mtime changed — read + hash to confirm a real content change.
  2411. let content: string;
  2412. try {
  2413. content = fs.readFileSync(fullPath, 'utf-8');
  2414. } catch (error) {
  2415. logDebug('Skipping unreadable file during sync', { filePath, error: String(error) });
  2416. continue;
  2417. }
  2418. const contentHash = hashContent(content);
  2419. if (!tracked) {
  2420. filesToIndex.push(filePath);
  2421. changedFilePaths.push(filePath);
  2422. filesAdded++;
  2423. } else if (tracked.contentHash !== contentHash) {
  2424. filesToIndex.push(filePath);
  2425. changedFilePaths.push(filePath);
  2426. filesModified++;
  2427. }
  2428. }
  2429. // Load only grammars needed for changed files
  2430. if (filesToIndex.length > 0) {
  2431. const overrides = loadExtensionOverrides(this.rootDir);
  2432. const neededLanguages = [...new Set(filesToIndex.map((f) => detectLanguage(f, undefined, overrides)))];
  2433. // .h files default to 'c' but may be C++ — ensure cpp grammar is loaded
  2434. if (neededLanguages.includes('c') && !neededLanguages.includes('cpp')) {
  2435. neededLanguages.push('cpp');
  2436. }
  2437. await loadGrammarsForLanguages(neededLanguages);
  2438. }
  2439. // Index changed files
  2440. const total = filesToIndex.length;
  2441. for (let i = 0; i < filesToIndex.length; i++) {
  2442. const filePath = filesToIndex[i]!;
  2443. onProgress?.({
  2444. phase: 'parsing',
  2445. current: i + 1,
  2446. total,
  2447. currentFile: filePath,
  2448. });
  2449. const result = await this.indexFile(filePath);
  2450. nodesUpdated += result.nodes.length;
  2451. }
  2452. return {
  2453. filesChecked,
  2454. filesAdded,
  2455. filesModified,
  2456. filesRemoved,
  2457. nodesUpdated,
  2458. durationMs: Date.now() - startTime,
  2459. changedFilePaths: changedFilePaths.length > 0 ? changedFilePaths : undefined,
  2460. };
  2461. }
  2462. /**
  2463. * Get files that have changed since last index.
  2464. * Uses git status as a fast path when available, falling back to full scan.
  2465. */
  2466. getChangedFiles(): { added: string[]; modified: string[]; removed: string[] } {
  2467. const gitChanges = getGitChangedFiles(this.rootDir);
  2468. if (gitChanges) {
  2469. // === Git fast path ===
  2470. const added: string[] = [];
  2471. const modified: string[] = [];
  2472. const removed: string[] = [];
  2473. // Deleted files — only report if tracked in DB
  2474. for (const filePath of gitChanges.deleted) {
  2475. const tracked = this.queries.getFileByPath(filePath);
  2476. if (tracked) {
  2477. removed.push(filePath);
  2478. }
  2479. }
  2480. // Modified + added files — read + hash, compare with DB. Untracked (`??`)
  2481. // files stay untracked in git even after indexing, so they must be
  2482. // hash-compared like modified files instead of always counting as added —
  2483. // otherwise status reports them as pending forever. (See issue #206.)
  2484. for (const filePath of [...gitChanges.modified, ...gitChanges.added]) {
  2485. const fullPath = path.join(this.rootDir, filePath);
  2486. let content: string;
  2487. try {
  2488. content = fs.readFileSync(fullPath, 'utf-8');
  2489. } catch (error) {
  2490. logDebug('Skipping unreadable file while detecting changes', { filePath, error: String(error) });
  2491. continue;
  2492. }
  2493. const contentHash = hashContent(content);
  2494. const tracked = this.queries.getFileByPath(filePath);
  2495. if (!tracked) {
  2496. added.push(filePath);
  2497. } else if (tracked.contentHash !== contentHash) {
  2498. modified.push(filePath);
  2499. }
  2500. }
  2501. return { added, modified, removed };
  2502. }
  2503. // === Fallback: full scan (non-git project or git failure) ===
  2504. const currentFiles = new Set(scanDirectory(this.rootDir));
  2505. const trackedFiles = this.queries.getAllFiles();
  2506. // Build Map for O(1) lookups
  2507. const trackedMap = new Map<string, FileRecord>();
  2508. for (const f of trackedFiles) {
  2509. trackedMap.set(f.path, f);
  2510. }
  2511. const added: string[] = [];
  2512. const modified: string[] = [];
  2513. const removed: string[] = [];
  2514. // Find removed files
  2515. for (const tracked of trackedFiles) {
  2516. if (!currentFiles.has(tracked.path)) {
  2517. removed.push(tracked.path);
  2518. }
  2519. }
  2520. // Find added and modified files
  2521. for (const filePath of currentFiles) {
  2522. const fullPath = path.join(this.rootDir, filePath);
  2523. let content: string;
  2524. try {
  2525. content = fs.readFileSync(fullPath, 'utf-8');
  2526. } catch (error) {
  2527. logDebug('Skipping unreadable file while detecting changes', { filePath, error: String(error) });
  2528. continue;
  2529. }
  2530. const contentHash = hashContent(content);
  2531. const tracked = trackedMap.get(filePath);
  2532. if (!tracked) {
  2533. added.push(filePath);
  2534. } else if (tracked.contentHash !== contentHash) {
  2535. modified.push(filePath);
  2536. }
  2537. }
  2538. return { added, modified, removed };
  2539. }
  2540. }
  2541. // Re-export useful types and functions
  2542. export { extractFromSource } from './tree-sitter';
  2543. export { detectLanguage, isSourceFile, isLanguageSupported, isGrammarLoaded, getSupportedLanguages, initGrammars, loadGrammarsForLanguages, loadAllGrammars } from './grammars';