octocode 0.22.0

AI-powered code intelligence with semantic search, knowledge graphs, and built-in MCP server. Transform your codebase into a queryable knowledge graph for AI assistants.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// GraphRAG data structures and types

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

/// Direction for relationship queries
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RelationshipDirection {
	/// Relationships where the node is the source
	Outgoing,
	/// Relationships where the node is the target
	Incoming,
	/// Both outgoing and incoming relationships
	Both,
}

/// Type of relationship between code nodes
/// Ordered by architectural importance (high to low)
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RelationType {
	// High importance - Architectural relationships (weight: 1.0)
	/// Interface or trait implementation
	Implements,
	/// Class inheritance or module extension
	Extends,
	/// Dependency injection or configuration setup
	Configures,
	/// High-level architectural dependency
	ArchitecturalDependency,

	// Medium importance - Structural relationships (weight: 0.7)
	/// Module or package import
	Imports,
	/// Function or method call
	Calls,
	/// Utility or service usage
	Uses,
	/// Factory pattern instantiation
	FactoryCreates,
	/// Observer pattern (event listening, callbacks)
	ObserverPattern,
	/// Strategy pattern (algorithm selection)
	StrategyPattern,
	/// Adapter pattern (interface adaptation)
	AdapterPattern,
	/// Document cross-reference via markdown link
	References,

	// Low importance - Organizational relationships (weight: 0.3)
	/// Files in the same directory
	SiblingModule,
	/// Parent directory relationship
	ParentModule,
	/// Child directory relationship
	ChildModule,
	/// File contains a declared live AST symbol
	Contains,
}

impl RelationType {
	/// Get importance weight for ranking (0.0-1.0)
	/// Higher values indicate more architecturally significant relationships
	pub fn importance_weight(&self) -> f32 {
		match self {
			// High importance - architectural patterns
			Self::Implements | Self::Extends | Self::Configures => 1.0,
			Self::ArchitecturalDependency => 0.9,

			// Medium importance - structural dependencies
			Self::Imports | Self::Calls | Self::Uses => 0.7,
			Self::FactoryCreates
			| Self::ObserverPattern
			| Self::StrategyPattern
			| Self::AdapterPattern => 0.8,
			Self::References => 0.6,

			// Low importance - organizational structure
			Self::SiblingModule | Self::ParentModule | Self::ChildModule | Self::Contains => 0.3,
		}
	}

	/// Convert to string (for database storage and display)
	pub fn as_str(&self) -> &'static str {
		match self {
			Self::Implements => "implements",
			Self::Extends => "extends",
			Self::Configures => "configures",
			Self::ArchitecturalDependency => "architectural_dependency",
			Self::Imports => "imports",
			Self::Calls => "calls",
			Self::Uses => "uses",
			Self::FactoryCreates => "factory_creates",
			Self::ObserverPattern => "observer_pattern",
			Self::StrategyPattern => "strategy_pattern",
			Self::AdapterPattern => "adapter_pattern",
			Self::References => "references",
			Self::SiblingModule => "sibling_module",
			Self::ParentModule => "parent_module",
			Self::ChildModule => "child_module",
			Self::Contains => "contains",
		}
	}
}

impl FromStr for RelationType {
	type Err = ();

	/// Parse from string (for backward compatibility with old String-based storage)
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Ok(match s {
			"implements" => Self::Implements,
			"extends" => Self::Extends,
			"configures" => Self::Configures,
			"architectural_dependency" => Self::ArchitecturalDependency,
			"imports" => Self::Imports,
			"calls" => Self::Calls,
			"uses" => Self::Uses,
			"factory_creates" => Self::FactoryCreates,
			"observer_pattern" => Self::ObserverPattern,
			"strategy_pattern" => Self::StrategyPattern,
			"adapter_pattern" => Self::AdapterPattern,
			"references" => Self::References,
			"sibling_module" => Self::SiblingModule,
			"parent_module" => Self::ParentModule,
			"child_module" => Self::ChildModule,
			"contains" => Self::Contains,
			// Default fallback for unknown types
			_ => Self::Imports,
		})
	}
}

impl fmt::Display for RelationType {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.as_str())
	}
}

/// How a relationship was derived. `Extracted` = read directly from the AST
/// (import statements, declared inheritance, same-file calls, module layout);
/// `Inferred` = resolved by heuristics (cross-file name matching, unique-global
/// resolution, LLM suggestions); `Ambiguous` = the reference matches multiple
/// targets and no import disambiguated it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Provenance {
	#[default]
	Extracted,
	Inferred,
	Ambiguous,
}

impl Provenance {
	/// Parse from the database column value; unknown/absent values (older
	/// rows written before the column existed) default to `Extracted`.
	pub fn parse_or_default(s: &str) -> Self {
		match s {
			"inferred" => Self::Inferred,
			"ambiguous" => Self::Ambiguous,
			_ => Self::Extracted,
		}
	}

