index.ts 136 KB

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