1
0

queries.ts 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577
  1. /**
  2. * Database Queries
  3. *
  4. * Prepared statements for CRUD operations on the knowledge graph.
  5. */
  6. import { SqliteDatabase, SqliteStatement } from './sqlite-adapter';
  7. import {
  8. Node,
  9. Edge,
  10. FileRecord,
  11. UnresolvedReference,
  12. NodeKind,
  13. EdgeKind,
  14. Language,
  15. GraphStats,
  16. SearchOptions,
  17. SearchResult,
  18. } from '../types';
  19. import { safeJsonParse } from '../utils';
  20. import { kindBonus, nameMatchBonus, scorePathRelevance } from '../search/query-utils';
  21. import { parseQuery, boundedEditDistance } from '../search/query-parser';
  22. import { isGeneratedFile } from '../extraction/generated-detection';
  23. import { splitIdentifierSegments } from '../search/identifier-segments';
  24. /**
  25. * Files that should not be candidates for "dominant file" detection: test/spec
  26. * files and tool-generated files. Generated files (`*.pb.go`, `*.pulsar.go`,
  27. * mock outputs, …) often have huge in-file edge counts that dwarf the real
  28. * source — etcd's `rpc.pb.go` has 4× the in-file edges of `server.go`.
  29. *
  30. * Path patterns plus, when the caller passes the indexed set, files whose
  31. * HEADER declares them generated — a `payroll.go` full of generated CRUD has
  32. * exactly the same edge-density problem as `rpc.pb.go` and nothing in its name
  33. * to catch it (#1500).
  34. */
  35. function isLowValueFile(filePath: string, generated?: ReadonlySet<string>): boolean {
  36. if (generated?.has(filePath)) return true;
  37. const lp = filePath.toLowerCase();
  38. return (
  39. /(?:^|\/)(tests?|__tests?__|spec)\//.test(lp) ||
  40. /_test\.go$/.test(lp) ||
  41. /(?:^|\/)test_[^/]+\.py$/.test(lp) ||
  42. /_test\.py$/.test(lp) ||
  43. /_spec\.rb$/.test(lp) ||
  44. /_test\.rb$/.test(lp) ||
  45. /\.(test|spec)\.[jt]sx?$/.test(lp) ||
  46. /(test|spec|tests)\.(java|kt|scala)$/.test(lp) ||
  47. /(tests?|spec)\.cs$/.test(lp) ||
  48. /tests?\.swift$/.test(lp) ||
  49. /_test\.dart$/.test(lp) ||
  50. isGeneratedFile(filePath)
  51. );
  52. }
  53. const SQLITE_PARAM_CHUNK_SIZE = 500;
  54. /**
  55. * Database row types (snake_case from SQLite)
  56. */
  57. interface NodeRow {
  58. id: string;
  59. kind: string;
  60. name: string;
  61. qualified_name: string;
  62. file_path: string;
  63. language: string;
  64. start_line: number;
  65. end_line: number;
  66. start_column: number;
  67. end_column: number;
  68. docstring: string | null;
  69. signature: string | null;
  70. visibility: string | null;
  71. is_exported: number;
  72. is_async: number;
  73. is_static: number;
  74. is_abstract: number;
  75. decorators: string | null;
  76. type_parameters: string | null;
  77. return_type: string | null;
  78. updated_at: number;
  79. }
  80. interface EdgeRow {
  81. id: number;
  82. source: string;
  83. target: string;
  84. kind: string;
  85. metadata: string | null;
  86. line: number | null;
  87. col: number | null;
  88. provenance: string | null;
  89. }
  90. interface FileRow {
  91. path: string;
  92. content_hash: string;
  93. language: string;
  94. size: number;
  95. modified_at: number;
  96. indexed_at: number;
  97. node_count: number;
  98. errors: string | null;
  99. /** Absent on pre-v9 rows read through a stale prepared statement. */
  100. generated?: number | null;
  101. }
  102. interface UnresolvedRefRow {
  103. id: number;
  104. from_node_id: string;
  105. reference_name: string;
  106. reference_kind: string;
  107. line: number;
  108. col: number;
  109. candidates: string | null;
  110. file_path: string;
  111. language: string;
  112. status: string;
  113. name_tail: string;
  114. }
  115. /**
  116. * Last segment of a (possibly dotted/qualified) reference name — the part a
  117. * new symbol's plain node name could match: 'util.greet' → 'greet',
  118. * 'mod::fn' → 'fn', 'greet' → 'greet'. Written to unresolved_refs.name_tail
  119. * when a ref is marked failed, so the #1240 retry lookup can match dotted
  120. * refs against newly-added node names.
  121. */
  122. function referenceNameTail(referenceName: string): string {
  123. const idx = Math.max(referenceName.lastIndexOf('.'), referenceName.lastIndexOf(':'));
  124. return idx >= 0 ? referenceName.slice(idx + 1) : referenceName;
  125. }
  126. /**
  127. * Convert database row to Node object
  128. */
  129. function rowToNode(row: NodeRow): Node {
  130. return {
  131. id: row.id,
  132. kind: row.kind as NodeKind,
  133. name: row.name,
  134. qualifiedName: row.qualified_name,
  135. filePath: row.file_path,
  136. language: row.language as Language,
  137. startLine: row.start_line,
  138. endLine: row.end_line,
  139. startColumn: row.start_column,
  140. endColumn: row.end_column,
  141. docstring: row.docstring ?? undefined,
  142. signature: row.signature ?? undefined,
  143. visibility: row.visibility as Node['visibility'],
  144. isExported: row.is_exported === 1,
  145. isAsync: row.is_async === 1,
  146. isStatic: row.is_static === 1,
  147. isAbstract: row.is_abstract === 1,
  148. decorators: row.decorators ? safeJsonParse(row.decorators, undefined) : undefined,
  149. typeParameters: row.type_parameters ? safeJsonParse(row.type_parameters, undefined) : undefined,
  150. returnType: row.return_type ?? undefined,
  151. updatedAt: row.updated_at,
  152. };
  153. }
  154. /**
  155. * Convert database row to Edge object
  156. */
  157. function rowToEdge(row: EdgeRow): Edge {
  158. return {
  159. source: row.source,
  160. target: row.target,
  161. kind: row.kind as EdgeKind,
  162. metadata: row.metadata ? safeJsonParse(row.metadata, undefined) : undefined,
  163. line: row.line ?? undefined,
  164. column: row.col ?? undefined,
  165. provenance: row.provenance as Edge['provenance'],
  166. };
  167. }
  168. /**
  169. * Convert database row to FileRecord object
  170. */
  171. function rowToFileRecord(row: FileRow): FileRecord {
  172. return {
  173. path: row.path,
  174. contentHash: row.content_hash,
  175. language: row.language as Language,
  176. size: row.size,
  177. modifiedAt: row.modified_at,
  178. indexedAt: row.indexed_at,
  179. nodeCount: row.node_count,
  180. errors: row.errors ? safeJsonParse(row.errors, undefined) : undefined,
  181. generated: row.generated === 1,
  182. };
  183. }
  184. /**
  185. * Query builder for the knowledge graph database
  186. */
  187. export class QueryBuilder {
  188. private db: SqliteDatabase;
  189. // Project-name tokens (go.mod / package.json / repo dir), normalized. A query
  190. // word matching one is dropped from path-relevance scoring — it names the
  191. // whole project, not a symbol, so it carries no discriminative signal (#720).
  192. // Set once by the CodeGraph instance; empty by default (no down-weighting).
  193. private projectNameTokens: Set<string> = new Set();
  194. // Node cache for frequently accessed nodes (LRU-style, max 1000 entries)
  195. private nodeCache: Map<string, Node> = new Map();
  196. private readonly maxCacheSize = 1000;
  197. // Prepared statements (lazily initialized)
  198. private stmts: {
  199. insertNode?: SqliteStatement;
  200. updateNode?: SqliteStatement;
  201. deleteNode?: SqliteStatement;
  202. deleteNodesByFile?: SqliteStatement;
  203. getNodeById?: SqliteStatement;
  204. getNodesByFile?: SqliteStatement;
  205. getNodesByKind?: SqliteStatement;
  206. insertEdge?: SqliteStatement;
  207. upsertFile?: SqliteStatement;
  208. deleteEdgesBySource?: SqliteStatement;
  209. deleteEdgesByTarget?: SqliteStatement;
  210. getEdgesBySource?: SqliteStatement;
  211. getEdgesByTarget?: SqliteStatement;
  212. insertFile?: SqliteStatement;
  213. updateFile?: SqliteStatement;
  214. deleteFile?: SqliteStatement;
  215. getFileByPath?: SqliteStatement;
  216. getAllFiles?: SqliteStatement;
  217. insertUnresolved?: SqliteStatement;
  218. deleteUnresolvedByNode?: SqliteStatement;
  219. getUnresolvedByName?: SqliteStatement;
  220. getNodesByName?: SqliteStatement;
  221. getNodesByNamePrefix?: SqliteStatement;
  222. getNodesByQualifiedNameExact?: SqliteStatement;
  223. getNodesByLowerName?: SqliteStatement;
  224. getUnresolvedCount?: SqliteStatement;
  225. getUnresolvedBatch?: SqliteStatement;
  226. getUnresolvedBatchAfter?: SqliteStatement;
  227. deleteRefsByRowIdsFull?: SqliteStatement;
  228. getAllFilePaths?: SqliteStatement;
  229. getAllNodeNames?: SqliteStatement;
  230. getDominantFile?: SqliteStatement;
  231. getTopRouteFile?: SqliteStatement;
  232. getRoutingManifest?: SqliteStatement;
  233. insertNameSegment?: SqliteStatement;
  234. } = {};
  235. // Names whose segments were already written this session — skips re-splitting
  236. // and re-inserting for the same-named nodes that repeat across files ("get",
  237. // "render", …). Purely a write-path fast path; INSERT OR IGNORE is the
  238. // correctness backstop. Bounded so a pathological repo can't grow it forever.
  239. private segmentedNames: Set<string> = new Set();
  240. private static readonly MAX_SEGMENTED_NAMES = 65536;
  241. // Multi-row INSERT statements, cached per (statement kind × row count). The
  242. // bulk write path decomposes N rows into a few fixed batch sizes so each
  243. // size's statement is prepared once and reused — one .run() binds a whole
  244. // chunk instead of one row, which is where the per-call overhead lives.
  245. // Row order within and across chunks is the input order, so rowid assignment
  246. // (and therefore resolution's insertion-order disambiguation) is identical
  247. // to the one-row-per-run path.
  248. private batchStmts: Map<string, SqliteStatement> = new Map();
  249. private static readonly BATCH_SIZES: readonly number[] = [128, 32, 8, 1];
  250. /**
  251. * Run `rows` through a multi-row `INSERT` built as `head + (tuple,)*n`,
  252. * decomposed greedily into the cached batch sizes. Preserves row order.
  253. */
  254. private runBatched(kind: string, head: string, tuple: string, rows: unknown[][]): void {
  255. if (rows.length === 0) return;
  256. let i = 0;
  257. for (const size of QueryBuilder.BATCH_SIZES) {
  258. while (rows.length - i >= size) {
  259. const key = `${kind}:${size}`;
  260. let stmt = this.batchStmts.get(key);
  261. if (!stmt) {
  262. stmt = this.db.prepare(head + new Array(size).fill(tuple).join(','));
  263. this.batchStmts.set(key, stmt);
  264. }
  265. if (size === 1) {
  266. stmt.run(...rows[i]!);
  267. } else {
  268. const params: unknown[] = [];
  269. for (let r = 0; r < size; r++) {
  270. const row = rows[i + r]!;
  271. for (let c = 0; c < row.length; c++) params.push(row[c]);
  272. }
  273. stmt.run(...params);
  274. }
  275. i += size;
  276. }
  277. }
  278. }
  279. constructor(db: SqliteDatabase) {
  280. this.db = db;
  281. }
  282. /**
  283. * Swap the underlying connection in place. Used by pool workers'
  284. * connection recycling (plan §7a.6, writes-under-readers): a long-lived
  285. * read connection pins WAL checkpoint progress, and the deep WAL that
  286. * accumulates behind it taxes every main-thread B-tree page operation
  287. * (deletes measured 42.6s → 118.8s from 0 to 4 attached readers on
  288. * identical hardware). Workers therefore close and reopen their read-only
  289. * connection at the pool-idle boundary; everything above the connection —
  290. * this QueryBuilder, the resolver and its warm caches — survives, and only
  291. * connection-derived state (prepared statements) resets, re-preparing
  292. * lazily on next use.
  293. */
  294. rebind(db: SqliteDatabase): void {
  295. this.db = db;
  296. this.stmts = {};
  297. this.batchStmts.clear();
  298. }
  299. /** Set the normalized project-name tokens used to down-weight non-discriminative
  300. * query words in path scoring (#720). Called once when the project opens. */
  301. setProjectNameTokens(tokens: Set<string>): void {
  302. this.projectNameTokens = tokens;
  303. }
  304. /** The normalized project-name tokens (#720); empty if none were derived. */
  305. getProjectNameTokens(): Set<string> {
  306. return this.projectNameTokens;
  307. }
  308. // ===========================================================================
  309. // Node Operations
  310. // ===========================================================================
  311. /**
  312. * Insert a new node
  313. */
  314. insertNode(node: Node): void {
  315. if (!this.stmts.insertNode) {
  316. this.stmts.insertNode = this.db.prepare(`
  317. INSERT OR REPLACE INTO nodes (
  318. id, kind, name, qualified_name, file_path, language,
  319. start_line, end_line, start_column, end_column,
  320. docstring, signature, visibility,
  321. is_exported, is_async, is_static, is_abstract,
  322. decorators, type_parameters, return_type, updated_at
  323. ) VALUES (
  324. @id, @kind, @name, @qualifiedName, @filePath, @language,
  325. @startLine, @endLine, @startColumn, @endColumn,
  326. @docstring, @signature, @visibility,
  327. @isExported, @isAsync, @isStatic, @isAbstract,
  328. @decorators, @typeParameters, @returnType, @updatedAt
  329. )
  330. `);
  331. }
  332. // Validate required fields to prevent SQLite bind errors
  333. if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
  334. console.error('[CodeGraph] Skipping node with missing required fields:', {
  335. id: node.id,
  336. kind: node.kind,
  337. name: node.name,
  338. filePath: node.filePath,
  339. language: node.language,
  340. });
  341. return;
  342. }
  343. // INSERT OR REPLACE may overwrite a node we have cached. Drop the
  344. // stale entry so the next getNodeById sees the new row, not the old
  345. // one (matches the cache-invalidation pattern used by updateNode and
  346. // deleteNode below).
  347. this.nodeCache.delete(node.id);
  348. this.stmts.insertNode.run({
  349. id: node.id,
  350. kind: node.kind,
  351. name: node.name,
  352. qualifiedName: node.qualifiedName ?? node.name,
  353. filePath: node.filePath,
  354. language: node.language,
  355. startLine: node.startLine ?? 0,
  356. endLine: node.endLine ?? 0,
  357. startColumn: node.startColumn ?? 0,
  358. endColumn: node.endColumn ?? 0,
  359. docstring: node.docstring ?? null,
  360. signature: node.signature ?? null,
  361. visibility: node.visibility ?? null,
  362. isExported: node.isExported ? 1 : 0,
  363. isAsync: node.isAsync ? 1 : 0,
  364. isStatic: node.isStatic ? 1 : 0,
  365. isAbstract: node.isAbstract ? 1 : 0,
  366. decorators: node.decorators ? JSON.stringify(node.decorators) : null,
  367. typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
  368. returnType: node.returnType ?? null,
  369. updatedAt: node.updatedAt ?? Date.now(),
  370. });
  371. // Segment vocabulary rides the same write path (and transaction) so it can
  372. // never drift ahead of the nodes it describes. Deletes intentionally leave
  373. // orphans behind — vocab rows are proposals re-verified against nodes
  374. // before use, and a full index clears the table at its start. File nodes
  375. // are excluded: a file's basename duplicates the symbols inside it
  376. // (state-machine.ts / OrderStateMachine), which double-counts every
  377. // concept and defeats the singleton-vs-cluster rarity statistics. Import
  378. // nodes are excluded too (#1144): they're named after module specifiers
  379. // ("external-unindexed-pkg", "./utils/helpers"), not symbols — an
  380. // import-only name can never be surfaced (getSegmentMatches requires a
  381. // real definition), so its rows would only inflate the rarity statistics.
  382. if (this.isSegmentableKind(node.kind)) this.insertNameSegments(node.name);
  383. }
  384. /** Which node kinds contribute their name to the segment vocabulary — the
  385. * single gate shared by insertNode, updateNode, and the rebuild page query
  386. * (getDistinctNodeNames), so the write paths can't drift apart. */
  387. private isSegmentableKind(kind: string): boolean {
  388. return kind !== 'file' && kind !== 'import';
  389. }
  390. /** Write `name`'s segments into name_segment_vocab (idempotent). */
  391. private insertNameSegments(name: string): void {
  392. const rows: unknown[][] = [];
  393. this.collectNameSegmentRows(name, rows);
  394. this.runBatched(
  395. 'insertNameSegments',
  396. 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ',
  397. '(?,?)',
  398. rows
  399. );
  400. }
  401. /**
  402. * Insert multiple nodes in a transaction
  403. */
  404. insertNodes(nodes: Node[]): void {
  405. this.db.transaction(() => {
  406. // Bulk path: same semantics as insertNode() per row (validation, cache
  407. // invalidation, segment vocab), but bound as multi-row INSERTs — the
  408. // per-.run() call overhead dominates the store phase on full indexes.
  409. const rows: unknown[][] = [];
  410. const segmentRows: unknown[][] = [];
  411. for (const node of nodes) {
  412. if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
  413. console.error('[CodeGraph] Skipping node with missing required fields:', {
  414. id: node.id,
  415. kind: node.kind,
  416. name: node.name,
  417. filePath: node.filePath,
  418. language: node.language,
  419. });
  420. continue;
  421. }
  422. this.nodeCache.delete(node.id);
  423. rows.push([
  424. node.id,
  425. node.kind,
  426. node.name,
  427. node.qualifiedName ?? node.name,
  428. node.filePath,
  429. node.language,
  430. node.startLine ?? 0,
  431. node.endLine ?? 0,
  432. node.startColumn ?? 0,
  433. node.endColumn ?? 0,
  434. node.docstring ?? null,
  435. node.signature ?? null,
  436. node.visibility ?? null,
  437. node.isExported ? 1 : 0,
  438. node.isAsync ? 1 : 0,
  439. node.isStatic ? 1 : 0,
  440. node.isAbstract ? 1 : 0,
  441. node.decorators ? JSON.stringify(node.decorators) : null,
  442. node.typeParameters ? JSON.stringify(node.typeParameters) : null,
  443. node.returnType ?? null,
  444. node.updatedAt ?? Date.now(),
  445. ]);
  446. if (this.isSegmentableKind(node.kind)) this.collectNameSegmentRows(node.name, segmentRows);
  447. }
  448. this.runBatched(
  449. 'insertNodes',
  450. `INSERT OR REPLACE INTO nodes (
  451. id, kind, name, qualified_name, file_path, language,
  452. start_line, end_line, start_column, end_column,
  453. docstring, signature, visibility,
  454. is_exported, is_async, is_static, is_abstract,
  455. decorators, type_parameters, return_type, updated_at
  456. ) VALUES `,
  457. '(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
  458. rows
  459. );
  460. this.runBatched(
  461. 'insertNameSegments',
  462. 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ',
  463. '(?,?)',
  464. segmentRows
  465. );
  466. })();
  467. }
  468. /**
  469. * Store one file's whole extraction bundle — nodes, edges, unresolved refs,
  470. * and the file record — in a SINGLE transaction. The bulk-index path calls
  471. * this once per file instead of opening one transaction per table (#1015
  472. * file-order commit discipline is unchanged: callers still invoke it in file
  473. * order, and row order within is input order).
  474. *
  475. * Edges MUST already be endpoint-filtered by the caller (the store path
  476. * filters to the file's own inserted node ids), so the per-file existence
  477. * SELECT that insertEdges() pays is skipped here.
  478. */
  479. storeFileBundle(bundle: {
  480. nodes: Node[];
  481. edges: Edge[];
  482. refs: UnresolvedReference[];
  483. file: FileRecord;
  484. }): void {
  485. this.db.transaction(() => {
  486. this.insertNodes(bundle.nodes);
  487. if (bundle.edges.length > 0) {
  488. const rows: unknown[][] = [];
  489. for (const edge of bundle.edges) {
  490. rows.push([
  491. edge.source,
  492. edge.target,
  493. edge.kind,
  494. edge.metadata ? JSON.stringify(edge.metadata) : null,
  495. edge.line ?? null,
  496. edge.column ?? null,
  497. edge.provenance ?? null,
  498. ]);
  499. }
  500. this.runBatched(
  501. 'insertEdges',
  502. 'INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance) VALUES ',
  503. '(?,?,?,?,?,?,?)',
  504. rows
  505. );
  506. }
  507. if (bundle.refs.length > 0) this.insertUnresolvedRefsBatch(bundle.refs);
  508. this.upsertFile(bundle.file);
  509. })();
  510. }
  511. /**
  512. * Collect (segment, name) rows for a name, honouring the same session-dedupe
  513. * semantics as insertNameSegments(). Shared by the bulk write paths.
  514. */
  515. private collectNameSegmentRows(name: string, out: unknown[][]): void {
  516. if (this.segmentedNames.has(name)) return;
  517. if (this.segmentedNames.size >= QueryBuilder.MAX_SEGMENTED_NAMES) this.segmentedNames.clear();
  518. this.segmentedNames.add(name);
  519. for (const segment of splitIdentifierSegments(name)) out.push([segment, name]);
  520. }
  521. /**
  522. * Update an existing node
  523. */
  524. updateNode(node: Node): void {
  525. if (!this.stmts.updateNode) {
  526. this.stmts.updateNode = this.db.prepare(`
  527. UPDATE nodes SET
  528. kind = @kind,
  529. name = @name,
  530. qualified_name = @qualifiedName,
  531. file_path = @filePath,
  532. language = @language,
  533. start_line = @startLine,
  534. end_line = @endLine,
  535. start_column = @startColumn,
  536. end_column = @endColumn,
  537. docstring = @docstring,
  538. signature = @signature,
  539. visibility = @visibility,
  540. is_exported = @isExported,
  541. is_async = @isAsync,
  542. is_static = @isStatic,
  543. is_abstract = @isAbstract,
  544. decorators = @decorators,
  545. type_parameters = @typeParameters,
  546. return_type = @returnType,
  547. updated_at = @updatedAt
  548. WHERE id = @id
  549. `);
  550. }
  551. // Invalidate cache before update
  552. this.nodeCache.delete(node.id);
  553. // Validate required fields
  554. if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
  555. console.error('[CodeGraph] Skipping node update with missing required fields:', node.id);
  556. return;
  557. }
  558. this.stmts.updateNode.run({
  559. id: node.id,
  560. kind: node.kind,
  561. name: node.name,
  562. qualifiedName: node.qualifiedName ?? node.name,
  563. filePath: node.filePath,
  564. language: node.language,
  565. startLine: node.startLine ?? 0,
  566. endLine: node.endLine ?? 0,
  567. startColumn: node.startColumn ?? 0,
  568. endColumn: node.endColumn ?? 0,
  569. docstring: node.docstring ?? null,
  570. signature: node.signature ?? null,
  571. visibility: node.visibility ?? null,
  572. isExported: node.isExported ? 1 : 0,
  573. isAsync: node.isAsync ? 1 : 0,
  574. isStatic: node.isStatic ? 1 : 0,
  575. isAbstract: node.isAbstract ? 1 : 0,
  576. decorators: node.decorators ? JSON.stringify(node.decorators) : null,
  577. typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
  578. returnType: node.returnType ?? null,
  579. updatedAt: node.updatedAt ?? Date.now(),
  580. });
  581. // updateNode is a second real write path to `nodes` — framework
  582. // post-extract passes rewrite names through it (NestJS route prefixing),
  583. // and a renamed node's new name must reach the segment vocabulary just
  584. // like an inserted one's (#1141). Without this the rename left the new
  585. // name permanently unsearchable: the old name's rows became honest-gate
  586. // orphans and the only backfill is gated on the vocab being EMPTY.
  587. // insertNameSegments is idempotent (in-memory set + INSERT OR IGNORE),
  588. // so no name-changed check is needed.
  589. if (this.isSegmentableKind(node.kind)) this.insertNameSegments(node.name);
  590. }
  591. /**
  592. * Delete a node by ID
  593. */
  594. deleteNode(id: string): void {
  595. if (!this.stmts.deleteNode) {
  596. this.stmts.deleteNode = this.db.prepare('DELETE FROM nodes WHERE id = ?');
  597. }
  598. // Invalidate cache
  599. this.nodeCache.delete(id);
  600. this.stmts.deleteNode.run(id);
  601. }
  602. /**
  603. * Delete all nodes for a file
  604. */
  605. deleteNodesByFile(filePath: string): void {
  606. if (!this.stmts.deleteNodesByFile) {
  607. this.stmts.deleteNodesByFile = this.db.prepare('DELETE FROM nodes WHERE file_path = ?');
  608. }
  609. // Invalidate cache for nodes in this file
  610. for (const [id, node] of this.nodeCache) {
  611. if (node.filePath === filePath) {
  612. this.nodeCache.delete(id);
  613. }
  614. }
  615. this.stmts.deleteNodesByFile.run(filePath);
  616. }
  617. // ===========================================================================
  618. // Name-segment vocabulary (prompt-hook graph-derived gate)
  619. // ===========================================================================
  620. /** Wipe the segment vocabulary. A full index calls this at its start; the
  621. * node write path repopulates it as files (re-)index, so the end state is
  622. * exactly the current names with no orphan rows. */
  623. clearNameSegmentVocab(): void {
  624. this.db.exec('DELETE FROM name_segment_vocab');
  625. this.segmentedNames.clear();
  626. }
  627. /** True when the vocab has no rows — an index built before the table existed.
  628. * `sync` uses this to heal such databases (see rebuildNameSegmentVocabFrom). */
  629. isNameSegmentVocabEmpty(): boolean {
  630. const row = this.db.prepare('SELECT 1 FROM name_segment_vocab LIMIT 1').get();
  631. return row === undefined;
  632. }
  633. /** One page of distinct segmentable node names, for batched vocab rebuilds
  634. * (file basenames and import specifiers are excluded from the vocab — see
  635. * insertNode). */
  636. getDistinctNodeNames(limit: number, offset: number): string[] {
  637. const rows = this.db
  638. .prepare("SELECT DISTINCT name FROM nodes WHERE kind NOT IN ('file', 'import') ORDER BY name LIMIT ? OFFSET ?")
  639. .all(limit, offset) as Array<{ name: string }>;
  640. return rows.map((r) => r.name);
  641. }
  642. /** Insert segments for a batch of names in one transaction (vocab heal path). */
  643. insertNameSegmentsBatch(names: string[]): void {
  644. this.db.transaction(() => {
  645. const rows: unknown[][] = [];
  646. for (const name of names) this.collectNameSegmentRows(name, rows);
  647. this.runBatched(
  648. 'insertNameSegments',
  649. 'INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ',
  650. '(?,?)',
  651. rows
  652. );
  653. })();
  654. }
  655. /**
  656. * Names whose segments cover at least `minWords` distinct PROMPT WORDS —
  657. * the co-occurrence probe behind the prompt hook's medium tier: the words
  658. * "state" and "machine" both being segments of `OrderStateMachine` is strong
  659. * evidence the prompt names that symbol in prose. Ordered by coverage.
  660. *
  661. * Takes (segment variant → original word) pairs and folds variants back to
  662. * their word INSIDE the SQL: a name matching both `service` and `services`
  663. * counts ONE word, not two. Counting raw variants let plural-variant pairs
  664. * of a single word tie with genuine two-word matches and — because ORDER
  665. * BY/LIMIT run here, before any JS-side re-check — crowd a real match past
  666. * the LIMIT on vocab-heavy repos (#1146).
  667. */
  668. getSegmentCoOccurrence(
  669. variants: Array<{ segment: string; word: string }>,
  670. minWords: number,
  671. limit: number,
  672. ): Array<{ name: string; matches: number }> {
  673. if (variants.length === 0) return [];
  674. const placeholders = variants.map(() => '?').join(', ');
  675. const whens = variants.map(() => 'WHEN ? THEN ?').join(' ');
  676. const rows = this.db
  677. .prepare(
  678. `SELECT name, COUNT(DISTINCT CASE segment ${whens} END) AS matches
  679. FROM name_segment_vocab
  680. WHERE segment IN (${placeholders})
  681. GROUP BY name
  682. HAVING matches >= ?
  683. ORDER BY matches DESC, length(name) ASC
  684. LIMIT ?`,
  685. )
  686. .all(
  687. ...variants.flatMap((v) => [v.segment, v.word]),
  688. ...variants.map((v) => v.segment),
  689. minWords,
  690. limit,
  691. ) as Array<{ name: string; matches: number }>;
  692. return rows;
  693. }
  694. /** How many distinct names each segment appears in — the rarity signal that
  695. * separates a discriminative word ("checkout") from a ubiquitous one ("state"). */
  696. getSegmentNameCounts(segments: string[]): Map<string, number> {
  697. if (segments.length === 0) return new Map();
  698. const placeholders = segments.map(() => '?').join(', ');
  699. const rows = this.db
  700. .prepare(
  701. `SELECT segment, COUNT(*) AS n FROM name_segment_vocab
  702. WHERE segment IN (${placeholders}) GROUP BY segment`,
  703. )
  704. .all(...segments) as Array<{ segment: string; n: number }>;
  705. return new Map(rows.map((r) => [r.segment, r.n]));
  706. }
  707. /** Names containing the given segment (rare-single-word tier). */
  708. getNamesForSegment(segment: string, limit: number): string[] {
  709. const rows = this.db
  710. .prepare('SELECT name FROM name_segment_vocab WHERE segment = ? ORDER BY length(name) ASC LIMIT ?')
  711. .all(segment, limit) as Array<{ name: string }>;
  712. return rows.map((r) => r.name);
  713. }
  714. /**
  715. * Get a node by ID
  716. */
  717. getNodeById(id: string): Node | null {
  718. // Check cache first
  719. if (this.nodeCache.has(id)) {
  720. const cached = this.nodeCache.get(id)!;
  721. // Move to end to implement LRU (delete and re-add)
  722. this.nodeCache.delete(id);
  723. this.nodeCache.set(id, cached);
  724. return cached;
  725. }
  726. if (!this.stmts.getNodeById) {
  727. this.stmts.getNodeById = this.db.prepare('SELECT * FROM nodes WHERE id = ?');
  728. }
  729. const row = this.stmts.getNodeById.get(id) as NodeRow | undefined;
  730. if (!row) {
  731. return null;
  732. }
  733. const node = rowToNode(row);
  734. this.cacheNode(node);
  735. return node;
  736. }
  737. /**
  738. * Batch lookup: fetch many nodes by ID in a single SQL round-trip.
  739. *
  740. * Replaces the N+1 pattern in graph traversal where every edge would
  741. * trigger its own `getNodeById` call. For a function with 50 callers
  742. * this collapses 50 point reads into one IN-list query (~10-50x
  743. * faster end-to-end).
  744. *
  745. * Returns a Map keyed by id so callers can preserve their own ordering
  746. * (typically the order edges were returned from the graph). Missing IDs
  747. * are simply absent from the map.
  748. *
  749. * Cache-aware: ids already in the LRU cache are served from memory and
  750. * the SQL query only touches the misses.
  751. */
  752. getNodesByIds(ids: readonly string[]): Map<string, Node> {
  753. const out = new Map<string, Node>();
  754. if (ids.length === 0) return out;
  755. // Serve cache hits first; build the miss list for SQL.
  756. const misses: string[] = [];
  757. for (const id of ids) {
  758. const cached = this.nodeCache.get(id);
  759. if (cached !== undefined) {
  760. // LRU touch
  761. this.nodeCache.delete(id);
  762. this.nodeCache.set(id, cached);
  763. out.set(id, cached);
  764. } else {
  765. misses.push(id);
  766. }
  767. }
  768. if (misses.length === 0) return out;
  769. // Chunk under SQLite's parameter limit (default 999, raised to 32766
  770. // in better-sqlite3 builds — chunk at 500 for safety across both
  771. // backends and to keep the query plan simple).
  772. for (let i = 0; i < misses.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  773. const chunk = misses.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  774. const placeholders = chunk.map(() => '?').join(',');
  775. const rows = this.db
  776. .prepare(`SELECT * FROM nodes WHERE id IN (${placeholders})`)
  777. .all(...chunk) as NodeRow[];
  778. for (const row of rows) {
  779. const node = rowToNode(row);
  780. out.set(node.id, node);
  781. this.cacheNode(node);
  782. }
  783. }
  784. return out;
  785. }
  786. private getExistingNodeIds(ids: readonly string[]): Set<string> {
  787. const out = new Set<string>();
  788. if (ids.length === 0) return out;
  789. const uniqueIds = [...new Set(ids)];
  790. for (let i = 0; i < uniqueIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  791. const chunk = uniqueIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  792. const placeholders = chunk.map(() => '?').join(',');
  793. const rows = this.db
  794. .prepare(`SELECT id FROM nodes WHERE id IN (${placeholders})`)
  795. .all(...chunk) as { id: string }[];
  796. for (const row of rows) {
  797. out.add(row.id);
  798. }
  799. }
  800. return out;
  801. }
  802. /**
  803. * Add a node to the cache, evicting oldest if needed
  804. */
  805. private cacheNode(node: Node): void {
  806. if (this.nodeCache.size >= this.maxCacheSize) {
  807. // Evict oldest (first) entry
  808. const firstKey = this.nodeCache.keys().next().value;
  809. if (firstKey) {
  810. this.nodeCache.delete(firstKey);
  811. }
  812. }
  813. this.nodeCache.set(node.id, node);
  814. }
  815. /**
  816. * Clear the node cache
  817. */
  818. clearCache(): void {
  819. this.nodeCache.clear();
  820. }
  821. /**
  822. * Get all nodes in a file
  823. */
  824. getNodesByFile(filePath: string): Node[] {
  825. if (!this.stmts.getNodesByFile) {
  826. this.stmts.getNodesByFile = this.db.prepare(
  827. 'SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line'
  828. );
  829. }
  830. const rows = this.stmts.getNodesByFile.all(filePath) as NodeRow[];
  831. return rows.map(rowToNode);
  832. }
  833. /**
  834. * Find the file that holds the densest concentration of the project's
  835. * internal call graph — the "core" file. Used by context-builder to
  836. * boost ranking of symbols in that file's directory (so e.g. sinatra
  837. * queries surface `lib/sinatra/base.rb`'s `route!` instead of
  838. * `sinatra-contrib/lib/sinatra/multi_route.rb`'s `route` extension).
  839. *
  840. * Returns null if no file has a meaningful concentration (e.g. spread
  841. * evenly across many files, or empty index).
  842. *
  843. * "Internal" = source and target are in the same file. Cross-file
  844. * edges aren't useful here — they don't tell us which file is the
  845. * functional center.
  846. *
  847. * Excludes test/spec files from candidacy via path-pattern. The agent's
  848. * typical question is "how does X work", not "how is X tested", so
  849. * boosting a test file's directory would be a misfire.
  850. */
  851. getDominantFile(): { filePath: string; edgeCount: number; nextEdgeCount: number } | null {
  852. if (!this.stmts.getDominantFile) {
  853. // Pull top 20 candidates; we then filter out test/generated files
  854. // in code (regex-grade matching that SQL LIKE can't express). The
  855. // generated-file filter is critical — without it, etcd's
  856. // `api/etcdserverpb/rpc.pb.go` (1916 in-file edges, generated
  857. // protobuf stub) outranks the real `server/etcdserver/server.go`
  858. // (470 edges) by 4×, and the boost would push the agent toward
  859. // generated code.
  860. this.stmts.getDominantFile = this.db.prepare(`
  861. SELECT n.file_path AS file_path, COUNT(*) AS edge_count
  862. FROM edges e
  863. JOIN nodes n ON e.source = n.id
  864. JOIN nodes m ON e.target = m.id
  865. WHERE n.file_path = m.file_path
  866. GROUP BY n.file_path
  867. ORDER BY edge_count DESC
  868. LIMIT 20
  869. `);
  870. }
  871. const rows = this.stmts.getDominantFile.all() as Array<{ file_path: string; edge_count: number }>;
  872. const generated = this.getGeneratedPathsAmong(rows.map(r => r.file_path));
  873. const filtered = rows.filter(r => !isLowValueFile(r.file_path, generated));
  874. if (filtered.length === 0 || filtered[0]!.edge_count < 20) return null;
  875. return {
  876. filePath: filtered[0]!.file_path,
  877. edgeCount: filtered[0]!.edge_count,
  878. nextEdgeCount: filtered[1]?.edge_count ?? 0,
  879. };
  880. }
  881. /**
  882. * Find the file that holds the densest concentration of the project's
  883. * `route` nodes (framework-emitted: Express/Gin/Flask/Rails/Drupal/etc.).
  884. * Used by handleContext on small repos to inline the project's routing
  885. * config when the agent's query is about request flow — eliminating the
  886. * "Glob + Read routes.rb" pattern that beats codegraph on tiny realworld
  887. * template repos.
  888. *
  889. * Excludes test/generated files from candidacy. Returns null if there
  890. * are fewer than 3 non-test routes total, or if no file holds at least
  891. * 30% of them (diffuse routing → no single answer file).
  892. */
  893. getTopRouteFile(): { filePath: string; routeCount: number; totalRoutes: number } | null {
  894. if (!this.stmts.getTopRouteFile) {
  895. this.stmts.getTopRouteFile = this.db.prepare(`
  896. SELECT file_path, COUNT(*) AS cnt
  897. FROM nodes
  898. WHERE kind = 'route'
  899. GROUP BY file_path
  900. ORDER BY cnt DESC
  901. LIMIT 20
  902. `);
  903. }
  904. const rows = this.stmts.getTopRouteFile.all() as Array<{ file_path: string; cnt: number }>;
  905. const generated = this.getGeneratedPathsAmong(rows.map(r => r.file_path));
  906. const filtered = rows.filter(r => !isLowValueFile(r.file_path, generated));
  907. if (filtered.length === 0) return null;
  908. const totalRoutes = filtered.reduce((sum, r) => sum + r.cnt, 0);
  909. const top = filtered[0]!;
  910. if (totalRoutes < 3 || top.cnt < 3) return null;
  911. if (top.cnt / totalRoutes < 0.30) return null;
  912. return { filePath: top.file_path, routeCount: top.cnt, totalRoutes };
  913. }
  914. /**
  915. * Build a URL → handler manifest from the index. Each route node's
  916. * `references` edge points at the function/method that handles the
  917. * request. We join them in one pass; the agent gets the canonical
  918. * routing answer ("POST /users/login → AuthController#login") without
  919. * having to parse the framework's route DSL itself.
  920. *
  921. * Also returns the file with the most handler endpoints — used as the
  922. * "top handler file" to inline source for, so the agent has both the
  923. * mapping AND the handler implementations.
  924. */
  925. getRoutingManifest(limit: number = 40): {
  926. entries: Array<{ url: string; handler: string; handlerFile: string; handlerLine: number; handlerKind: string }>;
  927. topHandlerFile: string | null;
  928. topHandlerFileCount: number;
  929. totalRoutes: number;
  930. } | null {
  931. if (!this.stmts.getRoutingManifest) {
  932. // Edge kind varies across framework resolvers: Spring/Rails/
  933. // Laravel/Drupal emit `references`, Express emits `calls`. Accept
  934. // both — the semantic is the same (route → its handler).
  935. this.stmts.getRoutingManifest = this.db.prepare(`
  936. SELECT
  937. r.name AS url,
  938. h.name AS handler,
  939. h.file_path AS handler_file,
  940. h.start_line AS handler_line,
  941. h.kind AS handler_kind
  942. FROM nodes r
  943. JOIN edges e ON e.source = r.id
  944. JOIN nodes h ON e.target = h.id
  945. WHERE r.kind = 'route'
  946. AND e.kind IN ('references', 'calls')
  947. AND h.kind IN ('function', 'method', 'class')
  948. ORDER BY r.file_path, r.start_line
  949. LIMIT ?
  950. `);
  951. }
  952. const rows = this.stmts.getRoutingManifest.all(limit) as Array<{
  953. url: string; handler: string; handler_file: string; handler_line: number; handler_kind: string;
  954. }>;
  955. // Drop test/generated handlers — same hygiene as elsewhere.
  956. const generated = this.getGeneratedPathsAmong(rows.map(r => r.handler_file));
  957. const filtered = rows.filter(r => !isLowValueFile(r.handler_file, generated));
  958. if (filtered.length < 3) return null;
  959. // Identify the file holding the most handlers (the "primary handler file").
  960. const fileCounts = new Map<string, number>();
  961. for (const r of filtered) {
  962. fileCounts.set(r.handler_file, (fileCounts.get(r.handler_file) ?? 0) + 1);
  963. }
  964. let topHandlerFile: string | null = null;
  965. let topHandlerFileCount = 0;
  966. for (const [file, count] of fileCounts) {
  967. if (count > topHandlerFileCount) {
  968. topHandlerFile = file;
  969. topHandlerFileCount = count;
  970. }
  971. }
  972. return {
  973. entries: filtered.map(r => ({
  974. url: r.url,
  975. handler: r.handler,
  976. handlerFile: r.handler_file,
  977. handlerLine: r.handler_line,
  978. handlerKind: r.handler_kind,
  979. })),
  980. topHandlerFile,
  981. topHandlerFileCount,
  982. totalRoutes: filtered.length,
  983. };
  984. }
  985. /**
  986. * Get all nodes of a specific kind
  987. */
  988. getNodesByKind(kind: NodeKind): Node[] {
  989. if (!this.stmts.getNodesByKind) {
  990. this.stmts.getNodesByKind = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
  991. }
  992. const rows = this.stmts.getNodesByKind.all(kind) as NodeRow[];
  993. return rows.map(rowToNode);
  994. }
  995. /**
  996. * Stream every node of a kind one at a time (lazy) instead of materializing
  997. * them all like {@link getNodesByKind}. For unbounded kinds (`function`,
  998. * `method`) on a symbol-dense project the full array is gigabytes; the
  999. * dynamic-edge synthesizers only scan-and-filter, so they iterate to keep
  1000. * memory O(1) in the node count rather than O(nodes) (#610).
  1001. */
  1002. *iterateNodesByKind(kind: NodeKind): IterableIterator<Node> {
  1003. // Fresh statement per call (not a cached one): an iterator holds an open
  1004. // cursor, so a shared statement would conflict across overlapping scans.
  1005. const stmt = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
  1006. for (const row of stmt.iterate(kind)) {
  1007. yield rowToNode(row as NodeRow);
  1008. }
  1009. }
  1010. /**
  1011. * Get all nodes in the database
  1012. */
  1013. getAllNodes(): Node[] {
  1014. const rows = this.db.prepare('SELECT * FROM nodes').all() as NodeRow[];
  1015. return rows.map(rowToNode);
  1016. }
  1017. /**
  1018. * Stream nodes of one language whose `decorators` JSON array contains
  1019. * `decorator`. The LIKE on the JSON text is a cheap index-free pre-filter
  1020. * (a decorator name can appear as a substring of another), so callers must
  1021. * still exact-check `node.decorators.includes(decorator)`. Exists so the
  1022. * kotlin expect/actual synthesizer never materializes the whole node table
  1023. * the way `getAllNodes().filter(...)` did — that array alone OOM'd Node's
  1024. * default heap on a 2M-node graph (#1212).
  1025. */
  1026. *iterateNodesByLanguageWithDecorator(language: Language, decorator: string): IterableIterator<Node> {
  1027. // Fresh statement per call — an iterator holds an open cursor (see
  1028. // iterateNodesByKind).
  1029. const stmt = this.db.prepare(
  1030. "SELECT * FROM nodes WHERE language = ? AND decorators LIKE '%' || ? || '%'"
  1031. );
  1032. for (const row of stmt.iterate(language, `"${decorator}"`)) {
  1033. yield rowToNode(row as NodeRow);
  1034. }
  1035. }
  1036. /**
  1037. * Distinct languages present in the files table. One indexed aggregate —
  1038. * lets the dynamic-edge synthesizers skip passes for languages the project
  1039. * doesn't contain at all (a Kotlin pass has no work on a pure-C repo), so
  1040. * their cost is zero rather than a full-graph scan that finds nothing (#1212).
  1041. */
  1042. getDistinctFileLanguages(): Set<string> {
  1043. const rows = this.db.prepare('SELECT DISTINCT language FROM files').all() as Array<{ language: string }>;
  1044. return new Set(rows.map((r) => r.language));
  1045. }
  1046. /**
  1047. * Get nodes by exact name match (uses idx_nodes_name index)
  1048. */
  1049. getNodesByName(name: string): Node[] {
  1050. if (!this.stmts.getNodesByName) {
  1051. this.stmts.getNodesByName = this.db.prepare('SELECT * FROM nodes WHERE name = ?');
  1052. }
  1053. const rows = this.stmts.getNodesByName.all(name) as NodeRow[];
  1054. return rows.map(rowToNode);
  1055. }
  1056. /**
  1057. * Nodes whose name starts with `prefix`, by index range scan (a LIKE would
  1058. * skip idx_nodes_name under SQLite's default case-insensitive LIKE).
  1059. */
  1060. getNodesByNamePrefix(prefix: string, limit = 20): Node[] {
  1061. if (!this.stmts.getNodesByNamePrefix) {
  1062. this.stmts.getNodesByNamePrefix = this.db.prepare(
  1063. 'SELECT * FROM nodes WHERE name >= ? AND name < ? ORDER BY name LIMIT ?'
  1064. );
  1065. }
  1066. const rows = this.stmts.getNodesByNamePrefix.all(prefix, prefix + '￿', limit) as NodeRow[];
  1067. return rows.map(rowToNode);
  1068. }
  1069. /**
  1070. * Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
  1071. */
  1072. getNodesByQualifiedNameExact(qualifiedName: string): Node[] {
  1073. if (!this.stmts.getNodesByQualifiedNameExact) {
  1074. this.stmts.getNodesByQualifiedNameExact = this.db.prepare(
  1075. 'SELECT * FROM nodes WHERE qualified_name = ?'
  1076. );
  1077. }
  1078. const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName) as NodeRow[];
  1079. return rows.map(rowToNode);
  1080. }
  1081. /**
  1082. * Get nodes by lowercase name match (uses idx_nodes_lower_name expression index)
  1083. */
  1084. getNodesByLowerName(lowerName: string): Node[] {
  1085. if (!this.stmts.getNodesByLowerName) {
  1086. this.stmts.getNodesByLowerName = this.db.prepare(
  1087. 'SELECT * FROM nodes WHERE lower(name) = ?'
  1088. );
  1089. }
  1090. const rows = this.stmts.getNodesByLowerName.all(lowerName) as NodeRow[];
  1091. return rows.map(rowToNode);
  1092. }
  1093. /**
  1094. * Search nodes by name using FTS with fallback to LIKE for better matching
  1095. *
  1096. * Search strategy:
  1097. * 1. Try FTS5 prefix match (query*) for word-start matching
  1098. * 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
  1099. * 3. Score results based on match quality
  1100. */
  1101. searchNodes(query: string, options: SearchOptions = {}): SearchResult[] {
  1102. const { limit = 100, offset = 0 } = options;
  1103. // Parse field-qualified bits out of the raw query (kind:, lang:,
  1104. // path:, name:). Anything not recognised stays in `text` and goes
  1105. // to FTS unchanged. Filters compose with the SearchOptions arg —
  1106. // both are applied (intersection-style).
  1107. const parsed = parseQuery(query);
  1108. const mergedKinds =
  1109. parsed.kinds.length > 0
  1110. ? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
  1111. : options.kinds;
  1112. const mergedLanguages =
  1113. parsed.languages.length > 0
  1114. ? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
  1115. : options.languages;
  1116. const pathFilters = parsed.pathFilters;
  1117. const nameFilters = parsed.nameFilters;
  1118. // The text portion drives FTS/LIKE; if all the user typed was
  1119. // filters (`kind:function`), we still need *some* candidate set,
  1120. // so synthesise an empty-text path that returns everything matching
  1121. // the filters.
  1122. const text = parsed.text;
  1123. const kinds = mergedKinds;
  1124. const languages = mergedLanguages;
  1125. // First try FTS5 with prefix matching
  1126. let results = text
  1127. ? this.searchNodesFTS(text, { kinds, languages, limit, offset })
  1128. // Over-fetch by 5× when running filter-only (no text). The
  1129. // post-scoring path: + name: filters can be very selective, so
  1130. // a smaller multiplier risks returning fewer than `limit`
  1131. // results despite the DB having plenty of matches.
  1132. : this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
  1133. // If no FTS results, try LIKE-based substring search
  1134. if (results.length === 0 && text.length >= 2) {
  1135. results = this.searchNodesLike(text, { kinds, languages, limit, offset });
  1136. }
  1137. // Final fuzzy fallback: scan all known names and keep those within
  1138. // a tight Levenshtein distance. Only fires when both FTS and LIKE
  1139. // returned nothing AND there's a text portion long enough to be
  1140. // worth fuzzing (1-char queries would match too much).
  1141. if (results.length === 0 && text.length >= 3) {
  1142. results = this.searchNodesFuzzy(text, { kinds, languages, limit });
  1143. }
  1144. // Supplement: ensure exact name matches are always candidates.
  1145. // BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
  1146. // compound names (e.g. "getBeanDescriptor") in large codebases,
  1147. // pushing them past the FTS fetch limit before post-hoc scoring can help.
  1148. // Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
  1149. // prefix=20) actually differentiates them after rescoring.
  1150. if (results.length > 0 && query) {
  1151. const existingIds = new Set(results.map(r => r.node.id));
  1152. const maxFtsScore = Math.max(...results.map(r => r.score));
  1153. const terms = query.split(/\s+/).filter(t => t.length >= 2);
  1154. for (const term of terms) {
  1155. let sql = 'SELECT * FROM nodes WHERE name = ? COLLATE NOCASE';
  1156. const params: (string | number)[] = [term];
  1157. if (kinds && kinds.length > 0) {
  1158. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1159. params.push(...kinds);
  1160. }
  1161. if (languages && languages.length > 0) {
  1162. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1163. params.push(...languages);
  1164. }
  1165. sql += ' LIMIT 20';
  1166. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1167. for (const row of rows) {
  1168. if (!existingIds.has(row.id)) {
  1169. results.push({ node: rowToNode(row), score: maxFtsScore });
  1170. existingIds.add(row.id);
  1171. }
  1172. }
  1173. }
  1174. }
  1175. // Apply multi-signal scoring
  1176. if (results.length > 0 && (text || query)) {
  1177. const scoringQuery = text || query;
  1178. results = results.map(r => ({
  1179. ...r,
  1180. score: r.score
  1181. + kindBonus(r.node.kind)
  1182. + scorePathRelevance(r.node.filePath, scoringQuery, this.projectNameTokens)
  1183. + nameMatchBonus(r.node.name, scoringQuery),
  1184. }));
  1185. results.sort((a, b) => b.score - a.score);
  1186. // Trim to requested limit after rescoring
  1187. if (results.length > limit) {
  1188. results = results.slice(0, limit);
  1189. }
  1190. }
  1191. // Apply path: + name: filters AFTER scoring. Scoring already uses
  1192. // path/name as a soft signal; the explicit filters here are a hard
  1193. // gate. Done last so the FTS limit fetched plenty of candidates to
  1194. // narrow from.
  1195. if (pathFilters.length > 0) {
  1196. const lowered = pathFilters.map((p) => p.toLowerCase());
  1197. results = results.filter((r) => {
  1198. const fp = r.node.filePath.toLowerCase();
  1199. return lowered.some((p) => fp.includes(p));
  1200. });
  1201. }
  1202. if (nameFilters.length > 0) {
  1203. const lowered = nameFilters.map((n) => n.toLowerCase());
  1204. results = results.filter((r) => {
  1205. const nm = r.node.name.toLowerCase();
  1206. return lowered.some((n) => nm.includes(n));
  1207. });
  1208. }
  1209. return results;
  1210. }
  1211. /**
  1212. * Match-everything path used when the user supplied only field
  1213. * filters (`kind:function lang:typescript`) with no text. Returns
  1214. * candidates ordered by name; the caller's filter pass narrows to
  1215. * what was asked for.
  1216. */
  1217. private searchAllByFilters(options: {
  1218. kinds?: NodeKind[];
  1219. languages?: Language[];
  1220. limit: number;
  1221. }): SearchResult[] {
  1222. const { kinds, languages, limit } = options;
  1223. let sql = 'SELECT * FROM nodes WHERE 1=1';
  1224. const params: (string | number)[] = [];
  1225. if (kinds && kinds.length > 0) {
  1226. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1227. params.push(...kinds);
  1228. }
  1229. if (languages && languages.length > 0) {
  1230. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1231. params.push(...languages);
  1232. }
  1233. sql += ' ORDER BY name LIMIT ?';
  1234. params.push(limit);
  1235. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1236. return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
  1237. }
  1238. /**
  1239. * Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
  1240. * sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
  1241. * `getUssr` finds `getUser` but `process` doesn't match `prosody`.
  1242. * Bounded edit distance keeps each comparison cheap; the per-query
  1243. * scan is O(distinct-name-count) which is far smaller than total
  1244. * node count on any real codebase.
  1245. */
  1246. private searchNodesFuzzy(
  1247. text: string,
  1248. options: { kinds?: NodeKind[]; languages?: Language[]; limit: number }
  1249. ): SearchResult[] {
  1250. const { kinds, languages, limit } = options;
  1251. const lowered = text.toLowerCase();
  1252. const maxDist = lowered.length <= 4 ? 1 : 2;
  1253. // Pull the distinct name list once. The set is cached on QueryBuilder
  1254. // by getAllNodeNames(); even on a 200k-node project the distinct
  1255. // name set is typically O(10k) because most names repeat. The
  1256. // candidate-cap below bounds memory regardless.
  1257. const allNames = this.getAllNodeNames();
  1258. const candidates: Array<{ name: string; dist: number }> = [];
  1259. for (const name of allNames) {
  1260. const dist = boundedEditDistance(name.toLowerCase(), lowered, maxDist);
  1261. if (dist <= maxDist) candidates.push({ name, dist });
  1262. }
  1263. candidates.sort((a, b) => a.dist - b.dist);
  1264. // Cap the per-name follow-up queries. Each survivor triggers a
  1265. // separate `SELECT * FROM nodes WHERE name = ?`; without this cap
  1266. // a project with many similar names (`getUser1`, `getUser2`...)
  1267. // could fan out far beyond `limit` queries before the inner-loop
  1268. // limit kicks in.
  1269. const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
  1270. const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
  1271. const results: SearchResult[] = [];
  1272. const seen = new Set<string>();
  1273. for (const c of cappedCandidates) {
  1274. if (results.length >= limit) break;
  1275. let sql = 'SELECT * FROM nodes WHERE name = ?';
  1276. const params: (string | number)[] = [c.name];
  1277. if (kinds && kinds.length > 0) {
  1278. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1279. params.push(...kinds);
  1280. }
  1281. if (languages && languages.length > 0) {
  1282. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1283. params.push(...languages);
  1284. }
  1285. sql += ' LIMIT 5';
  1286. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1287. for (const row of rows) {
  1288. if (seen.has(row.id)) continue;
  1289. seen.add(row.id);
  1290. // Lower the score for each edit step away from the query so
  1291. // exact-match fallbacks (dist 0) outrank dist-2 typos.
  1292. results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
  1293. if (results.length >= limit) break;
  1294. }
  1295. }
  1296. return results;
  1297. }
  1298. /**
  1299. * FTS5 search with prefix matching
  1300. */
  1301. private searchNodesFTS(query: string, options: SearchOptions): SearchResult[] {
  1302. const { kinds, languages, limit = 100, offset = 0 } = options;
  1303. // Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
  1304. // Escape special FTS5 characters and add prefix wildcard.
  1305. //
  1306. // `::` is a qualifier separator in Rust/C++/Ruby, not a token char,
  1307. // so treat it as whitespace before the strip step. Otherwise queries
  1308. // like `stage_apply::run` collapse to `stage_applyrun` (the colons
  1309. // are stripped without splitting) and find nothing. See #173.
  1310. const ftsQuery = query
  1311. .replace(/::/g, ' ') // Rust/C++/Ruby qualifier separator
  1312. .replace(/['"*():^]/g, '') // Remove FTS5 special chars
  1313. .split(/\s+/)
  1314. .filter(term => term.length > 0)
  1315. // Strip FTS5 boolean operators to prevent query manipulation
  1316. .filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
  1317. .map(term => `"${term}"*`) // Prefix match each term
  1318. .join(' OR ');
  1319. if (!ftsQuery) {
  1320. return [];
  1321. }
  1322. // BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
  1323. // Heavy name weight ensures exact/prefix name matches rank above incidental
  1324. // mentions in long docstrings or qualified names of nested symbols.
  1325. // Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
  1326. // nameMatchBonus) can promote results that BM25 alone undervalues.
  1327. const ftsLimit = Math.max(limit * 5, 100);
  1328. let sql = `
  1329. SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
  1330. FROM nodes_fts
  1331. JOIN nodes ON nodes_fts.id = nodes.id
  1332. WHERE nodes_fts MATCH ?
  1333. `;
  1334. const params: (string | number)[] = [ftsQuery];
  1335. if (kinds && kinds.length > 0) {
  1336. sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
  1337. params.push(...kinds);
  1338. }
  1339. if (languages && languages.length > 0) {
  1340. sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
  1341. params.push(...languages);
  1342. }
  1343. sql += ' ORDER BY score LIMIT ? OFFSET ?';
  1344. params.push(ftsLimit, offset);
  1345. try {
  1346. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1347. return rows.map((row) => ({
  1348. node: rowToNode(row),
  1349. score: Math.abs(row.score), // bm25 returns negative scores
  1350. }));
  1351. } catch {
  1352. // FTS query failed, return empty
  1353. return [];
  1354. }
  1355. }
  1356. /**
  1357. * LIKE-based substring search for cases where FTS doesn't match
  1358. * Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
  1359. */
  1360. private searchNodesLike(query: string, options: SearchOptions): SearchResult[] {
  1361. const { kinds, languages, limit = 100, offset = 0 } = options;
  1362. let sql = `
  1363. SELECT nodes.*,
  1364. CASE
  1365. WHEN name = ? THEN 1.0
  1366. WHEN name LIKE ? THEN 0.9
  1367. WHEN name LIKE ? THEN 0.8
  1368. WHEN qualified_name LIKE ? THEN 0.7
  1369. ELSE 0.5
  1370. END as score
  1371. FROM nodes
  1372. WHERE (
  1373. name LIKE ? OR
  1374. qualified_name LIKE ? OR
  1375. name LIKE ?
  1376. )
  1377. `;
  1378. // Pattern variants for better matching
  1379. const exactMatch = query;
  1380. const startsWith = `${query}%`;
  1381. const contains = `%${query}%`;
  1382. const params: (string | number)[] = [
  1383. exactMatch, // Exact match score
  1384. startsWith, // Starts with score
  1385. contains, // Contains score
  1386. contains, // Qualified name score
  1387. contains, // WHERE: name contains
  1388. contains, // WHERE: qualified_name contains
  1389. startsWith, // WHERE: name starts with
  1390. ];
  1391. if (kinds && kinds.length > 0) {
  1392. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1393. params.push(...kinds);
  1394. }
  1395. if (languages && languages.length > 0) {
  1396. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1397. params.push(...languages);
  1398. }
  1399. sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
  1400. params.push(limit, offset);
  1401. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1402. return rows.map((row) => ({
  1403. node: rowToNode(row),
  1404. score: row.score,
  1405. }));
  1406. }
  1407. /**
  1408. * Find nodes by exact name match
  1409. *
  1410. * Used for hybrid search - looks up symbols by exact name or case-insensitive match.
  1411. * Returns high-confidence matches for known symbol names extracted from query.
  1412. *
  1413. * @param names - Array of symbol names to look up
  1414. * @param options - Search options (kinds, languages, limit)
  1415. * @returns SearchResult array with exact matches scored at 1.0
  1416. */
  1417. findNodesByExactName(names: string[], options: SearchOptions = {}): SearchResult[] {
  1418. if (names.length === 0) return [];
  1419. const { kinds, languages, limit = 50 } = options;
  1420. // Two-pass approach to handle common names (e.g., "run" has 40+ matches):
  1421. // Pass 1: Find which files contain distinctive (rare) symbols from the query.
  1422. // Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
  1423. // Pass 1: Find files containing each queried name, identify distinctive names
  1424. const nameToFiles = new Map<string, Set<string>>();
  1425. for (const name of names) {
  1426. let sql = 'SELECT DISTINCT file_path FROM nodes WHERE name COLLATE NOCASE = ?';
  1427. const params: (string | number)[] = [name];
  1428. if (kinds && kinds.length > 0) {
  1429. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1430. params.push(...kinds);
  1431. }
  1432. sql += ' LIMIT 100';
  1433. const rows = this.db.prepare(sql).all(...params) as { file_path: string }[];
  1434. nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
  1435. }
  1436. // Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
  1437. const distinctiveFiles = new Set<string>();
  1438. for (const [, files] of nameToFiles) {
  1439. if (files.size > 0 && files.size < 10) {
  1440. for (const f of files) distinctiveFiles.add(f);
  1441. }
  1442. }
  1443. // Pass 2: Query each name with per-name limit, scoring by co-location
  1444. const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
  1445. const allResults: SearchResult[] = [];
  1446. const seenIds = new Set<string>();
  1447. for (const name of names) {
  1448. let sql = `
  1449. SELECT nodes.*, 1.0 as score
  1450. FROM nodes
  1451. WHERE name COLLATE NOCASE = ?
  1452. `;
  1453. const params: (string | number)[] = [name];
  1454. if (kinds && kinds.length > 0) {
  1455. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1456. params.push(...kinds);
  1457. }
  1458. if (languages && languages.length > 0) {
  1459. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1460. params.push(...languages);
  1461. }
  1462. // Fetch enough to find co-located results among common names
  1463. sql += ' LIMIT ?';
  1464. params.push(Math.max(perNameLimit * 3, 50));
  1465. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1466. const nameResults: SearchResult[] = [];
  1467. for (const row of rows) {
  1468. const node = rowToNode(row);
  1469. if (seenIds.has(node.id)) continue;
  1470. // Boost results in files that also contain distinctive symbols
  1471. const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
  1472. nameResults.push({ node, score: row.score + coLocationBoost });
  1473. }
  1474. // Sort by score (co-located first), take per-name limit
  1475. nameResults.sort((a, b) => b.score - a.score);
  1476. for (const r of nameResults.slice(0, perNameLimit)) {
  1477. seenIds.add(r.node.id);
  1478. allResults.push(r);
  1479. }
  1480. }
  1481. // Sort all results by score so co-located results bubble up
  1482. allResults.sort((a, b) => b.score - a.score);
  1483. return allResults.slice(0, limit);
  1484. }
  1485. /**
  1486. * Find nodes whose name contains a substring (LIKE-based).
  1487. * Useful for CamelCase-part matching where FTS fails because
  1488. * e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
  1489. *
  1490. * Results are ordered by name length (shorter = more likely to be the core type).
  1491. */
  1492. findNodesByNameSubstring(
  1493. substring: string,
  1494. options: SearchOptions & { excludePrefix?: boolean } = {}
  1495. ): SearchResult[] {
  1496. const { kinds, languages, limit = 30, excludePrefix } = options;
  1497. let sql = `
  1498. SELECT nodes.*, 1.0 as score
  1499. FROM nodes
  1500. WHERE name LIKE ?
  1501. `;
  1502. const params: (string | number)[] = [`%${substring}%`];
  1503. // Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
  1504. if (excludePrefix) {
  1505. sql += ` AND name NOT LIKE ?`;
  1506. params.push(`${substring}%`);
  1507. }
  1508. if (kinds && kinds.length > 0) {
  1509. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1510. params.push(...kinds);
  1511. }
  1512. if (languages && languages.length > 0) {
  1513. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1514. params.push(...languages);
  1515. }
  1516. sql += ' ORDER BY length(name) ASC LIMIT ?';
  1517. params.push(limit);
  1518. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1519. return rows.map((row) => ({
  1520. node: rowToNode(row),
  1521. score: row.score,
  1522. }));
  1523. }
  1524. // ===========================================================================
  1525. // Edge Operations
  1526. // ===========================================================================
  1527. /**
  1528. * Insert a new edge
  1529. */
  1530. insertEdge(edge: Edge): void {
  1531. if (!this.stmts.insertEdge) {
  1532. this.stmts.insertEdge = this.db.prepare(`
  1533. INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
  1534. VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
  1535. `);
  1536. }
  1537. this.stmts.insertEdge.run({
  1538. source: edge.source,
  1539. target: edge.target,
  1540. kind: edge.kind,
  1541. metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
  1542. line: edge.line ?? null,
  1543. col: edge.column ?? null,
  1544. provenance: edge.provenance ?? null,
  1545. });
  1546. }
  1547. /**
  1548. * Insert multiple edges in a transaction
  1549. */
  1550. insertEdges(edges: Edge[]): void {
  1551. if (edges.length === 0) return;
  1552. this.db.transaction(() => {
  1553. const endpointIds = new Set<string>();
  1554. for (const edge of edges) {
  1555. endpointIds.add(edge.source);
  1556. endpointIds.add(edge.target);
  1557. }
  1558. const existingNodeIds = this.getExistingNodeIds([...endpointIds]);
  1559. const rows: unknown[][] = [];
  1560. for (const edge of edges) {
  1561. if (!existingNodeIds.has(edge.source) || !existingNodeIds.has(edge.target)) {
  1562. continue;
  1563. }
  1564. rows.push([
  1565. edge.source,
  1566. edge.target,
  1567. edge.kind,
  1568. edge.metadata ? JSON.stringify(edge.metadata) : null,
  1569. edge.line ?? null,
  1570. edge.column ?? null,
  1571. edge.provenance ?? null,
  1572. ]);
  1573. }
  1574. this.runBatched(
  1575. 'insertEdges',
  1576. 'INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance) VALUES ',
  1577. '(?,?,?,?,?,?,?)',
  1578. rows
  1579. );
  1580. })();
  1581. }
  1582. /**
  1583. * Delete all edges from a source node
  1584. */
  1585. deleteEdgesBySource(sourceId: string): void {
  1586. if (!this.stmts.deleteEdgesBySource) {
  1587. this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
  1588. }
  1589. this.stmts.deleteEdgesBySource.run(sourceId);
  1590. }
  1591. /**
  1592. * Get outgoing edges from a node
  1593. */
  1594. getOutgoingEdges(sourceId: string, kinds?: EdgeKind[], provenance?: string): Edge[] {
  1595. if ((kinds && kinds.length > 0) || provenance) {
  1596. let sql = 'SELECT * FROM edges WHERE source = ?';
  1597. const params: (string | number)[] = [sourceId];
  1598. if (kinds && kinds.length > 0) {
  1599. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1600. params.push(...kinds);
  1601. }
  1602. if (provenance) {
  1603. sql += ' AND provenance = ?';
  1604. params.push(provenance);
  1605. }
  1606. const rows = this.db.prepare(sql).all(...params) as EdgeRow[];
  1607. return rows.map(rowToEdge);
  1608. }
  1609. if (!this.stmts.getEdgesBySource) {
  1610. this.stmts.getEdgesBySource = this.db.prepare('SELECT * FROM edges WHERE source = ?');
  1611. }
  1612. const rows = this.stmts.getEdgesBySource.all(sourceId) as EdgeRow[];
  1613. return rows.map(rowToEdge);
  1614. }
  1615. /**
  1616. * Get incoming edges to a node
  1617. */
  1618. getIncomingEdges(targetId: string, kinds?: EdgeKind[]): Edge[] {
  1619. if (kinds && kinds.length > 0) {
  1620. const sql = `SELECT * FROM edges WHERE target = ? AND kind IN (${kinds.map(() => '?').join(',')})`;
  1621. const rows = this.db.prepare(sql).all(targetId, ...kinds) as EdgeRow[];
  1622. return rows.map(rowToEdge);
  1623. }
  1624. if (!this.stmts.getEdgesByTarget) {
  1625. this.stmts.getEdgesByTarget = this.db.prepare('SELECT * FROM edges WHERE target = ?');
  1626. }
  1627. const rows = this.stmts.getEdgesByTarget.all(targetId) as EdgeRow[];
  1628. return rows.map(rowToEdge);
  1629. }
  1630. /**
  1631. * Find all edges where both source and target are in the given node set.
  1632. * Useful for recovering inter-node connectivity after BFS.
  1633. */
  1634. findEdgesBetweenNodes(nodeIds: string[], kinds?: EdgeKind[]): Edge[] {
  1635. if (nodeIds.length === 0) return [];
  1636. const idsJson = JSON.stringify(nodeIds);
  1637. let sql = `SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?)) AND target IN (SELECT value FROM json_each(?))`;
  1638. const params: string[] = [idsJson, idsJson];
  1639. if (kinds && kinds.length > 0) {
  1640. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1641. params.push(...kinds);
  1642. }
  1643. const rows = this.db.prepare(sql).all(...params) as EdgeRow[];
  1644. return rows.map(rowToEdge);
  1645. }
  1646. /**
  1647. * Distinct file paths that DEPEND ON `filePath`: every file containing a
  1648. * symbol with a cross-file edge (any kind except `contains`) into a symbol
  1649. * of this file. This is the file-level projection of the symbol dependency
  1650. * graph and the basis for blast-radius / `affected` test selection.
  1651. *
  1652. * It deliberately does NOT restrict to `imports` edges. In this graph an
  1653. * `imports` edge connects a file to its own local import declarations
  1654. * (it is always same-file), so an imports-only lookup returns zero
  1655. * cross-file dependents for every file. The real cross-file dependency
  1656. * signal is the resolved call/reference graph — calls, references,
  1657. * instantiates, extends, implements, overrides, type_of, returns,
  1658. * decorates — exactly what {@link GraphTraverser.getImpactRadius} traverses.
  1659. * `contains` is excluded: a parent containing a symbol does not *depend* on
  1660. * it. One indexed query (idx_nodes_file_path + idx_edges_target_kind).
  1661. */
  1662. getDependentFilePaths(filePath: string): string[] {
  1663. const sql = `SELECT DISTINCT src.file_path AS fp
  1664. FROM edges e
  1665. JOIN nodes tgt ON tgt.id = e.target
  1666. JOIN nodes src ON src.id = e.source
  1667. WHERE tgt.file_path = ?
  1668. AND e.kind != 'contains'
  1669. AND src.file_path != ?`;
  1670. const rows = this.db.prepare(sql).all(filePath, filePath) as Array<{ fp: string }>;
  1671. return rows.map((r) => r.fp);
  1672. }
  1673. /**
  1674. * Distinct file paths that `filePath` DEPENDS ON — the inverse of
  1675. * {@link getDependentFilePaths}: every file containing a symbol that a
  1676. * symbol of this file has a cross-file edge into. Same edge-kind rules
  1677. * (all kinds except `contains`); same reason imports-only is insufficient.
  1678. */
  1679. getDependencyFilePaths(filePath: string): string[] {
  1680. const sql = `SELECT DISTINCT tgt.file_path AS fp
  1681. FROM edges e
  1682. JOIN nodes src ON src.id = e.source
  1683. JOIN nodes tgt ON tgt.id = e.target
  1684. WHERE src.file_path = ?
  1685. AND e.kind != 'contains'
  1686. AND tgt.file_path != ?`;
  1687. const rows = this.db.prepare(sql).all(filePath, filePath) as Array<{ fp: string }>;
  1688. return rows.map((r) => r.fp);
  1689. }
  1690. /**
  1691. * Cross-file edges whose TARGET is a node in `filePath` and whose SOURCE is a
  1692. * node in a *different* file, paired with the target node's (name, kind) so a
  1693. * caller can re-resolve the edge to the re-indexed target's new ID (node IDs
  1694. * are `sha256(filePath:kind:name:line)`, so any line shift in the callee file
  1695. * changes target IDs and a naive re-insert by old ID silently drops them).
  1696. * Used by `storeExtractionResult` to preserve incoming edges across a file
  1697. * re-index (issue #899). Same edge-kind rules as
  1698. * {@link getDependentFilePaths}: all kinds except `contains`.
  1699. */
  1700. getCrossFileIncomingEdgesWithTarget(
  1701. filePath: string
  1702. ): Array<Edge & { targetName: string; targetKind: NodeKind; sourceFilePath: string; sourceLanguage: Language }> {
  1703. const sql = `SELECT e.*, tgt.name AS target_name, tgt.kind AS target_kind,
  1704. src.file_path AS source_file_path, src.language AS source_language
  1705. FROM edges e
  1706. JOIN nodes tgt ON tgt.id = e.target
  1707. JOIN nodes src ON src.id = e.source
  1708. WHERE tgt.file_path = ?
  1709. AND e.kind != 'contains'
  1710. AND src.file_path != ?`;
  1711. const rows = this.db.prepare(sql).all(filePath, filePath) as Array<
  1712. EdgeRow & { target_name: string; target_kind: NodeKind; source_file_path: string; source_language: Language }
  1713. >;
  1714. return rows.map(row => ({
  1715. ...rowToEdge(row),
  1716. targetName: row.target_name,
  1717. targetKind: row.target_kind,
  1718. sourceFilePath: row.source_file_path,
  1719. sourceLanguage: row.source_language,
  1720. }));
  1721. }
  1722. // ===========================================================================
  1723. // File Operations
  1724. // ===========================================================================
  1725. /**
  1726. * Insert or update a file record
  1727. */
  1728. upsertFile(file: FileRecord): void {
  1729. if (!this.stmts.upsertFile) {
  1730. this.stmts.upsertFile = this.db.prepare(`
  1731. INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors, generated)
  1732. VALUES (@path, @contentHash, @language, @size, @modifiedAt, @indexedAt, @nodeCount, @errors, @generated)
  1733. ON CONFLICT(path) DO UPDATE SET
  1734. content_hash = @contentHash,
  1735. language = @language,
  1736. size = @size,
  1737. modified_at = @modifiedAt,
  1738. indexed_at = @indexedAt,
  1739. node_count = @nodeCount,
  1740. errors = @errors,
  1741. generated = @generated
  1742. `);
  1743. }
  1744. this.stmts.upsertFile.run({
  1745. path: file.path,
  1746. contentHash: file.contentHash,
  1747. language: file.language,
  1748. size: file.size,
  1749. modifiedAt: file.modifiedAt,
  1750. indexedAt: file.indexedAt,
  1751. nodeCount: file.nodeCount,
  1752. errors: file.errors ? JSON.stringify(file.errors) : null,
  1753. // The upsert always REWRITES the flag: a file that loses its banner in an
  1754. // edit must lose the flag on the next sync, not keep a stale 1.
  1755. generated: file.generated ? 1 : 0,
  1756. });
  1757. }
  1758. /**
  1759. * Which of `filePaths` the index flagged as tool-generated (schema v9+).
  1760. *
  1761. * Bounded-lookup by design: every consumer already holds a short candidate
  1762. * list (a ranked file group, an FTS result page, a LIMIT-20 aggregate), so
  1763. * this stays a partial-index probe over a handful of paths — no whole-repo
  1764. * set to materialize, and no cache to invalidate, which means a ranking call
  1765. * can never serve a verdict the last sync already replaced.
  1766. *
  1767. * Returns ONLY the content/index signal; callers union it with
  1768. * {@link isGeneratedFile} so pre-v9 databases (column present, all zeros
  1769. * until a re-index) keep the path-only behavior rather than regressing.
  1770. */
  1771. getGeneratedPathsAmong(filePaths: Iterable<string>): Set<string> {
  1772. const unique = [...new Set(filePaths)];
  1773. const found = new Set<string>();
  1774. if (unique.length === 0) return found;
  1775. for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  1776. const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  1777. const placeholders = chunk.map(() => '?').join(',');
  1778. const rows = this.db
  1779. .prepare(`SELECT path FROM files WHERE generated = 1 AND path IN (${placeholders})`)
  1780. .all(...chunk) as Array<{ path: string }>;
  1781. for (const row of rows) found.add(row.path);
  1782. }
  1783. return found;
  1784. }
  1785. /**
  1786. * A reusable `(path) => boolean` over a bounded candidate list, unioning the
  1787. * indexed flag with the path convention. This is the shape every ranking
  1788. * comparator wants: one query up front, then O(1) per comparison.
  1789. */
  1790. generatedPredicateFor(filePaths: Iterable<string>): (filePath: string) => boolean {
  1791. const flagged = this.getGeneratedPathsAmong(filePaths);
  1792. return (filePath: string) => flagged.has(filePath) || isGeneratedFile(filePath);
  1793. }
  1794. /** How many indexed files carry the generated flag. Surfaced by `status`. */
  1795. countGeneratedFiles(): number {
  1796. const row = this.db
  1797. .prepare('SELECT COUNT(*) AS n FROM files WHERE generated = 1')
  1798. .get() as { n: number } | undefined;
  1799. return row?.n ?? 0;
  1800. }
  1801. /**
  1802. * Delete a file record and its nodes
  1803. */
  1804. deleteFile(filePath: string): void {
  1805. this.db.transaction(() => {
  1806. this.deleteNodesByFile(filePath);
  1807. if (!this.stmts.deleteFile) {
  1808. this.stmts.deleteFile = this.db.prepare('DELETE FROM files WHERE path = ?');
  1809. }
  1810. this.stmts.deleteFile.run(filePath);
  1811. })();
  1812. }
  1813. /**
  1814. * Get a file record by path
  1815. */
  1816. getFileByPath(filePath: string): FileRecord | null {
  1817. if (!this.stmts.getFileByPath) {
  1818. this.stmts.getFileByPath = this.db.prepare('SELECT * FROM files WHERE path = ?');
  1819. }
  1820. const row = this.stmts.getFileByPath.get(filePath) as FileRow | undefined;
  1821. return row ? rowToFileRecord(row) : null;
  1822. }
  1823. /**
  1824. * Get all tracked files
  1825. */
  1826. getAllFiles(): FileRecord[] {
  1827. if (!this.stmts.getAllFiles) {
  1828. this.stmts.getAllFiles = this.db.prepare('SELECT * FROM files ORDER BY path');
  1829. }
  1830. const rows = this.stmts.getAllFiles.all() as FileRow[];
  1831. return rows.map(rowToFileRecord);
  1832. }
  1833. /**
  1834. * Most recent index timestamp (ms since epoch) across all tracked files, or
  1835. * null when nothing is indexed yet. One indexed aggregate, no per-row scan. (#329)
  1836. */
  1837. getLastIndexedAt(): number | null {
  1838. const row = this.db
  1839. .prepare('SELECT MAX(indexed_at) AS last FROM files')
  1840. .get() as { last: number | null } | undefined;
  1841. return row?.last ?? null;
  1842. }
  1843. /**
  1844. * Get files that need re-indexing (hash changed)
  1845. */
  1846. getStaleFiles(currentHashes: Map<string, string>): FileRecord[] {
  1847. const files = this.getAllFiles();
  1848. return files.filter((f) => {
  1849. const currentHash = currentHashes.get(f.path);
  1850. return currentHash && currentHash !== f.contentHash;
  1851. });
  1852. }
  1853. // ===========================================================================
  1854. // Unresolved References
  1855. // ===========================================================================
  1856. /**
  1857. * Insert an unresolved reference
  1858. */
  1859. insertUnresolvedRef(ref: UnresolvedReference): void {
  1860. if (!this.stmts.insertUnresolved) {
  1861. this.stmts.insertUnresolved = this.db.prepare(`
  1862. INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language)
  1863. VALUES (@fromNodeId, @referenceName, @referenceKind, @line, @col, @candidates, @filePath, @language)
  1864. `);
  1865. }
  1866. this.stmts.insertUnresolved.run({
  1867. fromNodeId: ref.fromNodeId,
  1868. referenceName: ref.referenceName,
  1869. referenceKind: ref.referenceKind,
  1870. line: ref.line,
  1871. col: ref.column,
  1872. candidates: ref.candidates ? JSON.stringify(ref.candidates) : null,
  1873. filePath: ref.filePath ?? '',
  1874. language: ref.language ?? 'unknown',
  1875. });
  1876. }
  1877. /**
  1878. * Insert multiple unresolved references in a transaction
  1879. */
  1880. insertUnresolvedRefsBatch(refs: UnresolvedReference[]): void {
  1881. if (refs.length === 0) return;
  1882. const insert = this.db.transaction(() => {
  1883. const rows: unknown[][] = [];
  1884. for (const ref of refs) {
  1885. rows.push([
  1886. ref.fromNodeId,
  1887. ref.referenceName,
  1888. ref.referenceKind,
  1889. ref.line,
  1890. ref.column,
  1891. ref.candidates ? JSON.stringify(ref.candidates) : null,
  1892. ref.filePath ?? '',
  1893. ref.language ?? 'unknown',
  1894. ]);
  1895. }
  1896. this.runBatched(
  1897. 'insertUnresolvedRefs',
  1898. 'INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language) VALUES ',
  1899. '(?,?,?,?,?,?,?,?)',
  1900. rows
  1901. );
  1902. });
  1903. insert();
  1904. }
  1905. /**
  1906. * Delete unresolved references from a node
  1907. */
  1908. deleteUnresolvedByNode(nodeId: string): void {
  1909. if (!this.stmts.deleteUnresolvedByNode) {
  1910. this.stmts.deleteUnresolvedByNode = this.db.prepare(
  1911. 'DELETE FROM unresolved_refs WHERE from_node_id = ?'
  1912. );
  1913. }
  1914. this.stmts.deleteUnresolvedByNode.run(nodeId);
  1915. }
  1916. /**
  1917. * Get unresolved references by name (for resolution)
  1918. */
  1919. getUnresolvedByName(name: string): UnresolvedReference[] {
  1920. if (!this.stmts.getUnresolvedByName) {
  1921. this.stmts.getUnresolvedByName = this.db.prepare(
  1922. 'SELECT * FROM unresolved_refs WHERE reference_name = ?'
  1923. );
  1924. }
  1925. const rows = this.stmts.getUnresolvedByName.all(name) as UnresolvedRefRow[];
  1926. return rows.map((row) => ({
  1927. fromNodeId: row.from_node_id,
  1928. referenceName: row.reference_name,
  1929. referenceKind: row.reference_kind as EdgeKind,
  1930. line: row.line,
  1931. column: row.col,
  1932. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  1933. filePath: row.file_path,
  1934. language: row.language as Language,
  1935. rowId: row.id,
  1936. }));
  1937. }
  1938. /**
  1939. * Get all unresolved references
  1940. */
  1941. getUnresolvedReferences(): UnresolvedReference[] {
  1942. const rows = this.db.prepare('SELECT * FROM unresolved_refs').all() as UnresolvedRefRow[];
  1943. return rows.map((row) => ({
  1944. fromNodeId: row.from_node_id,
  1945. referenceName: row.reference_name,
  1946. referenceKind: row.reference_kind as EdgeKind,
  1947. line: row.line,
  1948. column: row.col,
  1949. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  1950. filePath: row.file_path,
  1951. language: row.language as Language,
  1952. rowId: row.id,
  1953. }));
  1954. }
  1955. /**
  1956. * Get the count of PENDING (never-attempted) references without loading
  1957. * them into memory. Rows marked status='failed' — attempted by a completed
  1958. * pass, no match — are excluded: they are not outstanding work, only retry
  1959. * candidates for the #1240 sweep, so they must not trip the #1187 orphan
  1960. * sweep or the `status` pending-refs warning.
  1961. */
  1962. getUnresolvedReferencesCount(): number {
  1963. if (!this.stmts.getUnresolvedCount) {
  1964. this.stmts.getUnresolvedCount = this.db.prepare(
  1965. "SELECT COUNT(*) as count FROM unresolved_refs WHERE status = 'pending'"
  1966. );
  1967. }
  1968. const row = this.stmts.getUnresolvedCount.get() as { count: number };
  1969. return row.count;
  1970. }
  1971. /**
  1972. * Get a batch of PENDING unresolved references using LIMIT/OFFSET
  1973. * pagination. Used to process references in bounded memory chunks; failed
  1974. * rows are excluded so the batched drain loop terminates once every row
  1975. * has been attempted.
  1976. */
  1977. getUnresolvedReferencesBatch(offset: number, limit: number): UnresolvedReference[] {
  1978. if (!this.stmts.getUnresolvedBatch) {
  1979. // ORDER BY rowid is load-bearing for the pipelined resolution loop: it
  1980. // prefetches batch k+1 at OFFSET batch_k.length while batch k's rows are
  1981. // still pending, which is only exact under a stable enumeration. (A plain
  1982. // scan and the status index both return rowid order anyway — this pins
  1983. // it.)
  1984. this.stmts.getUnresolvedBatch = this.db.prepare(
  1985. "SELECT * FROM unresolved_refs WHERE status = 'pending' ORDER BY rowid LIMIT ? OFFSET ?"
  1986. );
  1987. }
  1988. const rows = this.stmts.getUnresolvedBatch.all(limit, offset) as UnresolvedRefRow[];
  1989. return rows.map((row) => ({
  1990. fromNodeId: row.from_node_id,
  1991. referenceName: row.reference_name,
  1992. referenceKind: row.reference_kind as EdgeKind,
  1993. line: row.line,
  1994. column: row.col,
  1995. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  1996. filePath: row.file_path,
  1997. language: row.language as Language,
  1998. rowId: row.id,
  1999. }));
  2000. }
  2001. /**
  2002. * Keyset variant of {@link getUnresolvedReferencesBatch} for the batched
  2003. * resolution loop: seek past the last-seen row id instead of OFFSET-walking.
  2004. * OFFSET reads re-scan the accumulated failed-row prefix on every batch —
  2005. * O(failed rows) per read, measured at 54.6s of the kernel-scale batch loop
  2006. * (§7a.2) — while the seek is O(batch) forever. `id` is the rowid alias, so
  2007. * the enumeration order is identical to the OFFSET reader's.
  2008. */
  2009. getUnresolvedReferencesBatchAfter(afterRowId: number, limit: number): UnresolvedReference[] {
  2010. if (!this.stmts.getUnresolvedBatchAfter) {
  2011. this.stmts.getUnresolvedBatchAfter = this.db.prepare(
  2012. "SELECT * FROM unresolved_refs WHERE status = 'pending' AND id > ? ORDER BY id LIMIT ?"
  2013. );
  2014. }
  2015. const rows = this.stmts.getUnresolvedBatchAfter.all(afterRowId, limit) as UnresolvedRefRow[];
  2016. return rows.map((row) => ({
  2017. fromNodeId: row.from_node_id,
  2018. referenceName: row.reference_name,
  2019. referenceKind: row.reference_kind as EdgeKind,
  2020. line: row.line,
  2021. column: row.col,
  2022. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2023. filePath: row.file_path,
  2024. language: row.language as Language,
  2025. rowId: row.id,
  2026. }));
  2027. }
  2028. /**
  2029. * Get all tracked file paths (lightweight — no full FileRecord objects)
  2030. */
  2031. getAllFilePaths(): string[] {
  2032. if (!this.stmts.getAllFilePaths) {
  2033. this.stmts.getAllFilePaths = this.db.prepare('SELECT path FROM files ORDER BY path');
  2034. }
  2035. const rows = this.stmts.getAllFilePaths.all() as Array<{ path: string }>;
  2036. return rows.map((r) => r.path);
  2037. }
  2038. /**
  2039. * Get all distinct node names (lightweight — just name strings for pre-filtering)
  2040. */
  2041. getAllNodeNames(): string[] {
  2042. if (!this.stmts.getAllNodeNames) {
  2043. this.stmts.getAllNodeNames = this.db.prepare('SELECT DISTINCT name FROM nodes');
  2044. }
  2045. const rows = this.stmts.getAllNodeNames.all() as Array<{ name: string }>;
  2046. return rows.map((r) => r.name);
  2047. }
  2048. /**
  2049. * Stream the distinct node names one row at a time — the incremental
  2050. * counterpart to {@link getAllNodeNames} for callers that need to yield
  2051. * to the event loop mid-scan (resolver cache warm-up on multi-million-node
  2052. * indexes). Fresh statement per call: the iterator holds an open cursor.
  2053. */
  2054. *iterateNodeNames(): IterableIterator<string> {
  2055. const stmt = this.db.prepare('SELECT DISTINCT name FROM nodes');
  2056. for (const row of stmt.iterate()) {
  2057. yield (row as { name: string }).name;
  2058. }
  2059. }
  2060. /**
  2061. * Get unresolved references scoped to specific file paths.
  2062. * Uses the idx_unresolved_file_path index for efficient lookup.
  2063. */
  2064. getUnresolvedReferencesByFiles(filePaths: string[]): UnresolvedReference[] {
  2065. if (filePaths.length === 0) return [];
  2066. // Chunk under SQLite's parameter limit: the first sync of a very large repo
  2067. // passes every changed file here, which an unbounded `IN (...)` would bind
  2068. // as one parameter each — exceeding MAX_VARIABLE_NUMBER and aborting with
  2069. // "too many SQL variables". (#540)
  2070. const rows: UnresolvedRefRow[] = [];
  2071. for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2072. const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2073. const placeholders = chunk.map(() => '?').join(',');
  2074. const chunkRows = this.db
  2075. .prepare(`SELECT * FROM unresolved_refs WHERE status = 'pending' AND file_path IN (${placeholders})`)
  2076. .all(...chunk) as UnresolvedRefRow[];
  2077. rows.push(...chunkRows);
  2078. }
  2079. return rows.map((row) => ({
  2080. fromNodeId: row.from_node_id,
  2081. referenceName: row.reference_name,
  2082. referenceKind: row.reference_kind as EdgeKind,
  2083. line: row.line,
  2084. column: row.col,
  2085. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2086. filePath: row.file_path,
  2087. language: row.language as Language,
  2088. rowId: row.id,
  2089. }));
  2090. }
  2091. /**
  2092. * Delete all unresolved references (after resolution)
  2093. */
  2094. clearUnresolvedReferences(): void {
  2095. this.db.exec('DELETE FROM unresolved_refs');
  2096. }
  2097. /**
  2098. * Delete resolved references by their IDs
  2099. */
  2100. deleteResolvedReferences(fromNodeIds: string[]): void {
  2101. if (fromNodeIds.length === 0) return;
  2102. // Chunk under SQLite's parameter limit, matching every other IN-list in
  2103. // this file. The internal resolution path uses deleteSpecificResolvedReferences
  2104. // instead, but QueryBuilder is part of the public API, so a library consumer
  2105. // passing more ids than SQLITE_MAX_VARIABLE_NUMBER (32766 on the bundled
  2106. // node:sqlite) would otherwise hit "too many SQL variables". (#540, #1001)
  2107. for (let i = 0; i < fromNodeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2108. const chunk = fromNodeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2109. const placeholders = chunk.map(() => '?').join(',');
  2110. this.db.prepare(`DELETE FROM unresolved_refs WHERE from_node_id IN (${placeholders})`).run(...chunk);
  2111. }
  2112. }
  2113. /**
  2114. * Delete specific resolved references by (fromNodeId, referenceName, referenceKind) tuples.
  2115. * More precise than deleteResolvedReferences — only removes refs that were actually resolved.
  2116. */
  2117. deleteSpecificResolvedReferences(refs: Array<{ fromNodeId: string; referenceName: string; referenceKind: string }>): number {
  2118. if (refs.length === 0) return 0;
  2119. const stmt = this.db.prepare(
  2120. 'DELETE FROM unresolved_refs WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?'
  2121. );
  2122. // Returns rows actually removed (SQLite `changes`, summed): the batched
  2123. // resolution loop's non-progress guard keys on this — zero removals from
  2124. // a batch that claimed work is the direct runaway signal (§7a.2).
  2125. let changed = 0;
  2126. const deleteMany = this.db.transaction((items: typeof refs) => {
  2127. for (const ref of items) {
  2128. changed += stmt.run(ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
  2129. }
  2130. });
  2131. deleteMany(refs);
  2132. return changed;
  2133. }
  2134. /**
  2135. * Delete unresolved-ref rows by row id — the precise cleanup for refs a
  2136. * resolution pass actually processed. The key-tuple variant above also
  2137. * deletes SIBLING rows (same caller calling the same callee at other lines)
  2138. * that a later batch hasn't attempted yet, so when a batch boundary split a
  2139. * caller's same-named call sites, the later sites' edges were silently never
  2140. * created (#1269).
  2141. */
  2142. deleteReferencesByRowIds(rowIds: number[]): number {
  2143. if (rowIds.length === 0) return 0;
  2144. // One transaction for all chunks (each chunk was previously its own
  2145. // implicit transaction = its own WAL commit — measurable on 100k+-ref
  2146. // resolution persists), and the full-size chunk statement is cached so
  2147. // repeat calls skip the re-prepare; only the final partial chunk (if any)
  2148. // prepares ad hoc. Returns rows actually removed (summed `changes`) for
  2149. // the batched loop's non-progress guard (§7a.2).
  2150. let changed = 0;
  2151. this.db.transaction(() => {
  2152. for (let i = 0; i < rowIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2153. const chunk = rowIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2154. if (chunk.length === SQLITE_PARAM_CHUNK_SIZE) {
  2155. if (!this.stmts.deleteRefsByRowIdsFull) {
  2156. const placeholders = new Array(SQLITE_PARAM_CHUNK_SIZE).fill('?').join(',');
  2157. this.stmts.deleteRefsByRowIdsFull = this.db.prepare(
  2158. `DELETE FROM unresolved_refs WHERE id IN (${placeholders})`
  2159. );
  2160. }
  2161. changed += this.stmts.deleteRefsByRowIdsFull.run(...chunk).changes;
  2162. } else {
  2163. const placeholders = chunk.map(() => '?').join(',');
  2164. changed += this.db.prepare(`DELETE FROM unresolved_refs WHERE id IN (${placeholders})`).run(...chunk).changes;
  2165. }
  2166. }
  2167. })();
  2168. return changed;
  2169. }
  2170. /**
  2171. * Mark refs a completed resolution pass could not resolve as status='failed'
  2172. * instead of deleting them (#1240). Failed rows are invisible to the pending
  2173. * count/batch readers (so drain loops and the #1187 orphan sweep still
  2174. * terminate) but stay queryable by name_tail so a later sync can retry them
  2175. * when a changed file introduces a symbol that could satisfy them. name_tail
  2176. * is (re)written here so rows inserted before the v8 migration get their
  2177. * tail the first time they're attempted.
  2178. */
  2179. markReferencesFailed(refs: Array<{ fromNodeId: string; referenceName: string; referenceKind: string }>): number {
  2180. if (refs.length === 0) return 0;
  2181. const stmt = this.db.prepare(
  2182. "UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?"
  2183. );
  2184. let changed = 0;
  2185. const markMany = this.db.transaction((items: typeof refs) => {
  2186. for (const ref of items) {
  2187. changed += stmt.run(referenceNameTail(ref.referenceName), ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
  2188. }
  2189. });
  2190. markMany(refs);
  2191. return changed;
  2192. }
  2193. /**
  2194. * Park refs as status='failed' by row id — the precise counterpart of
  2195. * markReferencesFailed, for the same reason as deleteReferencesByRowIds:
  2196. * the key-tuple variant also flips same-key sibling rows in later batches
  2197. * to 'failed' before they were ever attempted (#1269). Resolution outcome
  2198. * can differ per call site (receiver-type inference reads the ref's line),
  2199. * so a sibling must not inherit this row's failure.
  2200. */
  2201. markReferencesFailedByRowIds(refs: Array<{ rowId: number; referenceName: string }>): number {
  2202. if (refs.length === 0) return 0;
  2203. const stmt = this.db.prepare(
  2204. "UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE id = ?"
  2205. );
  2206. let changed = 0;
  2207. const markMany = this.db.transaction((items: typeof refs) => {
  2208. for (const ref of items) {
  2209. changed += stmt.run(referenceNameTail(ref.referenceName), ref.rowId).changes;
  2210. }
  2211. });
  2212. markMany(refs);
  2213. return changed;
  2214. }
  2215. /**
  2216. * Failed refs whose name tail matches one of the given symbol names — the
  2217. * candidates a sync should retry after files carrying those names changed
  2218. * (#1240). Names matching more than `perNameCeiling` failed refs are
  2219. * skipped entirely: at that population a name is external/builtin noise
  2220. * (`get`, `map`, …) that one new definition won't resolve — the same
  2221. * rationale as resolution's AMBIGUOUS_NAME_CEILING (#999) — and retrying an
  2222. * arbitrary subset would be both wasted work and incoherent coverage.
  2223. */
  2224. getRetryableFailedReferences(names: string[], perNameCeiling: number = 500): UnresolvedReference[] {
  2225. if (names.length === 0) return [];
  2226. // Pass 1: per-tail counts, chunked under the SQLite parameter limit.
  2227. const retryNames: string[] = [];
  2228. for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2229. const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2230. const placeholders = chunk.map(() => '?').join(',');
  2231. const counts = this.db
  2232. .prepare(
  2233. `SELECT name_tail, COUNT(*) as count FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders}) GROUP BY name_tail`
  2234. )
  2235. .all(...chunk) as Array<{ name_tail: string; count: number }>;
  2236. for (const row of counts) {
  2237. if (row.count <= perNameCeiling) retryNames.push(row.name_tail);
  2238. }
  2239. }
  2240. if (retryNames.length === 0) return [];
  2241. // Pass 2: load the surviving rows.
  2242. const rows: UnresolvedRefRow[] = [];
  2243. for (let i = 0; i < retryNames.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2244. const chunk = retryNames.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2245. const placeholders = chunk.map(() => '?').join(',');
  2246. const chunkRows = this.db
  2247. .prepare(`SELECT * FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders})`)
  2248. .all(...chunk) as UnresolvedRefRow[];
  2249. rows.push(...chunkRows);
  2250. }
  2251. return rows.map((row) => ({
  2252. fromNodeId: row.from_node_id,
  2253. referenceName: row.reference_name,
  2254. referenceKind: row.reference_kind as EdgeKind,
  2255. line: row.line,
  2256. column: row.col,
  2257. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2258. filePath: row.file_path,
  2259. language: row.language as Language,
  2260. rowId: row.id,
  2261. }));
  2262. }
  2263. /**
  2264. * Distinct node names present in the given files — the symbol names a sync
  2265. * pass uses to look up retryable failed refs after those files changed.
  2266. */
  2267. getNodeNamesByFiles(filePaths: string[]): string[] {
  2268. if (filePaths.length === 0) return [];
  2269. const names = new Set<string>();
  2270. for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2271. const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2272. const placeholders = chunk.map(() => '?').join(',');
  2273. const rows = this.db
  2274. .prepare(`SELECT DISTINCT name FROM nodes WHERE file_path IN (${placeholders})`)
  2275. .all(...chunk) as Array<{ name: string }>;
  2276. for (const row of rows) names.add(row.name);
  2277. }
  2278. return [...names];
  2279. }
  2280. // ===========================================================================
  2281. // Statistics
  2282. // ===========================================================================
  2283. /**
  2284. * Lightweight (nodes, edges) count snapshot. Used around an index/sync
  2285. * run to compute true additions across extraction + resolution +
  2286. * synthesis — the per-phase counter in the orchestrator only sees
  2287. * extraction's contribution, which is why the CLI summary under-reported
  2288. * the edge count (resolution + synthesizer edges were invisible).
  2289. */
  2290. getNodeAndEdgeCount(): { nodes: number; edges: number } {
  2291. return this.db
  2292. .prepare('SELECT (SELECT COUNT(*) FROM nodes) AS nodes, (SELECT COUNT(*) FROM edges) AS edges')
  2293. .get() as { nodes: number; edges: number };
  2294. }
  2295. /**
  2296. * Get graph statistics
  2297. */
  2298. getStats(): GraphStats {
  2299. // Single query for all three aggregate counts
  2300. const counts = this.db.prepare(`
  2301. SELECT
  2302. (SELECT COUNT(*) FROM nodes) AS node_count,
  2303. (SELECT COUNT(*) FROM edges) AS edge_count,
  2304. (SELECT COUNT(*) FROM files) AS file_count
  2305. `).get() as { node_count: number; edge_count: number; file_count: number };
  2306. const nodesByKind = {} as Record<NodeKind, number>;
  2307. const nodeKindRows = this.db
  2308. .prepare('SELECT kind, COUNT(*) as count FROM nodes GROUP BY kind')
  2309. .all() as Array<{ kind: string; count: number }>;
  2310. for (const row of nodeKindRows) {
  2311. nodesByKind[row.kind as NodeKind] = row.count;
  2312. }
  2313. const edgesByKind = {} as Record<EdgeKind, number>;
  2314. const edgeKindRows = this.db
  2315. .prepare('SELECT kind, COUNT(*) as count FROM edges GROUP BY kind')
  2316. .all() as Array<{ kind: string; count: number }>;
  2317. for (const row of edgeKindRows) {
  2318. edgesByKind[row.kind as EdgeKind] = row.count;
  2319. }
  2320. const filesByLanguage = {} as Record<Language, number>;
  2321. const languageRows = this.db
  2322. .prepare('SELECT language, COUNT(*) as count FROM files GROUP BY language')
  2323. .all() as Array<{ language: string; count: number }>;
  2324. for (const row of languageRows) {
  2325. filesByLanguage[row.language as Language] = row.count;
  2326. }
  2327. return {
  2328. nodeCount: counts.node_count,
  2329. edgeCount: counts.edge_count,
  2330. fileCount: counts.file_count,
  2331. nodesByKind,
  2332. edgesByKind,
  2333. filesByLanguage,
  2334. dbSizeBytes: 0, // Set by caller using DatabaseConnection.getSize()
  2335. walSizeBytes: 0, // Set by caller using DatabaseConnection.getWalSizeBytes()
  2336. lastUpdated: Date.now(),
  2337. };
  2338. }
  2339. // ===========================================================================
  2340. // Project Metadata
  2341. // ===========================================================================
  2342. /**
  2343. * Get a metadata value by key
  2344. */
  2345. getMetadata(key: string): string | null {
  2346. const row = this.db.prepare('SELECT value FROM project_metadata WHERE key = ?').get(key) as { value: string } | undefined;
  2347. return row?.value ?? null;
  2348. }
  2349. /**
  2350. * Set a metadata key-value pair (upsert)
  2351. */
  2352. setMetadata(key: string, value: string): void {
  2353. this.db.prepare(
  2354. 'INSERT INTO project_metadata (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at'
  2355. ).run(key, value, Date.now());
  2356. }
  2357. /**
  2358. * Get all metadata as a key-value record
  2359. */
  2360. getAllMetadata(): Record<string, string> {
  2361. const rows = this.db.prepare('SELECT key, value FROM project_metadata').all() as { key: string; value: string }[];
  2362. const result: Record<string, string> = {};
  2363. for (const row of rows) {
  2364. result[row.key] = row.value;
  2365. }
  2366. return result;
  2367. }
  2368. /**
  2369. * Clear all data from the database
  2370. */
  2371. clear(): void {
  2372. this.nodeCache.clear();
  2373. this.db.transaction(() => {
  2374. this.db.exec('DELETE FROM unresolved_refs');
  2375. this.db.exec('DELETE FROM edges');
  2376. this.db.exec('DELETE FROM nodes');
  2377. this.db.exec('DELETE FROM files');
  2378. })();
  2379. }
  2380. }