types.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. /**
  251. * Options for graph traversal
  252. */
  253. export interface TraversalOptions {
  254. /** Maximum depth to traverse (default: Infinity) */
  255. maxDepth?: number;
  256. /** Edge types to follow (default: all) */
  257. edgeKinds?: EdgeKind[];
  258. /** Node types to include (default: all) */
  259. nodeKinds?: NodeKind[];
  260. /** Direction of traversal */
  261. direction?: 'outgoing' | 'incoming' | 'both';
  262. /** Maximum nodes to return */
  263. limit?: number;
  264. /** Whether to include the starting node */
  265. includeStart?: boolean;
  266. }
  267. /**
  268. * Options for searching the graph
  269. */
  270. export interface SearchOptions {
  271. /** Node types to search */
  272. kinds?: NodeKind[];
  273. /** Languages to include */
  274. languages?: Language[];
  275. /** File path patterns to include */
  276. includePatterns?: string[];
  277. /** File path patterns to exclude */
  278. excludePatterns?: string[];
  279. /** Maximum results to return */
  280. limit?: number;
  281. /** Offset for pagination */
  282. offset?: number;
  283. /** Whether search is case-sensitive */
  284. caseSensitive?: boolean;
  285. }
  286. /**
  287. * A search result with relevance scoring
  288. */
  289. export interface SearchResult {
  290. /** Matching node */
  291. node: Node;
  292. /** Relevance score (0-1) */
  293. score: number;
  294. /** Matched text snippets for highlighting */
  295. highlights?: string[];
  296. }
  297. // =============================================================================
  298. // Context Types
  299. // =============================================================================
  300. /**
  301. * Context information for code understanding
  302. */
  303. export interface Context {
  304. /** Primary node being examined */
  305. focal: Node;
  306. /** Nodes containing the focal node (file, class, etc.) */
  307. ancestors: Node[];
  308. /** Nodes directly contained by focal node */
  309. children: Node[];
  310. /** Incoming references (who calls/uses this) */
  311. incomingRefs: Array<{ node: Node; edge: Edge }>;
  312. /** Outgoing references (what this calls/uses) */
  313. outgoingRefs: Array<{ node: Node; edge: Edge }>;
  314. /** Related type information */
  315. types: Node[];
  316. /** Relevant imports */
  317. imports: Node[];
  318. }
  319. /**
  320. * A block of code with context
  321. */
  322. export interface CodeBlock {
  323. /** The code content */
  324. content: string;
  325. /** File path */
  326. filePath: string;
  327. /** Starting line */
  328. startLine: number;
  329. /** Ending line */
  330. endLine: number;
  331. /** Language for syntax highlighting */
  332. language: Language;
  333. /** Associated node if extracted */
  334. node?: Node;
  335. }
  336. // =============================================================================
  337. // Database Types
  338. // =============================================================================
  339. /**
  340. * Database schema version info
  341. */
  342. export interface SchemaVersion {
  343. /** Current schema version */
  344. version: number;
  345. /** When schema was created/updated */
  346. appliedAt: number;
  347. /** Description of this version */
  348. description?: string;
  349. }
  350. /**
  351. * Statistics about the knowledge graph
  352. */
  353. export interface GraphStats {
  354. /** Total number of nodes */
  355. nodeCount: number;
  356. /** Total number of edges */
  357. edgeCount: number;
  358. /** Number of tracked files */
  359. fileCount: number;
  360. /** Node counts by kind */
  361. nodesByKind: Record<NodeKind, number>;
  362. /** Edge counts by kind */
  363. edgesByKind: Record<EdgeKind, number>;
  364. /** File counts by language */
  365. filesByLanguage: Record<Language, number>;
  366. /** Database size in bytes */
  367. dbSizeBytes: number;
  368. /** Last update timestamp */
  369. lastUpdated: number;
  370. }
  371. // =============================================================================
  372. // Task Context Types (for buildContext)
  373. // =============================================================================
  374. /**
  375. * Input for building task context
  376. */
  377. export type TaskInput = string | { title: string; description?: string };
  378. /**
  379. * Options for building task context
  380. */
  381. export interface BuildContextOptions {
  382. /** Maximum number of nodes to include (default: 50) */
  383. maxNodes?: number;
  384. /** Maximum number of code blocks to include (default: 10) */
  385. maxCodeBlocks?: number;
  386. /** Maximum characters per code block (default: 2000) */
  387. maxCodeBlockSize?: number;
  388. /** Whether to include code blocks (default: true) */
  389. includeCode?: boolean;
  390. /** Output format (default: 'markdown') */
  391. format?: 'markdown' | 'json';
  392. /** Number of semantic search results (default: 5) */
  393. searchLimit?: number;
  394. /** Graph traversal depth from entry points (default: 2) */
  395. traversalDepth?: number;
  396. /** Minimum semantic similarity score (default: 0.3) */
  397. minScore?: number;
  398. }
  399. /**
  400. * Full context for a task, ready for Claude
  401. */
  402. export interface TaskContext {
  403. /** The original query/task */
  404. query: string;
  405. /** Subgraph of relevant nodes and edges */
  406. subgraph: Subgraph;
  407. /** Entry point nodes (from semantic search) */
  408. entryPoints: Node[];
  409. /** Code blocks extracted from key nodes */
  410. codeBlocks: CodeBlock[];
  411. /** Files involved in this context */
  412. relatedFiles: string[];
  413. /** Brief summary of the context */
  414. summary: string;
  415. /** Statistics about the context */
  416. stats: {
  417. /** Number of nodes included */
  418. nodeCount: number;
  419. /** Number of edges included */
  420. edgeCount: number;
  421. /** Number of files touched */
  422. fileCount: number;
  423. /** Number of code blocks included */
  424. codeBlockCount: number;
  425. /** Total characters in code blocks */
  426. totalCodeSize: number;
  427. };
  428. }
  429. /**
  430. * Options for finding relevant context
  431. */
  432. export interface FindRelevantContextOptions {
  433. /** Number of semantic search results (default: 5) */
  434. searchLimit?: number;
  435. /** Graph traversal depth (default: 2) */
  436. traversalDepth?: number;
  437. /** Maximum nodes in result (default: 50) */
  438. maxNodes?: number;
  439. /** Minimum semantic similarity score (default: 0.3) */
  440. minScore?: number;
  441. /** Edge types to follow in traversal */
  442. edgeKinds?: EdgeKind[];
  443. /** Node types to include */
  444. nodeKinds?: NodeKind[];
  445. }