types.ts 17 KB

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