queries.ts 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817
  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. * This is resolution's candidate list, and the ORDER BY is load-bearing for
  1050. * index correctness, not cosmetic (CG-33). When a reference names a symbol
  1051. * that several files define and nothing disambiguates them, resolution binds
  1052. * to the first candidate — so without an ORDER BY the winner was decided by
  1053. * rowid, i.e. by the order files happened to be WRITTEN. A full index writes
  1054. * them in scan order; an incremental sync appends each file as it changes, so
  1055. * the same tree resolved to different edges depending on how the index was
  1056. * built, and a long-lived synced index drifted away from a rebuild of itself
  1057. * (measured at 4.3% of distinct edges, mostly `calls`).
  1058. *
  1059. * `(file_path, start_line)` is a property of the CODE, so both paths now pick
  1060. * the same candidate. The sort is paid once per distinct name per resolution
  1061. * run — ReferenceResolver memoizes this in its nameCache — and the population
  1062. * is capped by AMBIGUOUS_NAME_CEILING (#999).
  1063. */
  1064. getNodesByName(name: string): Node[] {
  1065. if (!this.stmts.getNodesByName) {
  1066. this.stmts.getNodesByName = this.db.prepare(
  1067. 'SELECT * FROM nodes WHERE name = ? ORDER BY file_path, start_line'
  1068. );
  1069. }
  1070. const rows = this.stmts.getNodesByName.all(name) as NodeRow[];
  1071. return rows.map(rowToNode);
  1072. }
  1073. /**
  1074. * Nodes whose name starts with `prefix`, by index range scan (a LIKE would
  1075. * skip idx_nodes_name under SQLite's default case-insensitive LIKE).
  1076. */
  1077. getNodesByNamePrefix(prefix: string, limit = 20): Node[] {
  1078. if (!this.stmts.getNodesByNamePrefix) {
  1079. this.stmts.getNodesByNamePrefix = this.db.prepare(
  1080. 'SELECT * FROM nodes WHERE name >= ? AND name < ? ORDER BY name LIMIT ?'
  1081. );
  1082. }
  1083. const rows = this.stmts.getNodesByNamePrefix.all(prefix, prefix + '￿', limit) as NodeRow[];
  1084. return rows.map(rowToNode);
  1085. }
  1086. /**
  1087. * Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
  1088. */
  1089. getNodesByQualifiedNameExact(qualifiedName: string): Node[] {
  1090. if (!this.stmts.getNodesByQualifiedNameExact) {
  1091. this.stmts.getNodesByQualifiedNameExact = this.db.prepare(
  1092. 'SELECT * FROM nodes WHERE qualified_name = ?'
  1093. );
  1094. }
  1095. const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName) as NodeRow[];
  1096. return rows.map(rowToNode);
  1097. }
  1098. /**
  1099. * Get nodes by lowercase name match (uses idx_nodes_lower_name expression index)
  1100. */
  1101. getNodesByLowerName(lowerName: string): Node[] {
  1102. if (!this.stmts.getNodesByLowerName) {
  1103. this.stmts.getNodesByLowerName = this.db.prepare(
  1104. 'SELECT * FROM nodes WHERE lower(name) = ?'
  1105. );
  1106. }
  1107. const rows = this.stmts.getNodesByLowerName.all(lowerName) as NodeRow[];
  1108. return rows.map(rowToNode);
  1109. }
  1110. /**
  1111. * Search nodes by name using FTS with fallback to LIKE for better matching
  1112. *
  1113. * Search strategy:
  1114. * 1. Try FTS5 prefix match (query*) for word-start matching
  1115. * 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
  1116. * 3. Score results based on match quality
  1117. */
  1118. searchNodes(query: string, options: SearchOptions = {}): SearchResult[] {
  1119. const { limit = 100, offset = 0 } = options;
  1120. // Parse field-qualified bits out of the raw query (kind:, lang:,
  1121. // path:, name:). Anything not recognised stays in `text` and goes
  1122. // to FTS unchanged. Filters compose with the SearchOptions arg —
  1123. // both are applied (intersection-style).
  1124. const parsed = parseQuery(query);
  1125. const mergedKinds =
  1126. parsed.kinds.length > 0
  1127. ? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
  1128. : options.kinds;
  1129. const mergedLanguages =
  1130. parsed.languages.length > 0
  1131. ? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
  1132. : options.languages;
  1133. const pathFilters = parsed.pathFilters;
  1134. const nameFilters = parsed.nameFilters;
  1135. // The text portion drives FTS/LIKE; if all the user typed was
  1136. // filters (`kind:function`), we still need *some* candidate set,
  1137. // so synthesise an empty-text path that returns everything matching
  1138. // the filters.
  1139. const text = parsed.text;
  1140. const kinds = mergedKinds;
  1141. const languages = mergedLanguages;
  1142. // First try FTS5 with prefix matching
  1143. let results = text
  1144. ? this.searchNodesFTS(text, { kinds, languages, limit, offset })
  1145. // Over-fetch by 5× when running filter-only (no text). The
  1146. // post-scoring path: + name: filters can be very selective, so
  1147. // a smaller multiplier risks returning fewer than `limit`
  1148. // results despite the DB having plenty of matches.
  1149. : this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
  1150. // If no FTS results, try LIKE-based substring search
  1151. if (results.length === 0 && text.length >= 2) {
  1152. results = this.searchNodesLike(text, { kinds, languages, limit, offset });
  1153. }
  1154. // Final fuzzy fallback: scan all known names and keep those within
  1155. // a tight Levenshtein distance. Only fires when both FTS and LIKE
  1156. // returned nothing AND there's a text portion long enough to be
  1157. // worth fuzzing (1-char queries would match too much).
  1158. if (results.length === 0 && text.length >= 3) {
  1159. results = this.searchNodesFuzzy(text, { kinds, languages, limit });
  1160. }
  1161. // Supplement: ensure exact name matches are always candidates.
  1162. // BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
  1163. // compound names (e.g. "getBeanDescriptor") in large codebases,
  1164. // pushing them past the FTS fetch limit before post-hoc scoring can help.
  1165. // Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
  1166. // prefix=20) actually differentiates them after rescoring.
  1167. if (results.length > 0 && query) {
  1168. const existingIds = new Set(results.map(r => r.node.id));
  1169. const maxFtsScore = Math.max(...results.map(r => r.score));
  1170. const terms = query.split(/\s+/).filter(t => t.length >= 2);
  1171. for (const term of terms) {
  1172. let sql = 'SELECT * FROM nodes WHERE name = ? COLLATE NOCASE';
  1173. const params: (string | number)[] = [term];
  1174. if (kinds && kinds.length > 0) {
  1175. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1176. params.push(...kinds);
  1177. }
  1178. if (languages && languages.length > 0) {
  1179. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1180. params.push(...languages);
  1181. }
  1182. sql += ' LIMIT 20';
  1183. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1184. for (const row of rows) {
  1185. if (!existingIds.has(row.id)) {
  1186. results.push({ node: rowToNode(row), score: maxFtsScore });
  1187. existingIds.add(row.id);
  1188. }
  1189. }
  1190. }
  1191. }
  1192. // Apply multi-signal scoring
  1193. if (results.length > 0 && (text || query)) {
  1194. const scoringQuery = text || query;
  1195. results = results.map(r => ({
  1196. ...r,
  1197. score: r.score
  1198. + kindBonus(r.node.kind)
  1199. + scorePathRelevance(r.node.filePath, scoringQuery, this.projectNameTokens)
  1200. + nameMatchBonus(r.node.name, scoringQuery),
  1201. }));
  1202. results.sort((a, b) => b.score - a.score);
  1203. // Trim to requested limit after rescoring
  1204. if (results.length > limit) {
  1205. results = results.slice(0, limit);
  1206. }
  1207. }
  1208. // Apply path: + name: filters AFTER scoring. Scoring already uses
  1209. // path/name as a soft signal; the explicit filters here are a hard
  1210. // gate. Done last so the FTS limit fetched plenty of candidates to
  1211. // narrow from.
  1212. if (pathFilters.length > 0) {
  1213. const lowered = pathFilters.map((p) => p.toLowerCase());
  1214. results = results.filter((r) => {
  1215. const fp = r.node.filePath.toLowerCase();
  1216. return lowered.some((p) => fp.includes(p));
  1217. });
  1218. }
  1219. if (nameFilters.length > 0) {
  1220. const lowered = nameFilters.map((n) => n.toLowerCase());
  1221. results = results.filter((r) => {
  1222. const nm = r.node.name.toLowerCase();
  1223. return lowered.some((n) => nm.includes(n));
  1224. });
  1225. }
  1226. return results;
  1227. }
  1228. /**
  1229. * Match-everything path used when the user supplied only field
  1230. * filters (`kind:function lang:typescript`) with no text. Returns
  1231. * candidates ordered by name; the caller's filter pass narrows to
  1232. * what was asked for.
  1233. */
  1234. private searchAllByFilters(options: {
  1235. kinds?: NodeKind[];
  1236. languages?: Language[];
  1237. limit: number;
  1238. }): SearchResult[] {
  1239. const { kinds, languages, limit } = options;
  1240. let sql = 'SELECT * FROM nodes WHERE 1=1';
  1241. const params: (string | number)[] = [];
  1242. if (kinds && kinds.length > 0) {
  1243. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1244. params.push(...kinds);
  1245. }
  1246. if (languages && languages.length > 0) {
  1247. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1248. params.push(...languages);
  1249. }
  1250. sql += ' ORDER BY name LIMIT ?';
  1251. params.push(limit);
  1252. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1253. return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
  1254. }
  1255. /**
  1256. * Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
  1257. * sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
  1258. * `getUssr` finds `getUser` but `process` doesn't match `prosody`.
  1259. * Bounded edit distance keeps each comparison cheap; the per-query
  1260. * scan is O(distinct-name-count) which is far smaller than total
  1261. * node count on any real codebase.
  1262. */
  1263. private searchNodesFuzzy(
  1264. text: string,
  1265. options: { kinds?: NodeKind[]; languages?: Language[]; limit: number }
  1266. ): SearchResult[] {
  1267. const { kinds, languages, limit } = options;
  1268. const lowered = text.toLowerCase();
  1269. const maxDist = lowered.length <= 4 ? 1 : 2;
  1270. // Pull the distinct name list once. The set is cached on QueryBuilder
  1271. // by getAllNodeNames(); even on a 200k-node project the distinct
  1272. // name set is typically O(10k) because most names repeat. The
  1273. // candidate-cap below bounds memory regardless.
  1274. const allNames = this.getAllNodeNames();
  1275. const candidates: Array<{ name: string; dist: number }> = [];
  1276. for (const name of allNames) {
  1277. const dist = boundedEditDistance(name.toLowerCase(), lowered, maxDist);
  1278. if (dist <= maxDist) candidates.push({ name, dist });
  1279. }
  1280. candidates.sort((a, b) => a.dist - b.dist);
  1281. // Cap the per-name follow-up queries. Each survivor triggers a
  1282. // separate `SELECT * FROM nodes WHERE name = ?`; without this cap
  1283. // a project with many similar names (`getUser1`, `getUser2`...)
  1284. // could fan out far beyond `limit` queries before the inner-loop
  1285. // limit kicks in.
  1286. const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
  1287. const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
  1288. const results: SearchResult[] = [];
  1289. const seen = new Set<string>();
  1290. for (const c of cappedCandidates) {
  1291. if (results.length >= limit) break;
  1292. let sql = 'SELECT * FROM nodes WHERE name = ?';
  1293. const params: (string | number)[] = [c.name];
  1294. if (kinds && kinds.length > 0) {
  1295. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1296. params.push(...kinds);
  1297. }
  1298. if (languages && languages.length > 0) {
  1299. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1300. params.push(...languages);
  1301. }
  1302. sql += ' LIMIT 5';
  1303. const rows = this.db.prepare(sql).all(...params) as NodeRow[];
  1304. for (const row of rows) {
  1305. if (seen.has(row.id)) continue;
  1306. seen.add(row.id);
  1307. // Lower the score for each edit step away from the query so
  1308. // exact-match fallbacks (dist 0) outrank dist-2 typos.
  1309. results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
  1310. if (results.length >= limit) break;
  1311. }
  1312. }
  1313. return results;
  1314. }
  1315. /**
  1316. * FTS5 search with prefix matching
  1317. */
  1318. private searchNodesFTS(query: string, options: SearchOptions): SearchResult[] {
  1319. const { kinds, languages, limit = 100, offset = 0 } = options;
  1320. // Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
  1321. // Escape special FTS5 characters and add prefix wildcard.
  1322. //
  1323. // `::` is a qualifier separator in Rust/C++/Ruby, not a token char,
  1324. // so treat it as whitespace before the strip step. Otherwise queries
  1325. // like `stage_apply::run` collapse to `stage_applyrun` (the colons
  1326. // are stripped without splitting) and find nothing. See #173.
  1327. const ftsQuery = query
  1328. .replace(/::/g, ' ') // Rust/C++/Ruby qualifier separator
  1329. .replace(/['"*():^]/g, '') // Remove FTS5 special chars
  1330. .split(/\s+/)
  1331. .filter(term => term.length > 0)
  1332. // Strip FTS5 boolean operators to prevent query manipulation
  1333. .filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
  1334. .map(term => `"${term}"*`) // Prefix match each term
  1335. .join(' OR ');
  1336. if (!ftsQuery) {
  1337. return [];
  1338. }
  1339. // BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
  1340. // Heavy name weight ensures exact/prefix name matches rank above incidental
  1341. // mentions in long docstrings or qualified names of nested symbols.
  1342. // Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
  1343. // nameMatchBonus) can promote results that BM25 alone undervalues.
  1344. const ftsLimit = Math.max(limit * 5, 100);
  1345. let sql = `
  1346. SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
  1347. FROM nodes_fts
  1348. JOIN nodes ON nodes_fts.id = nodes.id
  1349. WHERE nodes_fts MATCH ?
  1350. `;
  1351. const params: (string | number)[] = [ftsQuery];
  1352. if (kinds && kinds.length > 0) {
  1353. sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
  1354. params.push(...kinds);
  1355. }
  1356. if (languages && languages.length > 0) {
  1357. sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
  1358. params.push(...languages);
  1359. }
  1360. sql += ' ORDER BY score LIMIT ? OFFSET ?';
  1361. params.push(ftsLimit, offset);
  1362. try {
  1363. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1364. return rows.map((row) => ({
  1365. node: rowToNode(row),
  1366. score: Math.abs(row.score), // bm25 returns negative scores
  1367. }));
  1368. } catch {
  1369. // FTS query failed, return empty
  1370. return [];
  1371. }
  1372. }
  1373. /**
  1374. * LIKE-based substring search for cases where FTS doesn't match
  1375. * Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
  1376. */
  1377. private searchNodesLike(query: string, options: SearchOptions): SearchResult[] {
  1378. const { kinds, languages, limit = 100, offset = 0 } = options;
  1379. let sql = `
  1380. SELECT nodes.*,
  1381. CASE
  1382. WHEN name = ? THEN 1.0
  1383. WHEN name LIKE ? THEN 0.9
  1384. WHEN name LIKE ? THEN 0.8
  1385. WHEN qualified_name LIKE ? THEN 0.7
  1386. ELSE 0.5
  1387. END as score
  1388. FROM nodes
  1389. WHERE (
  1390. name LIKE ? OR
  1391. qualified_name LIKE ? OR
  1392. name LIKE ?
  1393. )
  1394. `;
  1395. // Pattern variants for better matching
  1396. const exactMatch = query;
  1397. const startsWith = `${query}%`;
  1398. const contains = `%${query}%`;
  1399. const params: (string | number)[] = [
  1400. exactMatch, // Exact match score
  1401. startsWith, // Starts with score
  1402. contains, // Contains score
  1403. contains, // Qualified name score
  1404. contains, // WHERE: name contains
  1405. contains, // WHERE: qualified_name contains
  1406. startsWith, // WHERE: name starts with
  1407. ];
  1408. if (kinds && kinds.length > 0) {
  1409. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1410. params.push(...kinds);
  1411. }
  1412. if (languages && languages.length > 0) {
  1413. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1414. params.push(...languages);
  1415. }
  1416. sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
  1417. params.push(limit, offset);
  1418. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1419. return rows.map((row) => ({
  1420. node: rowToNode(row),
  1421. score: row.score,
  1422. }));
  1423. }
  1424. /**
  1425. * Find nodes by exact name match
  1426. *
  1427. * Used for hybrid search - looks up symbols by exact name or case-insensitive match.
  1428. * Returns high-confidence matches for known symbol names extracted from query.
  1429. *
  1430. * @param names - Array of symbol names to look up
  1431. * @param options - Search options (kinds, languages, limit)
  1432. * @returns SearchResult array with exact matches scored at 1.0
  1433. */
  1434. findNodesByExactName(names: string[], options: SearchOptions = {}): SearchResult[] {
  1435. if (names.length === 0) return [];
  1436. const { kinds, languages, limit = 50 } = options;
  1437. // Two-pass approach to handle common names (e.g., "run" has 40+ matches):
  1438. // Pass 1: Find which files contain distinctive (rare) symbols from the query.
  1439. // Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
  1440. // Pass 1: Find files containing each queried name, identify distinctive names
  1441. const nameToFiles = new Map<string, Set<string>>();
  1442. for (const name of names) {
  1443. let sql = 'SELECT DISTINCT file_path FROM nodes WHERE name COLLATE NOCASE = ?';
  1444. const params: (string | number)[] = [name];
  1445. if (kinds && kinds.length > 0) {
  1446. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1447. params.push(...kinds);
  1448. }
  1449. sql += ' LIMIT 100';
  1450. const rows = this.db.prepare(sql).all(...params) as { file_path: string }[];
  1451. nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
  1452. }
  1453. // Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
  1454. const distinctiveFiles = new Set<string>();
  1455. for (const [, files] of nameToFiles) {
  1456. if (files.size > 0 && files.size < 10) {
  1457. for (const f of files) distinctiveFiles.add(f);
  1458. }
  1459. }
  1460. // Pass 2: Query each name with per-name limit, scoring by co-location
  1461. const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
  1462. const allResults: SearchResult[] = [];
  1463. const seenIds = new Set<string>();
  1464. for (const name of names) {
  1465. let sql = `
  1466. SELECT nodes.*, 1.0 as score
  1467. FROM nodes
  1468. WHERE name COLLATE NOCASE = ?
  1469. `;
  1470. const params: (string | number)[] = [name];
  1471. if (kinds && kinds.length > 0) {
  1472. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1473. params.push(...kinds);
  1474. }
  1475. if (languages && languages.length > 0) {
  1476. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1477. params.push(...languages);
  1478. }
  1479. // Fetch enough to find co-located results among common names
  1480. sql += ' LIMIT ?';
  1481. params.push(Math.max(perNameLimit * 3, 50));
  1482. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1483. const nameResults: SearchResult[] = [];
  1484. for (const row of rows) {
  1485. const node = rowToNode(row);
  1486. if (seenIds.has(node.id)) continue;
  1487. // Boost results in files that also contain distinctive symbols
  1488. const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
  1489. nameResults.push({ node, score: row.score + coLocationBoost });
  1490. }
  1491. // Sort by score (co-located first), take per-name limit
  1492. nameResults.sort((a, b) => b.score - a.score);
  1493. for (const r of nameResults.slice(0, perNameLimit)) {
  1494. seenIds.add(r.node.id);
  1495. allResults.push(r);
  1496. }
  1497. }
  1498. // Sort all results by score so co-located results bubble up
  1499. allResults.sort((a, b) => b.score - a.score);
  1500. return allResults.slice(0, limit);
  1501. }
  1502. /**
  1503. * Find nodes whose name contains a substring (LIKE-based).
  1504. * Useful for CamelCase-part matching where FTS fails because
  1505. * e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
  1506. *
  1507. * Results are ordered by name length (shorter = more likely to be the core type).
  1508. */
  1509. findNodesByNameSubstring(
  1510. substring: string,
  1511. options: SearchOptions & { excludePrefix?: boolean } = {}
  1512. ): SearchResult[] {
  1513. const { kinds, languages, limit = 30, excludePrefix } = options;
  1514. let sql = `
  1515. SELECT nodes.*, 1.0 as score
  1516. FROM nodes
  1517. WHERE name LIKE ?
  1518. `;
  1519. const params: (string | number)[] = [`%${substring}%`];
  1520. // Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
  1521. if (excludePrefix) {
  1522. sql += ` AND name NOT LIKE ?`;
  1523. params.push(`${substring}%`);
  1524. }
  1525. if (kinds && kinds.length > 0) {
  1526. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1527. params.push(...kinds);
  1528. }
  1529. if (languages && languages.length > 0) {
  1530. sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
  1531. params.push(...languages);
  1532. }
  1533. sql += ' ORDER BY length(name) ASC LIMIT ?';
  1534. params.push(limit);
  1535. const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
  1536. return rows.map((row) => ({
  1537. node: rowToNode(row),
  1538. score: row.score,
  1539. }));
  1540. }
  1541. // ===========================================================================
  1542. // Edge Operations
  1543. // ===========================================================================
  1544. /**
  1545. * Insert a new edge
  1546. */
  1547. insertEdge(edge: Edge): void {
  1548. if (!this.stmts.insertEdge) {
  1549. this.stmts.insertEdge = this.db.prepare(`
  1550. INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
  1551. VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
  1552. `);
  1553. }
  1554. this.stmts.insertEdge.run({
  1555. source: edge.source,
  1556. target: edge.target,
  1557. kind: edge.kind,
  1558. metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
  1559. line: edge.line ?? null,
  1560. col: edge.column ?? null,
  1561. provenance: edge.provenance ?? null,
  1562. });
  1563. }
  1564. /**
  1565. * Insert multiple edges in a transaction
  1566. */
  1567. insertEdges(edges: Edge[]): void {
  1568. if (edges.length === 0) return;
  1569. this.db.transaction(() => {
  1570. const endpointIds = new Set<string>();
  1571. for (const edge of edges) {
  1572. endpointIds.add(edge.source);
  1573. endpointIds.add(edge.target);
  1574. }
  1575. const existingNodeIds = this.getExistingNodeIds([...endpointIds]);
  1576. const rows: unknown[][] = [];
  1577. for (const edge of edges) {
  1578. if (!existingNodeIds.has(edge.source) || !existingNodeIds.has(edge.target)) {
  1579. continue;
  1580. }
  1581. rows.push([
  1582. edge.source,
  1583. edge.target,
  1584. edge.kind,
  1585. edge.metadata ? JSON.stringify(edge.metadata) : null,
  1586. edge.line ?? null,
  1587. edge.column ?? null,
  1588. edge.provenance ?? null,
  1589. ]);
  1590. }
  1591. this.runBatched(
  1592. 'insertEdges',
  1593. 'INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance) VALUES ',
  1594. '(?,?,?,?,?,?,?)',
  1595. rows
  1596. );
  1597. })();
  1598. }
  1599. /**
  1600. * Delete all edges from a source node
  1601. */
  1602. deleteEdgesBySource(sourceId: string): void {
  1603. if (!this.stmts.deleteEdgesBySource) {
  1604. this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
  1605. }
  1606. this.stmts.deleteEdgesBySource.run(sourceId);
  1607. }
  1608. /**
  1609. * Get outgoing edges from a node
  1610. */
  1611. getOutgoingEdges(sourceId: string, kinds?: EdgeKind[], provenance?: string): Edge[] {
  1612. if ((kinds && kinds.length > 0) || provenance) {
  1613. let sql = 'SELECT * FROM edges WHERE source = ?';
  1614. const params: (string | number)[] = [sourceId];
  1615. if (kinds && kinds.length > 0) {
  1616. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1617. params.push(...kinds);
  1618. }
  1619. if (provenance) {
  1620. sql += ' AND provenance = ?';
  1621. params.push(provenance);
  1622. }
  1623. const rows = this.db.prepare(sql).all(...params) as EdgeRow[];
  1624. return rows.map(rowToEdge);
  1625. }
  1626. if (!this.stmts.getEdgesBySource) {
  1627. this.stmts.getEdgesBySource = this.db.prepare('SELECT * FROM edges WHERE source = ?');
  1628. }
  1629. const rows = this.stmts.getEdgesBySource.all(sourceId) as EdgeRow[];
  1630. return rows.map(rowToEdge);
  1631. }
  1632. /**
  1633. * Get incoming edges to a node
  1634. */
  1635. getIncomingEdges(targetId: string, kinds?: EdgeKind[]): Edge[] {
  1636. if (kinds && kinds.length > 0) {
  1637. const sql = `SELECT * FROM edges WHERE target = ? AND kind IN (${kinds.map(() => '?').join(',')})`;
  1638. const rows = this.db.prepare(sql).all(targetId, ...kinds) as EdgeRow[];
  1639. return rows.map(rowToEdge);
  1640. }
  1641. if (!this.stmts.getEdgesByTarget) {
  1642. this.stmts.getEdgesByTarget = this.db.prepare('SELECT * FROM edges WHERE target = ?');
  1643. }
  1644. const rows = this.stmts.getEdgesByTarget.all(targetId) as EdgeRow[];
  1645. return rows.map(rowToEdge);
  1646. }
  1647. /**
  1648. * Find all edges where both source and target are in the given node set.
  1649. * Useful for recovering inter-node connectivity after BFS.
  1650. */
  1651. findEdgesBetweenNodes(nodeIds: string[], kinds?: EdgeKind[]): Edge[] {
  1652. if (nodeIds.length === 0) return [];
  1653. const idsJson = JSON.stringify(nodeIds);
  1654. let sql = `SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?)) AND target IN (SELECT value FROM json_each(?))`;
  1655. const params: string[] = [idsJson, idsJson];
  1656. if (kinds && kinds.length > 0) {
  1657. sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
  1658. params.push(...kinds);
  1659. }
  1660. const rows = this.db.prepare(sql).all(...params) as EdgeRow[];
  1661. return rows.map(rowToEdge);
  1662. }
  1663. /**
  1664. * Distinct file paths that DEPEND ON `filePath`: every file containing a
  1665. * symbol with a cross-file edge (any kind except `contains`) into a symbol
  1666. * of this file. This is the file-level projection of the symbol dependency
  1667. * graph and the basis for blast-radius / `affected` test selection.
  1668. *
  1669. * It deliberately does NOT restrict to `imports` edges. In this graph an
  1670. * `imports` edge connects a file to its own local import declarations
  1671. * (it is always same-file), so an imports-only lookup returns zero
  1672. * cross-file dependents for every file. The real cross-file dependency
  1673. * signal is the resolved call/reference graph — calls, references,
  1674. * instantiates, extends, implements, overrides, type_of, returns,
  1675. * decorates — exactly what {@link GraphTraverser.getImpactRadius} traverses.
  1676. * `contains` is excluded: a parent containing a symbol does not *depend* on
  1677. * it. One indexed query (idx_nodes_file_path + idx_edges_target_kind).
  1678. */
  1679. getDependentFilePaths(filePath: string): string[] {
  1680. const sql = `SELECT DISTINCT src.file_path AS fp
  1681. FROM edges e
  1682. JOIN nodes tgt ON tgt.id = e.target
  1683. JOIN nodes src ON src.id = e.source
  1684. WHERE tgt.file_path = ?
  1685. AND e.kind != 'contains'
  1686. AND src.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. * Distinct file paths that `filePath` DEPENDS ON — the inverse of
  1692. * {@link getDependentFilePaths}: every file containing a symbol that a
  1693. * symbol of this file has a cross-file edge into. Same edge-kind rules
  1694. * (all kinds except `contains`); same reason imports-only is insufficient.
  1695. */
  1696. getDependencyFilePaths(filePath: string): string[] {
  1697. const sql = `SELECT DISTINCT tgt.file_path AS fp
  1698. FROM edges e
  1699. JOIN nodes src ON src.id = e.source
  1700. JOIN nodes tgt ON tgt.id = e.target
  1701. WHERE src.file_path = ?
  1702. AND e.kind != 'contains'
  1703. AND tgt.file_path != ?`;
  1704. const rows = this.db.prepare(sql).all(filePath, filePath) as Array<{ fp: string }>;
  1705. return rows.map((r) => r.fp);
  1706. }
  1707. /**
  1708. * Cross-file edges whose TARGET is a node in `filePath` and whose SOURCE is a
  1709. * node in a *different* file, paired with the target node's (name, kind) so a
  1710. * caller can re-resolve the edge to the re-indexed target's new ID (node IDs
  1711. * are `sha256(filePath:kind:name:line)`, so any line shift in the callee file
  1712. * changes target IDs and a naive re-insert by old ID silently drops them).
  1713. * Used by `storeExtractionResult` to preserve incoming edges across a file
  1714. * re-index (issue #899). Same edge-kind rules as
  1715. * {@link getDependentFilePaths}: all kinds except `contains`.
  1716. */
  1717. getCrossFileIncomingEdgesWithTarget(
  1718. filePath: string
  1719. ): Array<Edge & { targetName: string; targetKind: NodeKind; sourceFilePath: string; sourceLanguage: Language }> {
  1720. const sql = `SELECT e.*, tgt.name AS target_name, tgt.kind AS target_kind,
  1721. src.file_path AS source_file_path, src.language AS source_language
  1722. FROM edges e
  1723. JOIN nodes tgt ON tgt.id = e.target
  1724. JOIN nodes src ON src.id = e.source
  1725. WHERE tgt.file_path = ?
  1726. AND e.kind != 'contains'
  1727. AND src.file_path != ?`;
  1728. const rows = this.db.prepare(sql).all(filePath, filePath) as Array<
  1729. EdgeRow & { target_name: string; target_kind: NodeKind; source_file_path: string; source_language: Language }
  1730. >;
  1731. return rows.map(row => ({
  1732. ...rowToEdge(row),
  1733. targetName: row.target_name,
  1734. targetKind: row.target_kind,
  1735. sourceFilePath: row.source_file_path,
  1736. sourceLanguage: row.source_language,
  1737. }));
  1738. }
  1739. // ===========================================================================
  1740. // File Operations
  1741. // ===========================================================================
  1742. /**
  1743. * Insert or update a file record
  1744. */
  1745. upsertFile(file: FileRecord): void {
  1746. if (!this.stmts.upsertFile) {
  1747. this.stmts.upsertFile = this.db.prepare(`
  1748. INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors, generated)
  1749. VALUES (@path, @contentHash, @language, @size, @modifiedAt, @indexedAt, @nodeCount, @errors, @generated)
  1750. ON CONFLICT(path) DO UPDATE SET
  1751. content_hash = @contentHash,
  1752. language = @language,
  1753. size = @size,
  1754. modified_at = @modifiedAt,
  1755. indexed_at = @indexedAt,
  1756. node_count = @nodeCount,
  1757. errors = @errors,
  1758. generated = @generated
  1759. `);
  1760. }
  1761. this.stmts.upsertFile.run({
  1762. path: file.path,
  1763. contentHash: file.contentHash,
  1764. language: file.language,
  1765. size: file.size,
  1766. modifiedAt: file.modifiedAt,
  1767. indexedAt: file.indexedAt,
  1768. nodeCount: file.nodeCount,
  1769. errors: file.errors ? JSON.stringify(file.errors) : null,
  1770. // The upsert always REWRITES the flag: a file that loses its banner in an
  1771. // edit must lose the flag on the next sync, not keep a stale 1.
  1772. generated: file.generated ? 1 : 0,
  1773. });
  1774. }
  1775. /**
  1776. * Which of `filePaths` the index flagged as tool-generated (schema v9+).
  1777. *
  1778. * Bounded-lookup by design: every consumer already holds a short candidate
  1779. * list (a ranked file group, an FTS result page, a LIMIT-20 aggregate), so
  1780. * this stays a partial-index probe over a handful of paths — no whole-repo
  1781. * set to materialize, and no cache to invalidate, which means a ranking call
  1782. * can never serve a verdict the last sync already replaced.
  1783. *
  1784. * Returns ONLY the content/index signal; callers union it with
  1785. * {@link isGeneratedFile} so pre-v9 databases (column present, all zeros
  1786. * until a re-index) keep the path-only behavior rather than regressing.
  1787. */
  1788. getGeneratedPathsAmong(filePaths: Iterable<string>): Set<string> {
  1789. const unique = [...new Set(filePaths)];
  1790. const found = new Set<string>();
  1791. if (unique.length === 0) return found;
  1792. for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  1793. const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  1794. const placeholders = chunk.map(() => '?').join(',');
  1795. const rows = this.db
  1796. .prepare(`SELECT path FROM files WHERE generated = 1 AND path IN (${placeholders})`)
  1797. .all(...chunk) as Array<{ path: string }>;
  1798. for (const row of rows) found.add(row.path);
  1799. }
  1800. return found;
  1801. }
  1802. /**
  1803. * A reusable `(path) => boolean` over a bounded candidate list, unioning the
  1804. * indexed flag with the path convention. This is the shape every ranking
  1805. * comparator wants: one query up front, then O(1) per comparison.
  1806. */
  1807. generatedPredicateFor(filePaths: Iterable<string>): (filePath: string) => boolean {
  1808. const flagged = this.getGeneratedPathsAmong(filePaths);
  1809. return (filePath: string) => flagged.has(filePath) || isGeneratedFile(filePath);
  1810. }
  1811. /**
  1812. * Which of `filePaths` are AMBIENT DECLARATION files — they declare nothing
  1813. * but types, and nothing in the index depends on them (CG-28). A hand-written
  1814. * ambient `.d.ts` of global shims, a vendored typings file, module
  1815. * augmentation: reachable only by name, structurally attached to nothing.
  1816. *
  1817. * Structural, not extension-based, so a hand-written `types.ts` and a `.d.ts`
  1818. * are judged by the same rule and a `.d.ts` that does declare a class or a
  1819. * const is (correctly) not caught. Four conditions, all required:
  1820. *
  1821. * 1. it declares at least one symbol — an empty or unparsed file is not a
  1822. * declaration file, it is a file we know nothing about;
  1823. * 2. EVERY declared symbol is a type-level kind (interface / type alias /
  1824. * enum / namespace). The narrowness is deliberate and measured: a rule
  1825. * of "no callables" alone flags 1–18% of a repo, including Kotlin sealed
  1826. * classes, Rust `mod.rs` re-exports and django's locale constant tables —
  1827. * real source that must not be demoted. This rule flags 0–4%;
  1828. * 3. no symbol in it originates a `calls`/`instantiates` edge — the direct
  1829. * evidence that nothing here has a body;
  1830. * 4. NOTHING ELSE IN THE INDEX points at it. This is the condition that
  1831. * separates an ambient shim from a working type module, and it is why
  1832. * the flag is narrow enough to be safe: `displacement-ts`'s pipeline
  1833. * `types.ts` passes 1–3 identically but carries 13 inbound imports and
  1834. * 21 references, so the files that answer a query about the pipeline are
  1835. * typed BY it — it is part of that answer's structure. An ambient
  1836. * `declare global` shim has zero. Deliberately index-wide rather than
  1837. * restricted to the candidate list: the file that imports it is usually
  1838. * not itself a candidate.
  1839. *
  1840. * Bounded-lookup like {@link getGeneratedPathsAmong}: callers hold a ranked
  1841. * candidate list, so this is a partial-index probe over a handful of paths.
  1842. */
  1843. getAmbientDeclarationPathsAmong(filePaths: Iterable<string>): Set<string> {
  1844. const unique = [...new Set(filePaths)];
  1845. const found = new Set<string>();
  1846. if (unique.length === 0) return found;
  1847. for (let i = 0; i < unique.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  1848. const chunk = unique.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  1849. const placeholders = chunk.map(() => '?').join(',');
  1850. // `file`/`import`/`export`/`parameter` are structural bookkeeping, not
  1851. // things the file declares, so they neither qualify nor disqualify.
  1852. const rows = this.db
  1853. .prepare(`
  1854. SELECT file_path,
  1855. SUM(CASE WHEN kind NOT IN ('file','import','export','parameter')
  1856. THEN 1 ELSE 0 END) AS declared,
  1857. SUM(CASE WHEN kind IN ('interface','type_alias','enum','enum_member','namespace')
  1858. THEN 1 ELSE 0 END) AS typeDeclared
  1859. FROM nodes
  1860. WHERE file_path IN (${placeholders})
  1861. GROUP BY file_path
  1862. `)
  1863. .all(...chunk) as Array<{ file_path: string; declared: number; typeDeclared: number }>;
  1864. let candidates = rows
  1865. .filter((r) => r.declared > 0 && r.declared === r.typeDeclared)
  1866. .map((r) => r.file_path);
  1867. if (candidates.length === 0) continue;
  1868. const disqualify = (sql: string): void => {
  1869. if (candidates.length === 0) return;
  1870. const hit = new Set(
  1871. (this.db
  1872. .prepare(sql.replace('$IN$', candidates.map(() => '?').join(',')))
  1873. .all(...candidates) as Array<{ file_path: string }>).map((r) => r.file_path),
  1874. );
  1875. candidates = candidates.filter((p) => !hit.has(p));
  1876. };
  1877. // (3) originates behaviour
  1878. disqualify(`
  1879. SELECT DISTINCT n.file_path AS file_path
  1880. FROM edges e JOIN nodes n ON n.id = e.source
  1881. WHERE e.kind IN ('calls','instantiates') AND n.file_path IN ($IN$)
  1882. `);
  1883. // (4) something outside the file depends on it
  1884. disqualify(`
  1885. SELECT DISTINCT t.file_path AS file_path
  1886. FROM edges e JOIN nodes t ON t.id = e.target JOIN nodes s ON s.id = e.source
  1887. WHERE t.file_path IN ($IN$) AND s.file_path <> t.file_path
  1888. `);
  1889. for (const path of candidates) found.add(path);
  1890. }
  1891. return found;
  1892. }
  1893. /**
  1894. * A reusable `(path) => boolean` ambient-declaration test over a bounded
  1895. * candidate list — the shape a ranking comparator wants: one query up front,
  1896. * O(1) per comparison.
  1897. */
  1898. ambientDeclarationPredicateFor(filePaths: Iterable<string>): (filePath: string) => boolean {
  1899. const flagged = this.getAmbientDeclarationPathsAmong(filePaths);
  1900. return (filePath: string) => flagged.has(filePath);
  1901. }
  1902. /** How many indexed files carry the generated flag. Surfaced by `status`. */
  1903. countGeneratedFiles(): number {
  1904. const row = this.db
  1905. .prepare('SELECT COUNT(*) AS n FROM files WHERE generated = 1')
  1906. .get() as { n: number } | undefined;
  1907. return row?.n ?? 0;
  1908. }
  1909. /**
  1910. * Delete a file record and its nodes
  1911. */
  1912. deleteFile(filePath: string): void {
  1913. this.db.transaction(() => {
  1914. this.deleteNodesByFile(filePath);
  1915. if (!this.stmts.deleteFile) {
  1916. this.stmts.deleteFile = this.db.prepare('DELETE FROM files WHERE path = ?');
  1917. }
  1918. this.stmts.deleteFile.run(filePath);
  1919. })();
  1920. }
  1921. /**
  1922. * Get a file record by path
  1923. */
  1924. getFileByPath(filePath: string): FileRecord | null {
  1925. if (!this.stmts.getFileByPath) {
  1926. this.stmts.getFileByPath = this.db.prepare('SELECT * FROM files WHERE path = ?');
  1927. }
  1928. const row = this.stmts.getFileByPath.get(filePath) as FileRow | undefined;
  1929. return row ? rowToFileRecord(row) : null;
  1930. }
  1931. /**
  1932. * Get all tracked files
  1933. */
  1934. getAllFiles(): FileRecord[] {
  1935. if (!this.stmts.getAllFiles) {
  1936. this.stmts.getAllFiles = this.db.prepare('SELECT * FROM files ORDER BY path');
  1937. }
  1938. const rows = this.stmts.getAllFiles.all() as FileRow[];
  1939. return rows.map(rowToFileRecord);
  1940. }
  1941. /**
  1942. * Most recent index timestamp (ms since epoch) across all tracked files, or
  1943. * null when nothing is indexed yet. One indexed aggregate, no per-row scan. (#329)
  1944. */
  1945. getLastIndexedAt(): number | null {
  1946. const row = this.db
  1947. .prepare('SELECT MAX(indexed_at) AS last FROM files')
  1948. .get() as { last: number | null } | undefined;
  1949. return row?.last ?? null;
  1950. }
  1951. /**
  1952. * Get files that need re-indexing (hash changed)
  1953. */
  1954. getStaleFiles(currentHashes: Map<string, string>): FileRecord[] {
  1955. const files = this.getAllFiles();
  1956. return files.filter((f) => {
  1957. const currentHash = currentHashes.get(f.path);
  1958. return currentHash && currentHash !== f.contentHash;
  1959. });
  1960. }
  1961. // ===========================================================================
  1962. // Unresolved References
  1963. // ===========================================================================
  1964. /**
  1965. * Insert an unresolved reference
  1966. */
  1967. insertUnresolvedRef(ref: UnresolvedReference): void {
  1968. if (!this.stmts.insertUnresolved) {
  1969. this.stmts.insertUnresolved = this.db.prepare(`
  1970. INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language)
  1971. VALUES (@fromNodeId, @referenceName, @referenceKind, @line, @col, @candidates, @filePath, @language)
  1972. `);
  1973. }
  1974. this.stmts.insertUnresolved.run({
  1975. fromNodeId: ref.fromNodeId,
  1976. referenceName: ref.referenceName,
  1977. referenceKind: ref.referenceKind,
  1978. line: ref.line,
  1979. col: ref.column,
  1980. candidates: ref.candidates ? JSON.stringify(ref.candidates) : null,
  1981. filePath: ref.filePath ?? '',
  1982. language: ref.language ?? 'unknown',
  1983. });
  1984. }
  1985. /**
  1986. * Insert multiple unresolved references in a transaction
  1987. */
  1988. insertUnresolvedRefsBatch(refs: UnresolvedReference[]): void {
  1989. if (refs.length === 0) return;
  1990. const insert = this.db.transaction(() => {
  1991. const rows: unknown[][] = [];
  1992. for (const ref of refs) {
  1993. rows.push([
  1994. ref.fromNodeId,
  1995. ref.referenceName,
  1996. ref.referenceKind,
  1997. ref.line,
  1998. ref.column,
  1999. ref.candidates ? JSON.stringify(ref.candidates) : null,
  2000. ref.filePath ?? '',
  2001. ref.language ?? 'unknown',
  2002. ]);
  2003. }
  2004. this.runBatched(
  2005. 'insertUnresolvedRefs',
  2006. 'INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, candidates, file_path, language) VALUES ',
  2007. '(?,?,?,?,?,?,?,?)',
  2008. rows
  2009. );
  2010. });
  2011. insert();
  2012. }
  2013. /**
  2014. * Delete unresolved references from a node
  2015. */
  2016. deleteUnresolvedByNode(nodeId: string): void {
  2017. if (!this.stmts.deleteUnresolvedByNode) {
  2018. this.stmts.deleteUnresolvedByNode = this.db.prepare(
  2019. 'DELETE FROM unresolved_refs WHERE from_node_id = ?'
  2020. );
  2021. }
  2022. this.stmts.deleteUnresolvedByNode.run(nodeId);
  2023. }
  2024. /**
  2025. * Get unresolved references by name (for resolution)
  2026. */
  2027. getUnresolvedByName(name: string): UnresolvedReference[] {
  2028. if (!this.stmts.getUnresolvedByName) {
  2029. this.stmts.getUnresolvedByName = this.db.prepare(
  2030. 'SELECT * FROM unresolved_refs WHERE reference_name = ?'
  2031. );
  2032. }
  2033. const rows = this.stmts.getUnresolvedByName.all(name) as UnresolvedRefRow[];
  2034. return rows.map((row) => ({
  2035. fromNodeId: row.from_node_id,
  2036. referenceName: row.reference_name,
  2037. referenceKind: row.reference_kind as EdgeKind,
  2038. line: row.line,
  2039. column: row.col,
  2040. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2041. filePath: row.file_path,
  2042. language: row.language as Language,
  2043. rowId: row.id,
  2044. }));
  2045. }
  2046. /**
  2047. * Get all unresolved references
  2048. */
  2049. getUnresolvedReferences(): UnresolvedReference[] {
  2050. const rows = this.db.prepare('SELECT * FROM unresolved_refs').all() as UnresolvedRefRow[];
  2051. return rows.map((row) => ({
  2052. fromNodeId: row.from_node_id,
  2053. referenceName: row.reference_name,
  2054. referenceKind: row.reference_kind as EdgeKind,
  2055. line: row.line,
  2056. column: row.col,
  2057. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2058. filePath: row.file_path,
  2059. language: row.language as Language,
  2060. rowId: row.id,
  2061. }));
  2062. }
  2063. /**
  2064. * Get the count of PENDING (never-attempted) references without loading
  2065. * them into memory. Rows marked status='failed' — attempted by a completed
  2066. * pass, no match — are excluded: they are not outstanding work, only retry
  2067. * candidates for the #1240 sweep, so they must not trip the #1187 orphan
  2068. * sweep or the `status` pending-refs warning.
  2069. */
  2070. getUnresolvedReferencesCount(): number {
  2071. if (!this.stmts.getUnresolvedCount) {
  2072. this.stmts.getUnresolvedCount = this.db.prepare(
  2073. "SELECT COUNT(*) as count FROM unresolved_refs WHERE status = 'pending'"
  2074. );
  2075. }
  2076. const row = this.stmts.getUnresolvedCount.get() as { count: number };
  2077. return row.count;
  2078. }
  2079. /**
  2080. * Get a batch of PENDING unresolved references using LIMIT/OFFSET
  2081. * pagination. Used to process references in bounded memory chunks; failed
  2082. * rows are excluded so the batched drain loop terminates once every row
  2083. * has been attempted.
  2084. */
  2085. getUnresolvedReferencesBatch(offset: number, limit: number): UnresolvedReference[] {
  2086. if (!this.stmts.getUnresolvedBatch) {
  2087. // ORDER BY rowid is load-bearing for the pipelined resolution loop: it
  2088. // prefetches batch k+1 at OFFSET batch_k.length while batch k's rows are
  2089. // still pending, which is only exact under a stable enumeration. (A plain
  2090. // scan and the status index both return rowid order anyway — this pins
  2091. // it.)
  2092. this.stmts.getUnresolvedBatch = this.db.prepare(
  2093. "SELECT * FROM unresolved_refs WHERE status = 'pending' ORDER BY rowid LIMIT ? OFFSET ?"
  2094. );
  2095. }
  2096. const rows = this.stmts.getUnresolvedBatch.all(limit, offset) as UnresolvedRefRow[];
  2097. return rows.map((row) => ({
  2098. fromNodeId: row.from_node_id,
  2099. referenceName: row.reference_name,
  2100. referenceKind: row.reference_kind as EdgeKind,
  2101. line: row.line,
  2102. column: row.col,
  2103. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2104. filePath: row.file_path,
  2105. language: row.language as Language,
  2106. rowId: row.id,
  2107. }));
  2108. }
  2109. /**
  2110. * Keyset variant of {@link getUnresolvedReferencesBatch} for the batched
  2111. * resolution loop: seek past the last-seen row id instead of OFFSET-walking.
  2112. * OFFSET reads re-scan the accumulated failed-row prefix on every batch —
  2113. * O(failed rows) per read, measured at 54.6s of the kernel-scale batch loop
  2114. * (§7a.2) — while the seek is O(batch) forever. `id` is the rowid alias, so
  2115. * the enumeration order is identical to the OFFSET reader's.
  2116. */
  2117. getUnresolvedReferencesBatchAfter(afterRowId: number, limit: number): UnresolvedReference[] {
  2118. if (!this.stmts.getUnresolvedBatchAfter) {
  2119. this.stmts.getUnresolvedBatchAfter = this.db.prepare(
  2120. "SELECT * FROM unresolved_refs WHERE status = 'pending' AND id > ? ORDER BY id LIMIT ?"
  2121. );
  2122. }
  2123. const rows = this.stmts.getUnresolvedBatchAfter.all(afterRowId, limit) as UnresolvedRefRow[];
  2124. return rows.map((row) => ({
  2125. fromNodeId: row.from_node_id,
  2126. referenceName: row.reference_name,
  2127. referenceKind: row.reference_kind as EdgeKind,
  2128. line: row.line,
  2129. column: row.col,
  2130. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2131. filePath: row.file_path,
  2132. language: row.language as Language,
  2133. rowId: row.id,
  2134. }));
  2135. }
  2136. /**
  2137. * Get all tracked file paths (lightweight — no full FileRecord objects)
  2138. */
  2139. getAllFilePaths(): string[] {
  2140. if (!this.stmts.getAllFilePaths) {
  2141. this.stmts.getAllFilePaths = this.db.prepare('SELECT path FROM files ORDER BY path');
  2142. }
  2143. const rows = this.stmts.getAllFilePaths.all() as Array<{ path: string }>;
  2144. return rows.map((r) => r.path);
  2145. }
  2146. /**
  2147. * Get all distinct node names (lightweight — just name strings for pre-filtering)
  2148. */
  2149. getAllNodeNames(): string[] {
  2150. if (!this.stmts.getAllNodeNames) {
  2151. this.stmts.getAllNodeNames = this.db.prepare('SELECT DISTINCT name FROM nodes');
  2152. }
  2153. const rows = this.stmts.getAllNodeNames.all() as Array<{ name: string }>;
  2154. return rows.map((r) => r.name);
  2155. }
  2156. /**
  2157. * Stream the distinct node names one row at a time — the incremental
  2158. * counterpart to {@link getAllNodeNames} for callers that need to yield
  2159. * to the event loop mid-scan (resolver cache warm-up on multi-million-node
  2160. * indexes). Fresh statement per call: the iterator holds an open cursor.
  2161. */
  2162. *iterateNodeNames(): IterableIterator<string> {
  2163. const stmt = this.db.prepare('SELECT DISTINCT name FROM nodes');
  2164. for (const row of stmt.iterate()) {
  2165. yield (row as { name: string }).name;
  2166. }
  2167. }
  2168. /**
  2169. * Get unresolved references scoped to specific file paths.
  2170. * Uses the idx_unresolved_file_path index for efficient lookup.
  2171. */
  2172. getUnresolvedReferencesByFiles(filePaths: string[]): UnresolvedReference[] {
  2173. if (filePaths.length === 0) return [];
  2174. // Chunk under SQLite's parameter limit: the first sync of a very large repo
  2175. // passes every changed file here, which an unbounded `IN (...)` would bind
  2176. // as one parameter each — exceeding MAX_VARIABLE_NUMBER and aborting with
  2177. // "too many SQL variables". (#540)
  2178. const rows: UnresolvedRefRow[] = [];
  2179. for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2180. const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2181. const placeholders = chunk.map(() => '?').join(',');
  2182. const chunkRows = this.db
  2183. .prepare(`SELECT * FROM unresolved_refs WHERE status = 'pending' AND file_path IN (${placeholders})`)
  2184. .all(...chunk) as UnresolvedRefRow[];
  2185. // Append with a loop, never a spread: the INPUT chunk is bounded, but
  2186. // the RESULT rows per chunk are not — a dense recovery sync (e.g. the
  2187. // #1541 self-heal re-indexing hundreds of files) returns more rows than
  2188. // V8 allows as arguments, and `push(...chunkRows)` dies with "Maximum
  2189. // call stack size exceeded", aborting resolution mid-sync (#1558).
  2190. for (const row of chunkRows) rows.push(row);
  2191. }
  2192. return rows.map((row) => ({
  2193. fromNodeId: row.from_node_id,
  2194. referenceName: row.reference_name,
  2195. referenceKind: row.reference_kind as EdgeKind,
  2196. line: row.line,
  2197. column: row.col,
  2198. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2199. filePath: row.file_path,
  2200. language: row.language as Language,
  2201. rowId: row.id,
  2202. }));
  2203. }
  2204. /**
  2205. * Delete all unresolved references (after resolution)
  2206. */
  2207. clearUnresolvedReferences(): void {
  2208. this.db.exec('DELETE FROM unresolved_refs');
  2209. }
  2210. /**
  2211. * Delete resolved references by their IDs
  2212. */
  2213. deleteResolvedReferences(fromNodeIds: string[]): void {
  2214. if (fromNodeIds.length === 0) return;
  2215. // Chunk under SQLite's parameter limit, matching every other IN-list in
  2216. // this file. The internal resolution path uses deleteSpecificResolvedReferences
  2217. // instead, but QueryBuilder is part of the public API, so a library consumer
  2218. // passing more ids than SQLITE_MAX_VARIABLE_NUMBER (32766 on the bundled
  2219. // node:sqlite) would otherwise hit "too many SQL variables". (#540, #1001)
  2220. for (let i = 0; i < fromNodeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2221. const chunk = fromNodeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2222. const placeholders = chunk.map(() => '?').join(',');
  2223. this.db.prepare(`DELETE FROM unresolved_refs WHERE from_node_id IN (${placeholders})`).run(...chunk);
  2224. }
  2225. }
  2226. /**
  2227. * Delete specific resolved references by (fromNodeId, referenceName, referenceKind) tuples.
  2228. * More precise than deleteResolvedReferences — only removes refs that were actually resolved.
  2229. */
  2230. deleteSpecificResolvedReferences(refs: Array<{ fromNodeId: string; referenceName: string; referenceKind: string }>): number {
  2231. if (refs.length === 0) return 0;
  2232. const stmt = this.db.prepare(
  2233. 'DELETE FROM unresolved_refs WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?'
  2234. );
  2235. // Returns rows actually removed (SQLite `changes`, summed): the batched
  2236. // resolution loop's non-progress guard keys on this — zero removals from
  2237. // a batch that claimed work is the direct runaway signal (§7a.2).
  2238. let changed = 0;
  2239. const deleteMany = this.db.transaction((items: typeof refs) => {
  2240. for (const ref of items) {
  2241. changed += stmt.run(ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
  2242. }
  2243. });
  2244. deleteMany(refs);
  2245. return changed;
  2246. }
  2247. /**
  2248. * Delete unresolved-ref rows by row id — the precise cleanup for refs a
  2249. * resolution pass actually processed. The key-tuple variant above also
  2250. * deletes SIBLING rows (same caller calling the same callee at other lines)
  2251. * that a later batch hasn't attempted yet, so when a batch boundary split a
  2252. * caller's same-named call sites, the later sites' edges were silently never
  2253. * created (#1269).
  2254. */
  2255. deleteReferencesByRowIds(rowIds: number[]): number {
  2256. if (rowIds.length === 0) return 0;
  2257. // One transaction for all chunks (each chunk was previously its own
  2258. // implicit transaction = its own WAL commit — measurable on 100k+-ref
  2259. // resolution persists), and the full-size chunk statement is cached so
  2260. // repeat calls skip the re-prepare; only the final partial chunk (if any)
  2261. // prepares ad hoc. Returns rows actually removed (summed `changes`) for
  2262. // the batched loop's non-progress guard (§7a.2).
  2263. let changed = 0;
  2264. this.db.transaction(() => {
  2265. for (let i = 0; i < rowIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2266. const chunk = rowIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2267. if (chunk.length === SQLITE_PARAM_CHUNK_SIZE) {
  2268. if (!this.stmts.deleteRefsByRowIdsFull) {
  2269. const placeholders = new Array(SQLITE_PARAM_CHUNK_SIZE).fill('?').join(',');
  2270. this.stmts.deleteRefsByRowIdsFull = this.db.prepare(
  2271. `DELETE FROM unresolved_refs WHERE id IN (${placeholders})`
  2272. );
  2273. }
  2274. changed += this.stmts.deleteRefsByRowIdsFull.run(...chunk).changes;
  2275. } else {
  2276. const placeholders = chunk.map(() => '?').join(',');
  2277. changed += this.db.prepare(`DELETE FROM unresolved_refs WHERE id IN (${placeholders})`).run(...chunk).changes;
  2278. }
  2279. }
  2280. })();
  2281. return changed;
  2282. }
  2283. /**
  2284. * Mark refs a completed resolution pass could not resolve as status='failed'
  2285. * instead of deleting them (#1240). Failed rows are invisible to the pending
  2286. * count/batch readers (so drain loops and the #1187 orphan sweep still
  2287. * terminate) but stay queryable by name_tail so a later sync can retry them
  2288. * when a changed file introduces a symbol that could satisfy them. name_tail
  2289. * is (re)written here so rows inserted before the v8 migration get their
  2290. * tail the first time they're attempted.
  2291. */
  2292. markReferencesFailed(refs: Array<{ fromNodeId: string; referenceName: string; referenceKind: string }>): number {
  2293. if (refs.length === 0) return 0;
  2294. const stmt = this.db.prepare(
  2295. "UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE from_node_id = ? AND reference_name = ? AND reference_kind = ?"
  2296. );
  2297. let changed = 0;
  2298. const markMany = this.db.transaction((items: typeof refs) => {
  2299. for (const ref of items) {
  2300. changed += stmt.run(referenceNameTail(ref.referenceName), ref.fromNodeId, ref.referenceName, ref.referenceKind).changes;
  2301. }
  2302. });
  2303. markMany(refs);
  2304. return changed;
  2305. }
  2306. /**
  2307. * Park refs as status='failed' by row id — the precise counterpart of
  2308. * markReferencesFailed, for the same reason as deleteReferencesByRowIds:
  2309. * the key-tuple variant also flips same-key sibling rows in later batches
  2310. * to 'failed' before they were ever attempted (#1269). Resolution outcome
  2311. * can differ per call site (receiver-type inference reads the ref's line),
  2312. * so a sibling must not inherit this row's failure.
  2313. */
  2314. markReferencesFailedByRowIds(refs: Array<{ rowId: number; referenceName: string }>): number {
  2315. if (refs.length === 0) return 0;
  2316. const stmt = this.db.prepare(
  2317. "UPDATE unresolved_refs SET status = 'failed', name_tail = ? WHERE id = ?"
  2318. );
  2319. let changed = 0;
  2320. const markMany = this.db.transaction((items: typeof refs) => {
  2321. for (const ref of items) {
  2322. changed += stmt.run(referenceNameTail(ref.referenceName), ref.rowId).changes;
  2323. }
  2324. });
  2325. markMany(refs);
  2326. return changed;
  2327. }
  2328. /**
  2329. * Failed refs whose name tail matches one of the given symbol names — the
  2330. * candidates a sync should retry after files carrying those names changed
  2331. * (#1240). Names matching more than `perNameCeiling` failed refs are
  2332. * skipped entirely: at that population a name is external/builtin noise
  2333. * (`get`, `map`, …) that one new definition won't resolve — the same
  2334. * rationale as resolution's AMBIGUOUS_NAME_CEILING (#999) — and retrying an
  2335. * arbitrary subset would be both wasted work and incoherent coverage.
  2336. */
  2337. getRetryableFailedReferences(names: string[], perNameCeiling: number = 500): UnresolvedReference[] {
  2338. if (names.length === 0) return [];
  2339. // Pass 1: per-tail counts, chunked under the SQLite parameter limit.
  2340. const retryNames: string[] = [];
  2341. for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2342. const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2343. const placeholders = chunk.map(() => '?').join(',');
  2344. const counts = this.db
  2345. .prepare(
  2346. `SELECT name_tail, COUNT(*) as count FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders}) GROUP BY name_tail`
  2347. )
  2348. .all(...chunk) as Array<{ name_tail: string; count: number }>;
  2349. for (const row of counts) {
  2350. if (row.count <= perNameCeiling) retryNames.push(row.name_tail);
  2351. }
  2352. }
  2353. if (retryNames.length === 0) return [];
  2354. // Pass 2: load the surviving rows.
  2355. const rows: UnresolvedRefRow[] = [];
  2356. for (let i = 0; i < retryNames.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2357. const chunk = retryNames.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2358. const placeholders = chunk.map(() => '?').join(',');
  2359. const chunkRows = this.db
  2360. .prepare(`SELECT * FROM unresolved_refs WHERE status = 'failed' AND name_tail IN (${placeholders})`)
  2361. .all(...chunk) as UnresolvedRefRow[];
  2362. // Loop, not spread — same V8 argument-limit hazard as
  2363. // getUnresolvedReferencesByFiles (#1558): a large definition delta can
  2364. // select an unbounded number of failed rows per chunk.
  2365. for (const row of chunkRows) rows.push(row);
  2366. }
  2367. return rows.map((row) => ({
  2368. fromNodeId: row.from_node_id,
  2369. referenceName: row.reference_name,
  2370. referenceKind: row.reference_kind as EdgeKind,
  2371. line: row.line,
  2372. column: row.col,
  2373. candidates: row.candidates ? safeJsonParse(row.candidates, undefined) : undefined,
  2374. filePath: row.file_path,
  2375. language: row.language as Language,
  2376. rowId: row.id,
  2377. }));
  2378. }
  2379. /**
  2380. * Resolution edges whose TARGET symbol is named one of `names` — the edges a
  2381. * sync must re-resolve after `names` gained or lost a definition (CG-33).
  2382. *
  2383. * Resolution binds a reference to a node whose name matches the reference's
  2384. * tail, and it picks among ALL same-named definitions project-wide. So adding
  2385. * or removing one definition of `pct` changes the answer for every `pct(...)`
  2386. * reference in the repo — including references in files this sync never
  2387. * touches, whose edges nothing else revisits. Those edges' current target is,
  2388. * by that same rule, a node named `pct`, which is why the target's name is a
  2389. * sufficient (and index-backed, via idx_nodes_name) way to find them without
  2390. * a schema change or a scan of edge metadata.
  2391. *
  2392. * Returns the source file/language alongside each edge so the caller can
  2393. * resurrect it as its original reference. Excludes `provenance='heuristic'`
  2394. * (synthesized dispatch edges are not resolution output and carry no refName
  2395. * stamp to resurrect from — deleting one would be a permanent loss).
  2396. *
  2397. * Names matching more than `perNameCeiling` edges are skipped entirely, same
  2398. * rationale and same default as {@link getRetryableFailedReferences}: at that
  2399. * population the name is generic (`get`, `clear`, …), one definition changing
  2400. * won't flip most of them, and rebinding an arbitrary subset is both wasted
  2401. * work and incoherent coverage.
  2402. */
  2403. getResolutionEdgesByTargetName(
  2404. names: string[],
  2405. perNameCeiling: number = 500
  2406. ): Array<Edge & { edgeId: number; sourceFilePath: string; sourceLanguage: Language }> {
  2407. if (names.length === 0) return [];
  2408. // Pass 1: per-name edge counts, chunked under the SQLite parameter limit.
  2409. const keep: string[] = [];
  2410. for (let i = 0; i < names.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2411. const chunk = names.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2412. const placeholders = chunk.map(() => '?').join(',');
  2413. const counts = this.db
  2414. .prepare(
  2415. `SELECT tgt.name AS name, COUNT(*) AS count
  2416. FROM edges e
  2417. JOIN nodes tgt ON tgt.id = e.target
  2418. WHERE tgt.name IN (${placeholders})
  2419. AND (e.provenance IS NULL OR e.provenance != 'heuristic')
  2420. GROUP BY tgt.name`
  2421. )
  2422. .all(...chunk) as Array<{ name: string; count: number }>;
  2423. for (const row of counts) {
  2424. if (row.count <= perNameCeiling) keep.push(row.name);
  2425. }
  2426. }
  2427. if (keep.length === 0) return [];
  2428. // Pass 2: load the surviving edges with the source file context a
  2429. // resurrection needs.
  2430. const out: Array<Edge & { edgeId: number; sourceFilePath: string; sourceLanguage: Language }> = [];
  2431. for (let i = 0; i < keep.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2432. const chunk = keep.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2433. const placeholders = chunk.map(() => '?').join(',');
  2434. const rows = this.db
  2435. .prepare(
  2436. `SELECT e.*, src.file_path AS source_file_path, src.language AS source_language
  2437. FROM edges e
  2438. JOIN nodes tgt ON tgt.id = e.target
  2439. JOIN nodes src ON src.id = e.source
  2440. WHERE tgt.name IN (${placeholders})
  2441. AND (e.provenance IS NULL OR e.provenance != 'heuristic')`
  2442. )
  2443. .all(...chunk) as Array<EdgeRow & { source_file_path: string; source_language: Language }>;
  2444. for (const row of rows) {
  2445. out.push({
  2446. ...rowToEdge(row),
  2447. edgeId: row.id,
  2448. sourceFilePath: row.source_file_path,
  2449. sourceLanguage: row.source_language,
  2450. });
  2451. }
  2452. }
  2453. return out;
  2454. }
  2455. /** Delete edges by primary key — the rebind pass's half of a re-resolution. */
  2456. deleteEdgesByIds(edgeIds: number[]): number {
  2457. if (edgeIds.length === 0) return 0;
  2458. let changed = 0;
  2459. this.db.transaction(() => {
  2460. for (let i = 0; i < edgeIds.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2461. const chunk = edgeIds.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2462. const placeholders = chunk.map(() => '?').join(',');
  2463. changed += this.db.prepare(`DELETE FROM edges WHERE id IN (${placeholders})`).run(...chunk).changes;
  2464. }
  2465. })();
  2466. return changed;
  2467. }
  2468. /**
  2469. * Distinct node names present in the given files — the symbol names a sync
  2470. * pass uses to look up retryable failed refs after those files changed.
  2471. */
  2472. getNodeNamesByFiles(filePaths: string[]): string[] {
  2473. if (filePaths.length === 0) return [];
  2474. const names = new Set<string>();
  2475. for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2476. const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2477. const placeholders = chunk.map(() => '?').join(',');
  2478. const rows = this.db
  2479. .prepare(`SELECT DISTINCT name FROM nodes WHERE file_path IN (${placeholders})`)
  2480. .all(...chunk) as Array<{ name: string }>;
  2481. for (const row of rows) names.add(row.name);
  2482. }
  2483. return [...names];
  2484. }
  2485. /**
  2486. * Distinct `file\0name` pairs defined by the given files — the shape sync's
  2487. * definition delta needs (CG-33).
  2488. *
  2489. * Deliberately NOT `getNodeNamesByFiles`: a bare name set is taken over the
  2490. * WHOLE changed batch, so a name that moves between two files in one commit
  2491. * (or exists in one changed file and is newly added to another) appears on
  2492. * both sides and cancels out of the symmetric difference — even though a
  2493. * definition genuinely appeared or vanished and every reference to that name
  2494. * repo-wide may now bind elsewhere. Keying by file makes each definition its
  2495. * own fact, so the move is seen as one removal plus one addition.
  2496. */
  2497. getNodeNamePairsByFiles(filePaths: string[]): Set<string> {
  2498. const pairs = new Set<string>();
  2499. if (filePaths.length === 0) return pairs;
  2500. for (let i = 0; i < filePaths.length; i += SQLITE_PARAM_CHUNK_SIZE) {
  2501. const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
  2502. const placeholders = chunk.map(() => '?').join(',');
  2503. const rows = this.db
  2504. .prepare(`SELECT DISTINCT file_path, name FROM nodes WHERE file_path IN (${placeholders})`)
  2505. .all(...chunk) as Array<{ file_path: string; name: string }>;
  2506. // NUL-joined: a path or a symbol name can contain a space, never a NUL.
  2507. for (const row of rows) pairs.add(`${row.file_path}\0${row.name}`);
  2508. }
  2509. return pairs;
  2510. }
  2511. // ===========================================================================
  2512. // Statistics
  2513. // ===========================================================================
  2514. /**
  2515. * Lightweight (nodes, edges) count snapshot. Used around an index/sync
  2516. * run to compute true additions across extraction + resolution +
  2517. * synthesis — the per-phase counter in the orchestrator only sees
  2518. * extraction's contribution, which is why the CLI summary under-reported
  2519. * the edge count (resolution + synthesizer edges were invisible).
  2520. */
  2521. getNodeAndEdgeCount(): { nodes: number; edges: number } {
  2522. return this.db
  2523. .prepare('SELECT (SELECT COUNT(*) FROM nodes) AS nodes, (SELECT COUNT(*) FROM edges) AS edges')
  2524. .get() as { nodes: number; edges: number };
  2525. }
  2526. /**
  2527. * Get graph statistics
  2528. */
  2529. getStats(): GraphStats {
  2530. // Single query for all three aggregate counts
  2531. const counts = this.db.prepare(`
  2532. SELECT
  2533. (SELECT COUNT(*) FROM nodes) AS node_count,
  2534. (SELECT COUNT(*) FROM edges) AS edge_count,
  2535. (SELECT COUNT(*) FROM files) AS file_count
  2536. `).get() as { node_count: number; edge_count: number; file_count: number };
  2537. const nodesByKind = {} as Record<NodeKind, number>;
  2538. const nodeKindRows = this.db
  2539. .prepare('SELECT kind, COUNT(*) as count FROM nodes GROUP BY kind')
  2540. .all() as Array<{ kind: string; count: number }>;
  2541. for (const row of nodeKindRows) {
  2542. nodesByKind[row.kind as NodeKind] = row.count;
  2543. }
  2544. const edgesByKind = {} as Record<EdgeKind, number>;
  2545. const edgeKindRows = this.db
  2546. .prepare('SELECT kind, COUNT(*) as count FROM edges GROUP BY kind')
  2547. .all() as Array<{ kind: string; count: number }>;
  2548. for (const row of edgeKindRows) {
  2549. edgesByKind[row.kind as EdgeKind] = row.count;
  2550. }
  2551. const filesByLanguage = {} as Record<Language, number>;
  2552. const languageRows = this.db
  2553. .prepare('SELECT language, COUNT(*) as count FROM files GROUP BY language')
  2554. .all() as Array<{ language: string; count: number }>;
  2555. for (const row of languageRows) {
  2556. filesByLanguage[row.language as Language] = row.count;
  2557. }
  2558. return {
  2559. nodeCount: counts.node_count,
  2560. edgeCount: counts.edge_count,
  2561. fileCount: counts.file_count,
  2562. nodesByKind,
  2563. edgesByKind,
  2564. filesByLanguage,
  2565. dbSizeBytes: 0, // Set by caller using DatabaseConnection.getSize()
  2566. walSizeBytes: 0, // Set by caller using DatabaseConnection.getWalSizeBytes()
  2567. lastUpdated: Date.now(),
  2568. };
  2569. }
  2570. // ===========================================================================
  2571. // Project Metadata
  2572. // ===========================================================================
  2573. /**
  2574. * Get a metadata value by key
  2575. */
  2576. getMetadata(key: string): string | null {
  2577. const row = this.db.prepare('SELECT value FROM project_metadata WHERE key = ?').get(key) as { value: string } | undefined;
  2578. return row?.value ?? null;
  2579. }
  2580. /**
  2581. * Set a metadata key-value pair (upsert)
  2582. */
  2583. setMetadata(key: string, value: string): void {
  2584. this.db.prepare(
  2585. 'INSERT INTO project_metadata (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at'
  2586. ).run(key, value, Date.now());
  2587. }
  2588. /**
  2589. * Get all metadata as a key-value record
  2590. */
  2591. getAllMetadata(): Record<string, string> {
  2592. const rows = this.db.prepare('SELECT key, value FROM project_metadata').all() as { key: string; value: string }[];
  2593. const result: Record<string, string> = {};
  2594. for (const row of rows) {
  2595. result[row.key] = row.value;
  2596. }
  2597. return result;
  2598. }
  2599. /**
  2600. * Clear all data from the database
  2601. */
  2602. clear(): void {
  2603. this.nodeCache.clear();
  2604. this.db.transaction(() => {
  2605. this.db.exec('DELETE FROM unresolved_refs');
  2606. this.db.exec('DELETE FROM edges');
  2607. this.db.exec('DELETE FROM nodes');
  2608. this.db.exec('DELETE FROM files');
  2609. })();
  2610. }
  2611. }