types.ts 13 KB

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