types.ts 15 KB

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