types.ts 12 KB

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