types.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /**
  2. * CodeGraph Type Definitions
  3. *
  4. * Core types for the semantic knowledge graph system.
  5. */
  6. // =============================================================================
  7. // Union Types
  8. // =============================================================================
  9. /**
  10. * Types of nodes in the knowledge graph.
  11. *
  12. * Defined as a runtime-iterable `as const` array so the same source
  13. * of truth backs both the TS type and any runtime validation
  14. * (e.g. the search query parser).
  15. */
  16. export const NODE_KINDS = [
  17. 'file',
  18. 'module',
  19. 'class',
  20. 'struct',
  21. 'interface',
  22. 'trait',
  23. 'protocol',
  24. 'function',
  25. 'method',
  26. 'property',
  27. 'field',
  28. 'variable',
  29. 'constant',
  30. 'enum',
  31. 'enum_member',
  32. 'type_alias',
  33. 'namespace',
  34. 'parameter',
  35. 'import',
  36. 'export',
  37. 'route',
  38. 'component',
  39. ] as const;
  40. export type NodeKind = (typeof NODE_KINDS)[number];
  41. /**
  42. * Types of edges (relationships) between nodes
  43. */
  44. export type EdgeKind =
  45. | 'contains' // Parent contains child (file→class, class→method)
  46. | 'calls' // Function/method calls another
  47. | 'imports' // File imports from another
  48. | 'exports' // File exports a symbol
  49. | 'extends' // Class/interface extends another
  50. | 'implements' // Class implements interface
  51. | 'references' // Generic reference to another symbol
  52. | 'type_of' // Variable/parameter has type
  53. | 'returns' // Function returns type
  54. | 'instantiates' // Creates instance of class
  55. | 'overrides' // Method overrides parent method
  56. | 'decorates'; // Decorator applied to symbol
  57. /**
  58. * Supported programming languages. See NODE_KINDS for why this is a
  59. * runtime-iterable const array.
  60. */
  61. export const LANGUAGES = [
  62. 'typescript',
  63. 'javascript',
  64. 'tsx',
  65. 'jsx',
  66. 'python',
  67. 'go',
  68. 'rust',
  69. 'java',
  70. 'c',
  71. 'cpp',
  72. 'csharp',
  73. 'razor',
  74. 'php',
  75. 'ruby',
  76. 'swift',
  77. 'kotlin',
  78. 'dart',
  79. 'svelte',
  80. 'vue',
  81. 'astro',
  82. 'liquid',
  83. 'pascal',
  84. 'scala',
  85. 'lua',
  86. 'luau',
  87. 'objc',
  88. 'r',
  89. 'yaml',
  90. 'twig',
  91. 'xml',
  92. 'properties',
  93. 'cfml',
  94. 'cfscript',
  95. 'cfquery',
  96. 'cobol',
  97. 'vbnet',
  98. 'erlang',
  99. 'unknown',
  100. ] as const;
  101. export type Language = (typeof LANGUAGES)[number];
  102. // =============================================================================
  103. // Core Graph Types
  104. // =============================================================================
  105. /**
  106. * A node in the knowledge graph representing a code symbol
  107. */
  108. export interface Node {
  109. /** Unique identifier (hash of file path + qualified name) */
  110. id: string;
  111. /** Type of code element */
  112. kind: NodeKind;
  113. /** Simple name (e.g., "calculateTotal") */
  114. name: string;
  115. /** Fully qualified name (e.g., "src/utils.ts::MathHelper.calculateTotal") */
  116. qualifiedName: string;
  117. /** File path relative to project root */
  118. filePath: string;
  119. /** Programming language */
  120. language: Language;
  121. /** Starting line number (1-indexed) */
  122. startLine: number;
  123. /** Ending line number (1-indexed) */
  124. endLine: number;
  125. /** Starting column (0-indexed) */
  126. startColumn: number;
  127. /** Ending column (0-indexed) */
  128. endColumn: number;
  129. /** Documentation string if present */
  130. docstring?: string;
  131. /** Function/method signature */
  132. signature?: string;
  133. /** Visibility modifier */
  134. visibility?: 'public' | 'private' | 'protected' | 'internal';
  135. /** Whether symbol is exported */
  136. isExported?: boolean;
  137. /** Whether symbol is async */
  138. isAsync?: boolean;
  139. /** Whether symbol is static */
  140. isStatic?: boolean;
  141. /** Whether symbol is abstract */
  142. isAbstract?: boolean;
  143. /** Decorators/annotations applied */
  144. decorators?: string[];
  145. /** Generic type parameters */
  146. typeParameters?: string[];
  147. /**
  148. * Normalized return/result type name for a function/method (the bare class
  149. * name, smart-pointer pointee unwrapped). Captured for C/C++ so resolution
  150. * can infer a chained receiver's type from what the inner call returns —
  151. * `Foo::instance().bar()` resolves `bar` on `Foo` (issue #645). Undefined for
  152. * languages/symbols where it isn't captured.
  153. */
  154. returnType?: string;
  155. /** When the node was last updated */
  156. updatedAt: number;
  157. }
  158. /**
  159. * An edge representing a relationship between two nodes
  160. */
  161. export interface Edge {
  162. /** Source node ID */
  163. source: string;
  164. /** Target node ID */
  165. target: string;
  166. /** Type of relationship */
  167. kind: EdgeKind;
  168. /** Additional context about the relationship */
  169. metadata?: Record<string, unknown>;
  170. /** Line number where relationship occurs (e.g., call site) */
  171. line?: number;
  172. /** Column number where relationship occurs */
  173. column?: number;
  174. /** How this edge was created */
  175. provenance?: 'tree-sitter' | 'scip' | 'heuristic';
  176. }
  177. /**
  178. * Metadata about a tracked file
  179. */
  180. export interface FileRecord {
  181. /** File path relative to project root */
  182. path: string;
  183. /** Content hash for change detection */
  184. contentHash: string;
  185. /** Detected language */
  186. language: Language;
  187. /** File size in bytes */
  188. size: number;
  189. /** Last modification timestamp */
  190. modifiedAt: number;
  191. /** When last indexed */
  192. indexedAt: number;
  193. /** Number of nodes extracted */
  194. nodeCount: number;
  195. /** Any extraction errors */
  196. errors?: ExtractionError[];
  197. }
  198. // =============================================================================
  199. // Extraction Types
  200. // =============================================================================
  201. /**
  202. * Result from parsing a source file
  203. */
  204. export interface ExtractionResult {
  205. /** Extracted nodes */
  206. nodes: Node[];
  207. /** Extracted edges */
  208. edges: Edge[];
  209. /** References that couldn't be resolved yet */
  210. unresolvedReferences: UnresolvedReference[];
  211. /** Any errors during extraction */
  212. errors: ExtractionError[];
  213. /** Extraction duration in milliseconds */
  214. durationMs: number;
  215. }
  216. /**
  217. * Error during code extraction
  218. */
  219. export interface ExtractionError {
  220. /** Error message */
  221. message: string;
  222. /** File path where the error occurred */
  223. filePath?: string;
  224. /** Line number if available */
  225. line?: number;
  226. /** Column number if available */
  227. column?: number;
  228. /** Error severity */
  229. severity: 'error' | 'warning';
  230. /** Error code for categorization */
  231. code?: string;
  232. }
  233. /**
  234. * Kinds an unresolved reference can carry. `function_ref` is internal-only —
  235. * a function name used as a VALUE (callback registration, #756). It never
  236. * becomes an edge kind: resolution maps it to a `references` edge targeting
  237. * function/method nodes only (see `matchFunctionRef`).
  238. */
  239. export type ReferenceKind = EdgeKind | 'function_ref';
  240. /**
  241. * A reference that couldn't be resolved during extraction
  242. */
  243. export interface UnresolvedReference {
  244. /** ID of the node containing the reference */
  245. fromNodeId: string;
  246. /** Name being referenced */
  247. referenceName: string;
  248. /** Type of reference (call, type, import, etc.) */
  249. referenceKind: ReferenceKind;
  250. /** Location of the reference */
  251. line: number;
  252. column: number;
  253. /** File path where reference occurs (denormalized for performance) */
  254. filePath?: string;
  255. /** Language of the source file (denormalized for performance) */
  256. language?: Language;
  257. /** Possible qualified names it might resolve to */
  258. candidates?: string[];
  259. }
  260. // =============================================================================
  261. // Query Types
  262. // =============================================================================
  263. /**
  264. * A subgraph containing a subset of the knowledge graph
  265. */
  266. export interface Subgraph {
  267. /** Nodes in this subgraph */
  268. nodes: Map<string, Node>;
  269. /** Edges in this subgraph */
  270. edges: Edge[];
  271. /** Root node IDs (entry points) */
  272. roots: string[];
  273. /**
  274. * Retrieval confidence for context-style queries. `'low'` means the query
  275. * resolved only to isolated common-word matches (no entry point corroborated
  276. * by 2+ distinct query terms) — callers should surface an honest handoff to
  277. * explore/trace rather than present the results as comprehensive. Undefined
  278. * for graph traversals that don't run the search-ranking path.
  279. */
  280. confidence?: 'high' | 'low';
  281. }
  282. /**
  283. * Options for graph traversal
  284. */
  285. export interface TraversalOptions {
  286. /** Maximum depth to traverse (default: Infinity) */
  287. maxDepth?: number;
  288. /** Edge types to follow (default: all) */
  289. edgeKinds?: EdgeKind[];
  290. /** Node types to include (default: all) */
  291. nodeKinds?: NodeKind[];
  292. /** Direction of traversal */
  293. direction?: 'outgoing' | 'incoming' | 'both';
  294. /** Maximum nodes to return */
  295. limit?: number;
  296. /** Whether to include the starting node */
  297. includeStart?: boolean;
  298. }
  299. /**
  300. * Options for searching the graph
  301. */
  302. export interface SearchOptions {
  303. /** Node types to search */
  304. kinds?: NodeKind[];
  305. /** Languages to include */
  306. languages?: Language[];
  307. /** File path patterns to include */
  308. includePatterns?: string[];
  309. /** File path patterns to exclude */
  310. excludePatterns?: string[];
  311. /** Maximum results to return */
  312. limit?: number;
  313. /** Offset for pagination */
  314. offset?: number;
  315. /** Whether search is case-sensitive */
  316. caseSensitive?: boolean;
  317. }
  318. /**
  319. * A search result with relevance scoring
  320. */
  321. export interface SearchResult {
  322. /** Matching node */
  323. node: Node;
  324. /**
  325. * Relevance score for relative ranking only — higher is more relevant.
  326. * NOT normalized and NOT a 0-1 fraction: the FTS path returns an unbounded
  327. * BM25 magnitude (often in the tens or hundreds), while the fuzzy/exact
  328. * paths return ~0-1. Use it to order results, not as an absolute percentage.
  329. */
  330. score: number;
  331. /** Matched text snippets for highlighting */
  332. highlights?: string[];
  333. }
  334. /**
  335. * A symbol whose name-segments match prose words from a prompt — the
  336. * graph-derived signal behind the front-load hook's medium tier
  337. * (CodeGraph.getSegmentMatches). Always verified to exist in `nodes` at the
  338. * time it is returned.
  339. */
  340. export interface SegmentMatch {
  341. /** Symbol name as indexed (e.g. `OrderStateMachine`). */
  342. name: string;
  343. /** Kind of the representative definition. */
  344. kind: NodeKind;
  345. /** File of the representative definition. */
  346. filePath: string;
  347. /** 1-based start line of the representative definition. */
  348. startLine: number;
  349. /** The prompt words (normalized) that matched this name's segments. */
  350. matchedWords: string[];
  351. }
  352. // =============================================================================
  353. // Context Types
  354. // =============================================================================
  355. /**
  356. * Context information for code understanding
  357. */
  358. export interface Context {
  359. /** Primary node being examined */
  360. focal: Node;
  361. /** Nodes containing the focal node (file, class, etc.) */
  362. ancestors: Node[];
  363. /** Nodes directly contained by focal node */
  364. children: Node[];
  365. /** Incoming references (who calls/uses this) */
  366. incomingRefs: Array<{ node: Node; edge: Edge }>;
  367. /** Outgoing references (what this calls/uses) */
  368. outgoingRefs: Array<{ node: Node; edge: Edge }>;
  369. /** Related type information */
  370. types: Node[];
  371. /** Relevant imports */
  372. imports: Node[];
  373. }
  374. /**
  375. * A block of code with context
  376. */
  377. export interface CodeBlock {
  378. /** The code content */
  379. content: string;
  380. /** File path */
  381. filePath: string;
  382. /** Starting line */
  383. startLine: number;
  384. /** Ending line */
  385. endLine: number;
  386. /** Language for syntax highlighting */
  387. language: Language;
  388. /** Associated node if extracted */
  389. node?: Node;
  390. }
  391. // =============================================================================
  392. // Database Types
  393. // =============================================================================
  394. /**
  395. * Database schema version info
  396. */
  397. export interface SchemaVersion {
  398. /** Current schema version */
  399. version: number;
  400. /** When schema was created/updated */
  401. appliedAt: number;
  402. /** Description of this version */
  403. description?: string;
  404. }
  405. /**
  406. * Statistics about the knowledge graph
  407. */
  408. export interface GraphStats {
  409. /** Total number of nodes */
  410. nodeCount: number;
  411. /** Total number of edges */
  412. edgeCount: number;
  413. /** Number of tracked files */
  414. fileCount: number;
  415. /** Node counts by kind */
  416. nodesByKind: Record<NodeKind, number>;
  417. /** Edge counts by kind */
  418. edgesByKind: Record<EdgeKind, number>;
  419. /** File counts by language */
  420. filesByLanguage: Record<Language, number>;
  421. /** Database size in bytes */
  422. dbSizeBytes: number;
  423. /** Last update timestamp */
  424. lastUpdated: number;
  425. }
  426. // =============================================================================
  427. // Task Context Types (for buildContext)
  428. // =============================================================================
  429. /**
  430. * Input for building task context
  431. */
  432. export type TaskInput = string | { title: string; description?: string };
  433. /**
  434. * Options for building task context
  435. */
  436. export interface BuildContextOptions {
  437. /** Maximum number of nodes to include (default: 50) */
  438. maxNodes?: number;
  439. /** Maximum number of code blocks to include (default: 10) */
  440. maxCodeBlocks?: number;
  441. /** Maximum characters per code block (default: 2000) */
  442. maxCodeBlockSize?: number;
  443. /** Whether to include code blocks (default: true) */
  444. includeCode?: boolean;
  445. /** Output format (default: 'markdown') */
  446. format?: 'markdown' | 'json';
  447. /** Number of semantic search results (default: 5) */
  448. searchLimit?: number;
  449. /** Graph traversal depth from entry points (default: 2) */
  450. traversalDepth?: number;
  451. /** Minimum semantic similarity score (default: 0.3) */
  452. minScore?: number;
  453. }
  454. /**
  455. * Full context for a task, ready for Claude
  456. */
  457. export interface TaskContext {
  458. /** The original query/task */
  459. query: string;
  460. /** Subgraph of relevant nodes and edges */
  461. subgraph: Subgraph;
  462. /** Entry point nodes (from semantic search) */
  463. entryPoints: Node[];
  464. /** Code blocks extracted from key nodes */
  465. codeBlocks: CodeBlock[];
  466. /** Files involved in this context */
  467. relatedFiles: string[];
  468. /** Brief summary of the context */
  469. summary: string;
  470. /** Statistics about the context */
  471. stats: {
  472. /** Number of nodes included */
  473. nodeCount: number;
  474. /** Number of edges included */
  475. edgeCount: number;
  476. /** Number of files touched */
  477. fileCount: number;
  478. /** Number of code blocks included */
  479. codeBlockCount: number;
  480. /** Total characters in code blocks */
  481. totalCodeSize: number;
  482. };
  483. }
  484. /**
  485. * Options for finding relevant context
  486. */
  487. export interface FindRelevantContextOptions {
  488. /** Number of semantic search results (default: 5) */
  489. searchLimit?: number;
  490. /** Graph traversal depth (default: 2) */
  491. traversalDepth?: number;
  492. /** Maximum nodes in result (default: 50) */
  493. maxNodes?: number;
  494. /** Minimum semantic similarity score (default: 0.3) */
  495. minScore?: number;
  496. /** Edge types to follow in traversal */
  497. edgeKinds?: EdgeKind[];
  498. /** Node types to include */
  499. nodeKinds?: NodeKind[];
  500. }