types.ts 17 KB

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