	pub fn as_str(&self) -> &'static str {
		match self {
			Self::Extracted => "extracted",
			Self::Inferred => "inferred",
			Self::Ambiguous => "ambiguous",
		}
	}
}

// A node in the code graph - represents a file/module with efficient storage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeNode {
	pub id: String,           // Relative path from project root (efficient storage)
	pub name: String,         // File name or module name
	pub kind: String,         // Type of the node (file, module, package, function)
	pub path: String,         // Relative file path from project root
	pub description: String,  // Description/summary of what the file/module does
	pub symbols: Vec<String>, // All symbols from this file (functions, classes, etc.)
	pub hash: String,         // Content hash to detect changes
	pub embedding: Vec<f32>,  // Vector embedding of the file content
	pub imports: Vec<String>, // List of imported modules (relative paths or external)
	pub exports: Vec<String>, // List of exported symbols
	pub functions: Vec<FunctionInfo>, // Function-level information for better granularity
	pub size_lines: u32,      // Number of lines in the file
	pub language: String,     // Programming language
}

impl CodeNode {
	/// Clone this node WITHOUT its embedding vector. Relationship discovery reads
	/// only the metadata fields, so copying the (KB-sized) embedding for every
	/// node on every incremental run is pure waste.
	pub fn without_embedding(&self) -> CodeNode {
		CodeNode {
			id: self.id.clone(),
			name: self.name.clone(),
			kind: self.kind.clone(),
			path: self.path.clone(),
			description: self.description.clone(),
			symbols: self.symbols.clone(),
			hash: self.hash.clone(),
			embedding: Vec::new(),
			imports: self.imports.clone(),
			exports: self.exports.clone(),
			functions: self.functions.clone(),
			size_lines: self.size_lines,
			language: self.language.clone(),
		}
	}

	/// True for live AST symbol nodes (`{file_path}::{symbol_name}` or
	/// `{file_path}::{owner}::{method}`).
	/// File node ids are relative paths and never contain `::` in practice.
	pub fn is_symbol_node(&self) -> bool {
		self.id.contains("::")
	}
}

// Function-level information for better granularity. Also doubles as the
// container for file-scope relationship data (a single synthetic entry per
// file holds aggregate calls / extends / implements when per-function
// granularity is unavailable). The new vectors below default to empty so
// older serialized rows deserialize cleanly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionInfo {
	pub name: String,                // Function name
	pub signature: String,           // Function signature
	pub start_line: u32,             // Starting line number
	pub end_line: u32,               // Ending line number
	pub calls: Vec<String>,          // Functions this function calls
	pub called_by: Vec<String>,      // Functions that call this function
	pub parameters: Vec<String>,     // Function parameters
	pub return_type: Option<String>, // Return type if available
	#[serde(default)]
	pub extends: Vec<String>, // Types/traits this entity extends (inheritance)
	#[serde(default)]
	pub implements: Vec<String>, // Interfaces/traits this entity implements
}

// A relationship between code nodes - simplified and more efficient
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeRelationship {
	pub source: String,              // Source node ID (relative path)
	pub target: String,              // Target node ID (relative path)
	pub relation_type: RelationType, // Type: imports, calls, extends, implements, etc.
	pub description: String,         // Brief description
	pub confidence: f32,             // Confidence score (0.0-1.0)
	pub weight: f32,                 // Relationship strength/frequency
	#[serde(default)]
	pub provenance: Provenance, // How the relationship was derived
}

impl CodeRelationship {
	/// Create a new relationship with default values
	pub fn new(
		source: String,
		target: String,
		relation_type: RelationType,
		description: String,
	) -> Self {
		Self {
			source,
			target,
			relation_type,
			description,
			confidence: 0.9, // Default high confidence for AST-based relationships
			weight: 1.0,     // Default weight, will be calculated later
			provenance: Provenance::default(),
		}
	}

	/// Create from legacy string-based relation_type (for backward compatibility)
	pub fn from_legacy(
		source: String,
		target: String,
		relation_type_str: &str,
		description: String,
		confidence: f32,
		weight: f32,
	) -> Self {
		Self {
			source,
			target,
			relation_type: relation_type_str.parse().unwrap_or(RelationType::Imports),
			description,
			confidence,
			weight,
			provenance: Provenance::default(),
		}
	}
}

// The full code graph
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CodeGraph {
	pub nodes: HashMap<String, CodeNode>,
	pub relationships: Vec<CodeRelationship>,
}

