types.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. 'php',
  74. 'ruby',
  75. 'swift',
  76. 'kotlin',
  77. 'dart',
  78. 'svelte',
  79. 'vue',
  80. 'liquid',
  81. 'pascal',
  82. 'scala',
  83. 'lua',
  84. 'luau',
  85. 'objc',
  86. 'yaml',
  87. 'twig',
  88. 'xml',
  89. 'properties',
  90. 'unknown',
  91. ] as const;
  92. export type Language = (typeof LANGUAGES)[number];
  93. // =============================================================================
  94. // Core Graph Types
  95. // =============================================================================
  96. /**
  97. * A node in the knowledge graph representing a code symbol
  98. */
  99. export interface Node {
  100. /** Unique identifier (hash of file path + qualified name) */
  101. id: string;
  102. /** Type of code element */
  103. kind: NodeKind;
  104. /** Simple name (e.g., "calculateTotal") */
  105. name: string;
  106. /** Fully qualified name (e.g., "src/utils.ts::MathHelper.calculateTotal") */
  107. qualifiedName: string;
  108. /** File path relative to project root */
  109. filePath: string;
  110. /** Programming language */
  111. language: Language;
  112. /** Starting line number (1-indexed) */
  113. startLine: number;
  114. /** Ending line number (1-indexed) */
  115. endLine: number;
  116. /** Starting column (0-indexed) */
  117. startColumn: number;
  118. /** Ending column (0-indexed) */
  119. endColumn: number;
  120. /** Documentation string if present */
  121. docstring?: string;
  122. /** Function/method signature */
  123. signature?: string;
  124. /** Visibility modifier */
  125. visibility?: 'public' | 'private' | 'protected' | 'internal';
  126. /** Whether symbol is exported */
  127. isExported?: boolean;
  128. /** Whether symbol is async */
  129. isAsync?: boolean;
  130. /** Whether symbol is static */
  131. isStatic?: boolean;
  132. /** Whether symbol is abstract */
  133. isAbstract?: boolean;
  134. /** Decorators/annotations applied */
  135. decorators?: string[];
  136. /** Generic type parameters */
  137. typeParameters?: string[];
  138. /** When the node was last updated */
  139. updatedAt: number;
  140. }
  141. /**
  142. * An edge representing a relationship between two nodes
  143. */
  144. export interface Edge {
  145. /** Source node ID */
  146. source: string;
  147. /** Target node ID */
  148. target: string;
  149. /** Type of relationship */
  150. kind: EdgeKind;
  151. /** Additional context about the relationship */
  152. metadata?: Record<string, unknown>;
  153. /** Line number where relationship occurs (e.g., call site) */
  154. line?: number;
  155. /** Column number where relationship occurs */
  156. column?: number;
  157. /** How this edge was created */
  158. provenance?: 'tree-sitter' | 'scip' | 'heuristic';
  159. }
  160. /**
  161. * Metadata about a tracked file
  162. */
  163. export interface FileRecord {
  164. /** File path relative to project root */
  165. path: string;
  166. /** Content hash for change detection */
  167. contentHash: string;
  168. /** Detected language */
  169. language: Language;
  170. /** File size in bytes */
  171. size: number;
  172. /** Last modification timestamp */
  173. modifiedAt: number;
  174. /** When last indexed */
  175. indexedAt: number;
  176. /** Number of nodes extracted */
  177. nodeCount: number;
  178. /** Any extraction errors */
  179. errors?: ExtractionError[];
  180. }
  181. // =============================================================================
  182. // Extraction Types
  183. // =============================================================================
  184. /**
  185. * Result from parsing a source file
  186. */
  187. export interface ExtractionResult {
  188. /** Extracted nodes */
  189. nodes: Node[];
  190. /** Extracted edges */
  191. edges: Edge[];
  192. /** References that couldn't be resolved yet */
  193. unresolvedReferences: UnresolvedReference[];
  194. /** Any errors during extraction */
  195. errors: ExtractionError[];
  196. /** Extraction duration in milliseconds */
  197. durationMs: number;
  198. }
  199. /**
  200. * Error during code extraction
  201. */
  202. export interface ExtractionError {
  203. /** Error message */
  204. message: string;
  205. /** File path where the error occurred */
  206. filePath?: string;
  207. /** Line number if available */
  208. line?: number;
  209. /** Column number if available */
  210. column?: number;
  211. /** Error severity */
  212. severity: 'error' | 'warning';
  213. /** Error code for categorization */
  214. code?: string;
  215. }
  216. /**
  217. * A reference that couldn't be resolved during extraction
  218. */
  219. export interface UnresolvedReference {
  220. /** ID of the node containing the reference */
  221. fromNodeId: string;
  222. /** Name being referenced */
  223. referenceName: string;
  224. /** Type of reference (call, type, import, etc.) */
  225. referenceKind: EdgeKind;
  226. /** Location of the reference */
  227. line: number;
  228. column: number;
  229. /** File path where reference occurs (denormalized for performance) */
  230. filePath?: string;
  231. /** Language of the source file (denormalized for performance) */
  232. language?: Language;
  233. /** Possible qualified names it might resolve to */
  234. candidates?: string[];
  235. }
  236. // =============================================================================
  237. // Query Types
  238. // =============================================================================
  239. /**
  240. * A subgraph containing a subset of the knowledge graph
  241. */
  242. export interface Subgraph {
  243. /** Nodes in this subgraph */
  244. nodes: Map<string, Node>;
  245. /** Edges in this subgraph */
  246. edges: Edge[];
  247. /** Root node IDs (entry points) */
  248. roots: string[];
  249. /**
  250. * Retrieval confidence for context-style queries. `'low'` means the query
  251. * resolved only to isolated common-word matches (no entry point corroborated
  252. * by 2+ distinct query terms) — callers should surface an honest handoff to
  253. * explore/trace rather than present the results as comprehensive. Undefined
  254. * for graph traversals that don't run the search-ranking path.
  255. */
  256. confidence?: 'high' | 'low';
  257. }
  258. /**
  259. * Options for graph traversal
  260. */
  261. export interface TraversalOptions {
  262. /** Maximum depth to traverse (default: Infinity) */
  263. maxDepth?: number;
  264. /** Edge types to follow (default: all) */
  265. edgeKinds?: EdgeKind[];
  266. /** Node types to include (default: all) */
  267. nodeKinds?: NodeKind[];
  268. /** Direction of traversal */
  269. direction?: 'outgoing' | 'incoming' | 'both';
  270. /** Maximum nodes to return */
  271. limit?: number;
  272. /** Whether to include the starting node */
  273. includeStart?: boolean;
  274. }
  275. /**
  276. * Options for searching the graph
  277. */
  278. export interface SearchOptions {
  279. /** Node types to search */
  280. kinds?: NodeKind[];
  281. /** Languages to include */
  282. languages?: Language[];
  283. /** File path patterns to include */
  284. includePatterns?: string[];
  285. /** File path patterns to exclude */
  286. excludePatterns?: string[];
  287. /** Maximum results to return */
  288. limit?: number;
  289. /** Offset for pagination */
  290. offset?: number;
  291. /** Whether search is case-sensitive */
  292. caseSensitive?: boolean;
  293. }
  294. /**
  295. * A search result with relevance scoring
  296. */
  297. export interface SearchResult {
  298. /** Matching node */
  299. node: Node;
  300. /** Relevance score (0-1) */
  301. score: number;
  302. /** Matched text snippets for highlighting */
  303. highlights?: string[];
  304. }
  305. // =============================================================================
  306. // Context Types
  307. // =============================================================================
  308. /**
  309. * Context information for code understanding
  310. */
  311. export interface Context {
  312. /** Primary node being examined */
  313. focal: Node;
  314. /** Nodes containing the focal node (file, class, etc.) */
  315. ancestors: Node[];
  316. /** Nodes directly contained by focal node */
  317. children: Node[];
  318. /** Incoming references (who calls/uses this) */
  319. incomingRefs: Array<{ node: Node; edge: Edge }>;
  320. /** Outgoing references (what this calls/uses) */
  321. outgoingRefs: Array<{ node: Node; edge: Edge }>;
  322. /** Related type information */
  323. types: Node[];
  324. /** Relevant imports */
  325. imports: Node[];
  326. }
  327. /**
  328. * A block of code with context
  329. */
  330. export interface CodeBlock {
  331. /** The code content */
  332. content: string;
  333. /** File path */
  334. filePath: string;
  335. /** Starting line */
  336. startLine: number;
  337. /** Ending line */
  338. endLine: number;
  339. /** Language for syntax highlighting */
  340. language: Language;
  341. /** Associated node if extracted */
  342. node?: Node;
  343. }
  344. // =============================================================================
  345. // Database Types
  346. // =============================================================================
  347. /**
  348. * Database schema version info
  349. */
  350. export interface SchemaVersion {
  351. /** Current schema version */
  352. version: number;
  353. /** When schema was created/updated */
  354. appliedAt: number;
  355. /** Description of this version */
  356. description?: string;
  357. }
  358. /**
  359. * Statistics about the knowledge graph
  360. */
  361. export interface GraphStats {
  362. /** Total number of nodes */
  363. nodeCount: number;
  364. /** Total number of edges */
  365. edgeCount: number;
  366. /** Number of tracked files */
  367. fileCount: number;
  368. /** Node counts by kind */
  369. nodesByKind: Record<NodeKind, number>;
  370. /** Edge counts by kind */
  371. edgesByKind: Record<EdgeKind, number>;
  372. /** File counts by language */
  373. filesByLanguage: Record<Language, number>;
  374. /** Database size in bytes */
  375. dbSizeBytes: number;
  376. /** Last update timestamp */
  377. lastUpdated: number;
  378. }
  379. // =============================================================================
  380. // Task Context Types (for buildContext)
  381. // =============================================================================
  382. /**
  383. * Input for building task context
  384. */
  385. export type TaskInput = string | { title: string; description?: string };
  386. /**
  387. * Options for building task context
  388. */
  389. export interface BuildContextOptions {
  390. /** Maximum number of nodes to include (default: 50) */
  391. maxNodes?: number;
  392. /** Maximum number of code blocks to include (default: 10) */
  393. maxCodeBlocks?: number;
  394. /** Maximum characters per code block (default: 2000) */
  395. maxCodeBlockSize?: number;
  396. /** Whether to include code blocks (default: true) */
  397. includeCode?: boolean;
  398. /** Output format (default: 'markdown') */
  399. format?: 'markdown' | 'json';
  400. /** Number of semantic search results (default: 5) */
  401. searchLimit?: number;
  402. /** Graph traversal depth from entry points (default: 2) */
  403. traversalDepth?: number;
  404. /** Minimum semantic similarity score (default: 0.3) */
  405. minScore?: number;
  406. }
  407. /**
  408. * Full context for a task, ready for Claude
  409. */
  410. export interface TaskContext {
  411. /** The original query/task */
  412. query: string;
  413. /** Subgraph of relevant nodes and edges */
  414. subgraph: Subgraph;
  415. /** Entry point nodes (from semantic search) */
  416. entryPoints: Node[];
  417. /** Code blocks extracted from key nodes */
  418. codeBlocks: CodeBlock[];
  419. /** Files involved in this context */
  420. relatedFiles: string[];
  421. /** Brief summary of the context */
  422. summary: string;
  423. /** Statistics about the context */
  424. stats: {
  425. /** Number of nodes included */
  426. nodeCount: number;
  427. /** Number of edges included */
  428. edgeCount: number;
  429. /** Number of files touched */
  430. fileCount: number;
  431. /** Number of code blocks included */
  432. codeBlockCount: number;
  433. /** Total characters in code blocks */
  434. totalCodeSize: number;
  435. };
  436. }
  437. /**
  438. * Options for finding relevant context
  439. */
  440. export interface FindRelevantContextOptions {
  441. /** Number of semantic search results (default: 5) */
  442. searchLimit?: number;
  443. /** Graph traversal depth (default: 2) */
  444. traversalDepth?: number;
  445. /** Maximum nodes in result (default: 50) */
  446. maxNodes?: number;
  447. /** Minimum semantic similarity score (default: 0.3) */
  448. minScore?: number;
  449. /** Edge types to follow in traversal */
  450. edgeKinds?: EdgeKind[];
  451. /** Node types to include */
  452. nodeKinds?: NodeKind[];
  453. }