types.ts 17 KB

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