types.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. export type NodeKind =
  13. | 'file'
  14. | 'module'
  15. | 'class'
  16. | 'struct'
  17. | 'interface'
  18. | 'trait'
  19. | 'protocol'
  20. | 'function'
  21. | 'method'
  22. | 'property'
  23. | 'field'
  24. | 'variable'
  25. | 'constant'
  26. | 'enum'
  27. | 'enum_member'
  28. | 'type_alias'
  29. | 'namespace'
  30. | 'parameter'
  31. | 'import'
  32. | 'export'
  33. | 'route'
  34. | 'component';
  35. /**
  36. * Types of edges (relationships) between nodes
  37. */
  38. export type EdgeKind =
  39. | 'contains' // Parent contains child (file→class, class→method)
  40. | 'calls' // Function/method calls another
  41. | 'imports' // File imports from another
  42. | 'exports' // File exports a symbol
  43. | 'extends' // Class/interface extends another
  44. | 'implements' // Class implements interface
  45. | 'references' // Generic reference to another symbol
  46. | 'type_of' // Variable/parameter has type
  47. | 'returns' // Function returns type
  48. | 'instantiates' // Creates instance of class
  49. | 'overrides' // Method overrides parent method
  50. | 'decorates'; // Decorator applied to symbol
  51. /**
  52. * Supported programming languages
  53. */
  54. export type Language =
  55. | 'typescript'
  56. | 'javascript'
  57. | 'tsx'
  58. | 'jsx'
  59. | 'python'
  60. | 'go'
  61. | 'rust'
  62. | 'java'
  63. | 'c'
  64. | 'cpp'
  65. | 'csharp'
  66. | 'php'
  67. | 'ruby'
  68. | 'swift'
  69. | 'kotlin'
  70. | 'unknown';
  71. // =============================================================================
  72. // Core Graph Types
  73. // =============================================================================
  74. /**
  75. * A node in the knowledge graph representing a code symbol
  76. */
  77. export interface Node {
  78. /** Unique identifier (hash of file path + qualified name) */
  79. id: string;
  80. /** Type of code element */
  81. kind: NodeKind;
  82. /** Simple name (e.g., "calculateTotal") */
  83. name: string;
  84. /** Fully qualified name (e.g., "src/utils.ts::MathHelper.calculateTotal") */
  85. qualifiedName: string;
  86. /** File path relative to project root */
  87. filePath: string;
  88. /** Programming language */
  89. language: Language;
  90. /** Starting line number (1-indexed) */
  91. startLine: number;
  92. /** Ending line number (1-indexed) */
  93. endLine: number;
  94. /** Starting column (0-indexed) */
  95. startColumn: number;
  96. /** Ending column (0-indexed) */
  97. endColumn: number;
  98. /** Documentation string if present */
  99. docstring?: string;
  100. /** Function/method signature */
  101. signature?: string;
  102. /** Visibility modifier */
  103. visibility?: 'public' | 'private' | 'protected' | 'internal';
  104. /** Whether symbol is exported */
  105. isExported?: boolean;
  106. /** Whether symbol is async */
  107. isAsync?: boolean;
  108. /** Whether symbol is static */
  109. isStatic?: boolean;
  110. /** Whether symbol is abstract */
  111. isAbstract?: boolean;
  112. /** Decorators/annotations applied */
  113. decorators?: string[];
  114. /** Generic type parameters */
  115. typeParameters?: string[];
  116. /** When the node was last updated */
  117. updatedAt: number;
  118. }
  119. /**
  120. * An edge representing a relationship between two nodes
  121. */
  122. export interface Edge {
  123. /** Source node ID */
  124. source: string;
  125. /** Target node ID */
  126. target: string;
  127. /** Type of relationship */
  128. kind: EdgeKind;
  129. /** Additional context about the relationship */
  130. metadata?: Record<string, unknown>;
  131. /** Line number where relationship occurs (e.g., call site) */
  132. line?: number;
  133. /** Column number where relationship occurs */
  134. column?: number;
  135. }
  136. /**
  137. * Metadata about a tracked file
  138. */
  139. export interface FileRecord {
  140. /** File path relative to project root */
  141. path: string;
  142. /** Content hash for change detection */
  143. contentHash: string;
  144. /** Detected language */
  145. language: Language;
  146. /** File size in bytes */
  147. size: number;
  148. /** Last modification timestamp */
  149. modifiedAt: number;
  150. /** When last indexed */
  151. indexedAt: number;
  152. /** Number of nodes extracted */
  153. nodeCount: number;
  154. /** Any extraction errors */
  155. errors?: ExtractionError[];
  156. }
  157. // =============================================================================
  158. // Extraction Types
  159. // =============================================================================
  160. /**
  161. * Result from parsing a source file
  162. */
  163. export interface ExtractionResult {
  164. /** Extracted nodes */
  165. nodes: Node[];
  166. /** Extracted edges */
  167. edges: Edge[];
  168. /** References that couldn't be resolved yet */
  169. unresolvedReferences: UnresolvedReference[];
  170. /** Any errors during extraction */
  171. errors: ExtractionError[];
  172. /** Extraction duration in milliseconds */
  173. durationMs: number;
  174. }
  175. /**
  176. * Error during code extraction
  177. */
  178. export interface ExtractionError {
  179. /** Error message */
  180. message: string;
  181. /** Line number if available */
  182. line?: number;
  183. /** Column number if available */
  184. column?: number;
  185. /** Error severity */
  186. severity: 'error' | 'warning';
  187. /** Error code for categorization */
  188. code?: string;
  189. }
  190. /**
  191. * A reference that couldn't be resolved during extraction
  192. */
  193. export interface UnresolvedReference {
  194. /** ID of the node containing the reference */
  195. fromNodeId: string;
  196. /** Name being referenced */
  197. referenceName: string;
  198. /** Type of reference (call, type, import, etc.) */
  199. referenceKind: EdgeKind;
  200. /** Location of the reference */
  201. line: number;
  202. column: number;
  203. /** Possible qualified names it might resolve to */
  204. candidates?: string[];
  205. }
  206. // =============================================================================
  207. // Query Types
  208. // =============================================================================
  209. /**
  210. * A subgraph containing a subset of the knowledge graph
  211. */
  212. export interface Subgraph {
  213. /** Nodes in this subgraph */
  214. nodes: Map<string, Node>;
  215. /** Edges in this subgraph */
  216. edges: Edge[];
  217. /** Root node IDs (entry points) */
  218. roots: string[];
  219. }
  220. /**
  221. * Options for graph traversal
  222. */
  223. export interface TraversalOptions {
  224. /** Maximum depth to traverse (default: Infinity) */
  225. maxDepth?: number;
  226. /** Edge types to follow (default: all) */
  227. edgeKinds?: EdgeKind[];
  228. /** Node types to include (default: all) */
  229. nodeKinds?: NodeKind[];
  230. /** Direction of traversal */
  231. direction?: 'outgoing' | 'incoming' | 'both';
  232. /** Maximum nodes to return */
  233. limit?: number;
  234. /** Whether to include the starting node */
  235. includeStart?: boolean;
  236. }
  237. /**
  238. * Options for searching the graph
  239. */
  240. export interface SearchOptions {
  241. /** Node types to search */
  242. kinds?: NodeKind[];
  243. /** Languages to include */
  244. languages?: Language[];
  245. /** File path patterns to include */
  246. includePatterns?: string[];
  247. /** File path patterns to exclude */
  248. excludePatterns?: string[];
  249. /** Maximum results to return */
  250. limit?: number;
  251. /** Offset for pagination */
  252. offset?: number;
  253. /** Whether search is case-sensitive */
  254. caseSensitive?: boolean;
  255. }
  256. /**
  257. * A search result with relevance scoring
  258. */
  259. export interface SearchResult {
  260. /** Matching node */
  261. node: Node;
  262. /** Relevance score (0-1) */
  263. score: number;
  264. /** Matched text snippets for highlighting */
  265. highlights?: string[];
  266. }
  267. // =============================================================================
  268. // Context Types
  269. // =============================================================================
  270. /**
  271. * Context information for code understanding
  272. */
  273. export interface Context {
  274. /** Primary node being examined */
  275. focal: Node;
  276. /** Nodes containing the focal node (file, class, etc.) */
  277. ancestors: Node[];
  278. /** Nodes directly contained by focal node */
  279. children: Node[];
  280. /** Incoming references (who calls/uses this) */
  281. incomingRefs: Array<{ node: Node; edge: Edge }>;
  282. /** Outgoing references (what this calls/uses) */
  283. outgoingRefs: Array<{ node: Node; edge: Edge }>;
  284. /** Related type information */
  285. types: Node[];
  286. /** Relevant imports */
  287. imports: Node[];
  288. }
  289. /**
  290. * A block of code with context
  291. */
  292. export interface CodeBlock {
  293. /** The code content */
  294. content: string;
  295. /** File path */
  296. filePath: string;
  297. /** Starting line */
  298. startLine: number;
  299. /** Ending line */
  300. endLine: number;
  301. /** Language for syntax highlighting */
  302. language: Language;
  303. /** Associated node if extracted */
  304. node?: Node;
  305. }
  306. // =============================================================================
  307. // Configuration Types
  308. // =============================================================================
  309. /**
  310. * Framework-specific hints for better extraction
  311. */
  312. export interface FrameworkHint {
  313. /** Framework name (react, express, django, etc.) */
  314. name: string;
  315. /** Version constraint if relevant */
  316. version?: string;
  317. /** Custom patterns for this framework */
  318. patterns?: {
  319. /** Component detection patterns */
  320. components?: string[];
  321. /** Route detection patterns */
  322. routes?: string[];
  323. /** Model detection patterns */
  324. models?: string[];
  325. };
  326. }
  327. /**
  328. * Configuration for a CodeGraph project
  329. */
  330. export interface CodeGraphConfig {
  331. /** Schema version for migrations */
  332. version: number;
  333. /** Root directory of the project */
  334. rootDir: string;
  335. /** Glob patterns for files to include */
  336. include: string[];
  337. /** Glob patterns for files to exclude */
  338. exclude: string[];
  339. /** Languages to process (auto-detected if empty) */
  340. languages: Language[];
  341. /** Framework hints for better extraction */
  342. frameworks: FrameworkHint[];
  343. /** Maximum file size to process (in bytes) */
  344. maxFileSize: number;
  345. /** Whether to extract docstrings */
  346. extractDocstrings: boolean;
  347. /** Whether to track call sites */
  348. trackCallSites: boolean;
  349. /** Whether to compute embeddings for semantic search */
  350. enableEmbeddings: boolean;
  351. /** Custom symbol patterns to extract */
  352. customPatterns?: {
  353. /** Name for this pattern group */
  354. name: string;
  355. /** Regex pattern to match */
  356. pattern: string;
  357. /** Node kind to assign */
  358. kind: NodeKind;
  359. }[];
  360. }
  361. /**
  362. * Default configuration values
  363. */
  364. export const DEFAULT_CONFIG: CodeGraphConfig = {
  365. version: 1,
  366. rootDir: '.',
  367. include: [
  368. // TypeScript/JavaScript
  369. '**/*.ts',
  370. '**/*.tsx',
  371. '**/*.js',
  372. '**/*.jsx',
  373. // Python
  374. '**/*.py',
  375. // Go
  376. '**/*.go',
  377. // Rust
  378. '**/*.rs',
  379. // Java
  380. '**/*.java',
  381. // C/C++
  382. '**/*.c',
  383. '**/*.h',
  384. '**/*.cpp',
  385. '**/*.hpp',
  386. '**/*.cc',
  387. '**/*.cxx',
  388. // C#
  389. '**/*.cs',
  390. // PHP
  391. '**/*.php',
  392. // Ruby
  393. '**/*.rb',
  394. ],
  395. exclude: [
  396. // Version control
  397. '**/.git/**',
  398. // Dependencies
  399. '**/node_modules/**',
  400. '**/vendor/**',
  401. '**/Pods/**',
  402. // Generic build outputs
  403. '**/dist/**',
  404. '**/build/**',
  405. '**/out/**',
  406. '**/bin/**',
  407. '**/obj/**',
  408. '**/target/**',
  409. // JavaScript/TypeScript
  410. '**/*.min.js',
  411. '**/*.bundle.js',
  412. '**/.next/**',
  413. '**/.nuxt/**',
  414. '**/.svelte-kit/**',
  415. '**/.output/**',
  416. '**/.turbo/**',
  417. '**/.cache/**',
  418. '**/.parcel-cache/**',
  419. '**/.vite/**',
  420. '**/.astro/**',
  421. '**/.docusaurus/**',
  422. '**/.gatsby/**',
  423. '**/.webpack/**',
  424. '**/.nx/**',
  425. '**/.yarn/cache/**',
  426. '**/.pnpm-store/**',
  427. '**/storybook-static/**',
  428. // React Native / Expo
  429. '**/.expo/**',
  430. '**/web-build/**',
  431. '**/ios/Pods/**',
  432. '**/ios/build/**',
  433. '**/android/build/**',
  434. '**/android/.gradle/**',
  435. // Python
  436. '**/__pycache__/**',
  437. '**/.venv/**',
  438. '**/venv/**',
  439. '**/.pytest_cache/**',
  440. '**/.mypy_cache/**',
  441. '**/.ruff_cache/**',
  442. '**/.tox/**',
  443. '**/.nox/**',
  444. '**/*.egg-info/**',
  445. '**/.eggs/**',
  446. // Go
  447. '**/go/pkg/mod/**',
  448. // Rust
  449. '**/target/debug/**',
  450. '**/target/release/**',
  451. // Java/Kotlin/Gradle
  452. '**/.gradle/**',
  453. '**/.m2/**',
  454. '**/generated-sources/**',
  455. '**/.kotlin/**',
  456. // C#/.NET
  457. '**/.vs/**',
  458. '**/.nuget/**',
  459. '**/artifacts/**',
  460. '**/publish/**',
  461. // C/C++
  462. '**/cmake-build-*/**',
  463. '**/CMakeFiles/**',
  464. '**/bazel-*/**',
  465. '**/vcpkg_installed/**',
  466. '**/.conan/**',
  467. '**/Debug/**',
  468. '**/Release/**',
  469. '**/x64/**',
  470. // Swift/iOS/Xcode
  471. '**/DerivedData/**',
  472. '**/.build/**',
  473. '**/.swiftpm/**',
  474. '**/xcuserdata/**',
  475. '**/Carthage/Build/**',
  476. '**/SourcePackages/**',
  477. // PHP
  478. '**/.composer/**',
  479. '**/storage/framework/**',
  480. '**/bootstrap/cache/**',
  481. // Ruby
  482. '**/.bundle/**',
  483. '**/tmp/cache/**',
  484. '**/public/assets/**',
  485. '**/public/packs/**',
  486. '**/.yardoc/**',
  487. // Testing/Coverage
  488. '**/coverage/**',
  489. '**/htmlcov/**',
  490. '**/.nyc_output/**',
  491. '**/test-results/**',
  492. '**/.coverage/**',
  493. // IDE/Editor
  494. '**/.idea/**',
  495. // Logs and temp
  496. '**/logs/**',
  497. '**/tmp/**',
  498. '**/temp/**',
  499. // Documentation build output
  500. '**/_build/**',
  501. '**/docs/_build/**',
  502. '**/site/**',
  503. ],
  504. languages: [],
  505. frameworks: [],
  506. maxFileSize: 1024 * 1024, // 1MB
  507. extractDocstrings: true,
  508. trackCallSites: true,
  509. enableEmbeddings: false,
  510. };
  511. // =============================================================================
  512. // Database Types
  513. // =============================================================================
  514. /**
  515. * Database schema version info
  516. */
  517. export interface SchemaVersion {
  518. /** Current schema version */
  519. version: number;
  520. /** When schema was created/updated */
  521. appliedAt: number;
  522. /** Description of this version */
  523. description?: string;
  524. }
  525. /**
  526. * Statistics about the knowledge graph
  527. */
  528. export interface GraphStats {
  529. /** Total number of nodes */
  530. nodeCount: number;
  531. /** Total number of edges */
  532. edgeCount: number;
  533. /** Number of tracked files */
  534. fileCount: number;
  535. /** Node counts by kind */
  536. nodesByKind: Record<NodeKind, number>;
  537. /** Edge counts by kind */
  538. edgesByKind: Record<EdgeKind, number>;
  539. /** File counts by language */
  540. filesByLanguage: Record<Language, number>;
  541. /** Database size in bytes */
  542. dbSizeBytes: number;
  543. /** Last update timestamp */
  544. lastUpdated: number;
  545. }
  546. // =============================================================================
  547. // Task Context Types (for buildContext)
  548. // =============================================================================
  549. /**
  550. * Input for building task context
  551. */
  552. export type TaskInput = string | { title: string; description?: string };
  553. /**
  554. * Options for building task context
  555. */
  556. export interface BuildContextOptions {
  557. /** Maximum number of nodes to include (default: 50) */
  558. maxNodes?: number;
  559. /** Maximum number of code blocks to include (default: 10) */
  560. maxCodeBlocks?: number;
  561. /** Maximum characters per code block (default: 2000) */
  562. maxCodeBlockSize?: number;
  563. /** Whether to include code blocks (default: true) */
  564. includeCode?: boolean;
  565. /** Output format (default: 'markdown') */
  566. format?: 'markdown' | 'json';
  567. /** Number of semantic search results (default: 5) */
  568. searchLimit?: number;
  569. /** Graph traversal depth from entry points (default: 2) */
  570. traversalDepth?: number;
  571. /** Minimum semantic similarity score (default: 0.3) */
  572. minScore?: number;
  573. }
  574. /**
  575. * Full context for a task, ready for Claude
  576. */
  577. export interface TaskContext {
  578. /** The original query/task */
  579. query: string;
  580. /** Subgraph of relevant nodes and edges */
  581. subgraph: Subgraph;
  582. /** Entry point nodes (from semantic search) */
  583. entryPoints: Node[];
  584. /** Code blocks extracted from key nodes */
  585. codeBlocks: CodeBlock[];
  586. /** Files involved in this context */
  587. relatedFiles: string[];
  588. /** Brief summary of the context */
  589. summary: string;
  590. /** Statistics about the context */
  591. stats: {
  592. /** Number of nodes included */
  593. nodeCount: number;
  594. /** Number of edges included */
  595. edgeCount: number;
  596. /** Number of files touched */
  597. fileCount: number;
  598. /** Number of code blocks included */
  599. codeBlockCount: number;
  600. /** Total characters in code blocks */
  601. totalCodeSize: number;
  602. };
  603. }
  604. /**
  605. * Options for finding relevant context
  606. */
  607. export interface FindRelevantContextOptions {
  608. /** Number of semantic search results (default: 5) */
  609. searchLimit?: number;
  610. /** Graph traversal depth (default: 2) */
  611. traversalDepth?: number;
  612. /** Maximum nodes in result (default: 50) */
  613. maxNodes?: number;
  614. /** Minimum semantic similarity score (default: 0.3) */
  615. minScore?: number;
  616. /** Edge types to follow in traversal */
  617. edgeKinds?: EdgeKind[];
  618. /** Node types to include */
  619. nodeKinds?: NodeKind[];
  620. }