// Helper struct for batch relationship analysis request
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct BatchRelationshipResult {
	pub source_id: String,
	pub target_id: String,
	pub relation_type: String,
	pub description: String,
	pub confidence: f32,
	pub exists: bool,
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_relationship_type_importance_weights() {
		// High importance relationships
		assert_eq!(RelationType::Implements.importance_weight(), 1.0);
		assert_eq!(RelationType::Extends.importance_weight(), 1.0);
		assert_eq!(RelationType::Configures.importance_weight(), 1.0);
		assert_eq!(
			RelationType::ArchitecturalDependency.importance_weight(),
			0.9
		);

		// Medium importance relationships
		assert_eq!(RelationType::Imports.importance_weight(), 0.7);
		assert_eq!(RelationType::Calls.importance_weight(), 0.7);
		assert_eq!(RelationType::Uses.importance_weight(), 0.7);
		assert_eq!(RelationType::FactoryCreates.importance_weight(), 0.8);

		// Document references (between structural and organizational)
		assert_eq!(RelationType::References.importance_weight(), 0.6);

		// Low importance relationships
		assert_eq!(RelationType::SiblingModule.importance_weight(), 0.3);
		assert_eq!(RelationType::ParentModule.importance_weight(), 0.3);
		assert_eq!(RelationType::ChildModule.importance_weight(), 0.3);
	}

	#[test]
	fn test_relationship_type_ordering() {
		// Verify architectural relationships have higher weight than structural
		assert!(
			RelationType::Implements.importance_weight()
				> RelationType::Imports.importance_weight()
		);
		assert!(
			RelationType::Extends.importance_weight() > RelationType::Calls.importance_weight()
		);

		// Verify structural relationships have higher weight than organizational
		assert!(
			RelationType::Imports.importance_weight()
				> RelationType::SiblingModule.importance_weight()
		);
		assert!(
			RelationType::Calls.importance_weight()
				> RelationType::ParentModule.importance_weight()
		);

		// Verify references sit between structural imports and organizational
		assert!(
			RelationType::Imports.importance_weight()
				> RelationType::References.importance_weight()
		);
		assert!(
			RelationType::References.importance_weight()
				> RelationType::SiblingModule.importance_weight()
		);
	}

	#[test]
	fn test_relationship_type_from_str() {
		// Test all enum variants
		assert_eq!(
			"implements".parse::<RelationType>().unwrap(),
			RelationType::Implements
		);
		assert_eq!(
			"extends".parse::<RelationType>().unwrap(),
			RelationType::Extends
		);
		assert_eq!(
			"imports".parse::<RelationType>().unwrap(),
			RelationType::Imports
		);
		assert_eq!(
			"calls".parse::<RelationType>().unwrap(),
			RelationType::Calls
		);
		assert_eq!(
			"sibling_module".parse::<RelationType>().unwrap(),
			RelationType::SiblingModule
		);
		assert_eq!(
			"references".parse::<RelationType>().unwrap(),
			RelationType::References
		);

		// Test unknown type defaults to Imports
		assert_eq!(
			"unknown_type".parse::<RelationType>().unwrap(),
			RelationType::Imports
		);
		assert_eq!("".parse::<RelationType>().unwrap(), RelationType::Imports);
	}

	#[test]
	fn test_relationship_type_as_str() {
		// Test string conversion
		assert_eq!(RelationType::Implements.as_str(), "implements");
		assert_eq!(RelationType::Extends.as_str(), "extends");
		assert_eq!(RelationType::Imports.as_str(), "imports");
		assert_eq!(RelationType::Calls.as_str(), "calls");
		assert_eq!(RelationType::SiblingModule.as_str(), "sibling_module");
	}

	#[test]
	fn test_relationship_type_roundtrip() {
		// Test that from_str and as_str are inverses
		let types = vec![
			RelationType::Implements,
			RelationType::Extends,
			RelationType::Imports,
			RelationType::Calls,
			RelationType::Uses,
			RelationType::References,
			RelationType::SiblingModule,
		];

		for rel_type in types {
			let as_string = rel_type.as_str();
			let parsed = as_string.parse::<RelationType>().unwrap();
			assert_eq!(parsed, rel_type, "Roundtrip failed for {:?}", rel_type);
		}
	}

	#[test]
	fn test_relationship_type_display() {
		// Test Display trait
		assert_eq!(format!("{}", RelationType::Implements), "implements");
		assert_eq!(format!("{}", RelationType::Extends), "extends");
		assert_eq!(format!("{}", RelationType::Imports), "imports");
	}

	#[test]
	fn test_relationship_type_serialization() {
		// Test serde serialization
		let rel_type = RelationType::Implements;
		let serialized = serde_json::to_string(&rel_type).unwrap();
		assert_eq!(serialized, "\"implements\"");

		let deserialized: RelationType = serde_json::from_str(&serialized).unwrap();
		assert_eq!(deserialized, RelationType::Implements);
	}

	#[test]
	fn test_code_relationship_new() {
		let rel = CodeRelationship::new(
			"src/main.rs".to_string(),
			"src/lib.rs".to_string(),
			RelationType::Imports,
			"Imports lib module".to_string(),
		);

		assert_eq!(rel.source, "src/main.rs");
		assert_eq!(rel.target, "src/lib.rs");
		assert_eq!(rel.relation_type, RelationType::Imports);
		assert_eq!(rel.description, "Imports lib module");
		assert_eq!(rel.confidence, 0.9); // Default
		assert_eq!(rel.weight, 1.0); // Default
	}

	#[test]
	fn test_code_relationship_from_legacy() {
		// Test backward compatibility with string-based types
		let rel = CodeRelationship::from_legacy(
			"src/main.rs".to_string(),
			"src/lib.rs".to_string(),
			"implements",
			"Implements trait".to_string(),
			0.95,
			2.5,
		);

		assert_eq!(rel.source, "src/main.rs");
		assert_eq!(rel.target, "src/lib.rs");
		assert_eq!(rel.relation_type, RelationType::Implements);
		assert_eq!(rel.description, "Implements trait");
		assert_eq!(rel.confidence, 0.95);
		assert_eq!(rel.weight, 2.5);
	}

	#[test]
	fn test_code_relationship_legacy_unknown_type() {
		// Test that unknown legacy types default to Imports
		let rel = CodeRelationship::from_legacy(
			"src/a.rs".to_string(),
			"src/b.rs".to_string(),
			"some_old_type",
			"Description".to_string(),
			0.8,
			1.0,
		);

		assert_eq!(rel.relation_type, RelationType::Imports);
	}

	#[test]
	fn test_relationship_direction_enum() {
		// Test that enum variants exist and are distinct
		let outgoing = RelationshipDirection::Outgoing;
		let incoming = RelationshipDirection::Incoming;
		let both = RelationshipDirection::Both;

		assert_ne!(outgoing, incoming);
		assert_ne!(outgoing, both);
		assert_ne!(incoming, both);
	}

	#[test]
	fn test_code_relationship_serialization() {
		let rel = CodeRelationship::new(
			"src/main.rs".to_string(),
			"src/lib.rs".to_string(),
			RelationType::Imports,
			"Test relationship".to_string(),
		);

		// Test JSON serialization
		let json = serde_json::to_string(&rel).unwrap();
		let deserialized: CodeRelationship = serde_json::from_str(&json).unwrap();

		assert_eq!(deserialized.source, rel.source);
		assert_eq!(deserialized.target, rel.target);
		assert_eq!(deserialized.relation_type, rel.relation_type);
		assert_eq!(deserialized.description, rel.description);
	}

	#[test]
	fn test_relation_type_contains_roundtrip() {
		assert_eq!(RelationType::Contains.as_str(), "contains");
		assert_eq!(
			"contains".parse::<RelationType>().unwrap(),
			RelationType::Contains
		);
		assert_eq!(RelationType::Contains.importance_weight(), 0.3);
	}

	#[test]
	fn test_provenance_serde_roundtrip() {
		let mut rel = CodeRelationship::new(
			"src/a.rs".to_string(),
			"src/a.rs::foo".to_string(),
			RelationType::Contains,
			"File contains function foo".to_string(),
		);
		assert_eq!(rel.provenance, Provenance::default());

		rel.provenance = Provenance::Inferred;
		let json = serde_json::to_string(&rel).unwrap();
		assert!(json.contains("\"inferred\""));
		let deserialized: CodeRelationship = serde_json::from_str(&json).unwrap();
		assert_eq!(deserialized.provenance, Provenance::Inferred);
	}

	#[test]
	fn test_provenance_parse_or_default() {
		assert_eq!(
			Provenance::parse_or_default("extracted"),
			Provenance::Extracted
		);
		assert_eq!(
			Provenance::parse_or_default("inferred"),
			Provenance::Inferred
		);
		assert_eq!(
			Provenance::parse_or_default("ambiguous"),
			Provenance::Ambiguous
		);
		// Unknown values (rows written before the column existed) default to Extracted
		assert_eq!(Provenance::parse_or_default(""), Provenance::Extracted);
		assert_eq!(
			Provenance::parse_or_default("legacy"),
			Provenance::Extracted
		);
	}

	#[test]
	fn test_code_node_is_symbol_node() {
		let mut node = CodeNode {
			id: "src/lib.rs".to_string(),
			name: "lib".to_string(),
			kind: "source_file".to_string(),
			path: "src/lib.rs".to_string(),
			description: String::new(),
			symbols: Vec::new(),
			hash: String::new(),
			embedding: Vec::new(),
			imports: Vec::new(),
			exports: Vec::new(),
			functions: Vec::new(),
			size_lines: 0,
			language: "rust".to_string(),
		};
		assert!(!node.is_symbol_node());
		node.id = "src/lib.rs::my_func".to_string();
		assert!(node.is_symbol_node());
	}
}