index.ts 147 KB

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