types.ts 18 KB

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