octocode 0.14.1

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
// 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.

use anyhow::Result;
use std::sync::Arc;

// Arrow imports
use arrow_array::{Array, Int64Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};

// LanceDB imports
use futures::TryStreamExt;
use lancedb::{
	query::{ExecutableQuery, QueryBase, Select},
	Connection,
};

use crate::store::table_ops::TableOperations;

/// Handles git and file metadata operations
pub struct MetadataOperations<'a> {
	pub db: &'a Connection,
	pub table_ops: TableOperations<'a>,
}

impl<'a> MetadataOperations<'a> {
	pub fn new(db: &'a Connection) -> Self {
		Self {
			db,
			table_ops: TableOperations::new(db),
		}
	}

	/// Store git metadata (commit hash, etc.)
	pub async fn store_git_metadata(&self, commit_hash: &str) -> Result<()> {
		// Check if table exists, create if not
		if !self.table_ops.table_exists("git_metadata").await? {
			self.create_git_metadata_table().await?;
		}

		// Check if the commit hash is already stored
		if let Ok(Some(existing_hash)) = self.get_last_commit_hash().await {
			if existing_hash == commit_hash {
				// Same commit hash, no need to update
				return Ok(());
			}
		}

		// Create a record with the current timestamp
		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		let commit_hashes = vec![commit_hash];
		let timestamps = vec![chrono::Utc::now().timestamp()];

		let batch = RecordBatch::try_new(
			schema,
			vec![
				Arc::new(StringArray::from(commit_hashes)),
				Arc::new(Int64Array::from(timestamps)),
			],
		)?;

		// Only clear and store if we have a different commit hash
		self.table_ops.clear_table("git_metadata").await?;
		self.table_ops.store_batch("git_metadata", batch).await?;

		Ok(())
	}

	/// Get last indexed git commit hash
	pub async fn get_last_commit_hash(&self) -> Result<Option<String>> {
		if !self.table_ops.table_exists("git_metadata").await? {
			return Ok(None);
		}

		let table = self.db.open_table("git_metadata").execute().await?;

		// Get the most recent commit hash
		let mut results = table
			.query()
			.select(Select::Columns(vec!["commit_hash".to_string()]))
			.limit(1)
			.execute()
			.await?;

		// Process results
		while let Some(batch) = results.try_next().await? {
			if batch.num_rows() > 0 {
				if let Some(column) = batch.column_by_name("commit_hash") {
					if let Some(hash_array) = column.as_any().downcast_ref::<StringArray>() {
						if let Some(hash) = hash_array.iter().next() {
							return Ok(hash.map(|s| s.to_string()));
						}
					}
				}
			}
		}

		Ok(None)
	}

	/// Store file metadata (modification time, etc.)
	pub async fn store_file_metadata(&self, file_path: &str, mtime: u64) -> Result<()> {
		// Check if table exists, create if not
		if !self.table_ops.table_exists("file_metadata").await? {
			self.create_file_metadata_table().await?;
		}

		let table = self.db.open_table("file_metadata").execute().await?;

		// Check if file already exists in metadata
		let mut existing_results = table
			.query()
			.only_if(format!("path = '{}'", file_path))
			.limit(1)
			.execute()
			.await?;

		let mut file_exists = false;
		while let Some(batch) = existing_results.try_next().await? {
			if batch.num_rows() > 0 {
				file_exists = true;
				break;
			}
		}

		if file_exists {
			// Update existing record using correct LanceDB UpdateBuilder API
			table
				.update()
				.only_if(format!("path = '{}'", file_path))
				.column("mtime", (mtime as i64).to_string())
				.column("indexed_at", chrono::Utc::now().timestamp().to_string())
				.execute()
				.await?;
		} else {
			// Insert new record
			let schema = Arc::new(Schema::new(vec![
				Field::new("path", DataType::Utf8, false),
				Field::new("mtime", DataType::Int64, false),
				Field::new("indexed_at", DataType::Int64, false),
			]));

			let paths = vec![file_path];
			let mtimes = vec![mtime as i64];
			let timestamps = vec![chrono::Utc::now().timestamp()];

			let batch = RecordBatch::try_new(
				schema,
				vec![
					Arc::new(StringArray::from(paths)),
					Arc::new(Int64Array::from(mtimes)),
					Arc::new(Int64Array::from(timestamps)),
				],
			)?;

			// Use RecordBatchIterator instead of Vec<RecordBatch>
			use std::iter::once;
			let batches = once(Ok(batch.clone()));
			let batch_reader =
				arrow::record_batch::RecordBatchIterator::new(batches, batch.schema());
			table.add(batch_reader).execute().await?;
		}

		Ok(())
	}

	/// Get file modification time from metadata
	pub async fn get_file_mtime(&self, file_path: &str) -> Result<Option<u64>> {
		if !self.table_ops.table_exists("file_metadata").await? {
			return Ok(None);
		}

		let table = self.db.open_table("file_metadata").execute().await?;

		// Query for the specific file
		let mut results = table
			.query()
			.only_if(format!("path = '{}'", file_path))
			.select(Select::Columns(vec!["mtime".to_string()]))
			.limit(1)
			.execute()
			.await?;

		// Process results
		while let Some(batch) = results.try_next().await? {
			if batch.num_rows() > 0 {
				if let Some(column) = batch.column_by_name("mtime") {
					if let Some(mtime_array) = column.as_any().downcast_ref::<Int64Array>() {
						if let Some(mtime) = mtime_array.iter().next() {
							return Ok(mtime.map(|t| t as u64));
						}
					}
				}
			}
		}

		Ok(None)
	}

	/// Get all file metadata for efficient batch processing
	/// This eliminates the need for individual database queries per file
	pub async fn get_all_file_metadata(&self) -> Result<std::collections::HashMap<String, u64>> {
		let mut metadata_map = std::collections::HashMap::new();

		if !self.table_ops.table_exists("file_metadata").await? {
			return Ok(metadata_map);
		}

		let table = self.db.open_table("file_metadata").execute().await?;

		// Query for all file metadata
		let mut results = table
			.query()
			.select(Select::Columns(vec![
				"path".to_string(),
				"mtime".to_string(),
			]))
			.execute()
			.await?;

		// Process all result batches
		while let Some(batch) = results.try_next().await? {
			if batch.num_rows() > 0 {
				if let (Some(path_column), Some(mtime_column)) =
					(batch.column_by_name("path"), batch.column_by_name("mtime"))
				{
					if let (Some(path_array), Some(mtime_array)) = (
						path_column.as_any().downcast_ref::<StringArray>(),
						mtime_column.as_any().downcast_ref::<Int64Array>(),
					) {
						for i in 0..path_array.len() {
							if let (Some(path), Some(mtime)) = (
								path_array.iter().nth(i).flatten(),
								mtime_array.iter().nth(i).flatten(),
							) {
								metadata_map.insert(path.to_string(), mtime as u64);
							}
						}
					}
				}
			}
		}

		Ok(metadata_map)
	}

	/// Clear git metadata table to force full re-scan
	pub async fn clear_git_metadata(&self) -> Result<()> {
		self.table_ops.clear_table("git_metadata").await
	}

	/// Create git metadata table
	async fn create_git_metadata_table(&self) -> Result<()> {
		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		self.table_ops
			.create_table_with_schema("git_metadata", schema)
			.await
	}

	/// Create file metadata table
	async fn create_file_metadata_table(&self) -> Result<()> {
		let schema = Arc::new(Schema::new(vec![
			Field::new("path", DataType::Utf8, false),
			Field::new("mtime", DataType::Int64, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		self.table_ops
			.create_table_with_schema("file_metadata", schema)
			.await
	}

	/// Get the last GraphRAG commit hash
	pub async fn get_graphrag_last_commit_hash(&self) -> Result<Option<String>> {
		// Check if table exists
		if !self.table_ops.table_exists("graphrag_git_metadata").await? {
			return Ok(None);
		}

		let table = self
			.db
			.open_table("graphrag_git_metadata")
			.execute()
			.await?;

		// Get the most recent commit hash
		let mut results = table
			.query()
			.select(Select::Columns(vec!["commit_hash".to_string()]))
			.limit(1)
			.execute()
			.await?;

		// Process results
		while let Some(batch) = results.try_next().await? {
			if batch.num_rows() > 0 {
				if let Some(column) = batch.column_by_name("commit_hash") {
					if let Some(hash_array) = column.as_any().downcast_ref::<StringArray>() {
						if let Some(hash) = hash_array.iter().next() {
							return Ok(hash.map(|s| s.to_string()));
						}
					}
				}
			}
		}

		Ok(None)
	}

	/// Store GraphRAG git metadata (commit hash and timestamp)
	pub async fn store_graphrag_commit_hash(&self, commit_hash: &str) -> Result<()> {
		// Check if table exists, create if not
		if !self.table_ops.table_exists("graphrag_git_metadata").await? {
			self.create_graphrag_git_metadata_table().await?;
		}

		// Check if the commit hash is already stored
		if let Ok(Some(existing_hash)) = self.get_graphrag_last_commit_hash().await {
			if existing_hash == commit_hash {
				// Same commit hash, no need to update
				return Ok(());
			}
		}

		// Create a record with the current timestamp
		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		let commit_hashes = vec![commit_hash];
		let timestamps = vec![chrono::Utc::now().timestamp()];

		let batch = RecordBatch::try_new(
			schema,
			vec![
				Arc::new(StringArray::from(commit_hashes)),
				Arc::new(Int64Array::from(timestamps)),
			],
		)?;

		// Only clear and store if we have a different commit hash
		self.table_ops.clear_table("graphrag_git_metadata").await?;
		self.table_ops
			.store_batch("graphrag_git_metadata", batch)
			.await?;

		Ok(())
	}

	/// Create GraphRAG git metadata table
	async fn create_graphrag_git_metadata_table(&self) -> Result<()> {
		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		self.table_ops
			.create_table_with_schema("graphrag_git_metadata", schema)
			.await
	}

	/// Get the last commits commit hash
	pub async fn get_commits_last_commit_hash(&self) -> Result<Option<String>> {
		if !self.table_ops.table_exists("commits_git_metadata").await? {
			return Ok(None);
		}

		let table = self.db.open_table("commits_git_metadata").execute().await?;

		let mut results = table
			.query()
			.select(Select::Columns(vec!["commit_hash".to_string()]))
			.limit(1)
			.execute()
			.await?;

		while let Some(batch) = results.try_next().await? {
			if batch.num_rows() > 0 {
				if let Some(column) = batch.column_by_name("commit_hash") {
					if let Some(hash_array) = column.as_any().downcast_ref::<StringArray>() {
						if let Some(hash) = hash_array.iter().next() {
							return Ok(hash.map(|s| s.to_string()));
						}
					}
				}
			}
		}

		Ok(None)
	}

	/// Store commits git metadata (commit hash and timestamp)
	pub async fn store_commits_last_commit_hash(&self, commit_hash: &str) -> Result<()> {
		if !self.table_ops.table_exists("commits_git_metadata").await? {
			self.create_commits_git_metadata_table().await?;
		}

		if let Ok(Some(existing_hash)) = self.get_commits_last_commit_hash().await {
			if existing_hash == commit_hash {
				return Ok(());
			}
		}

		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		let commit_hashes = vec![commit_hash];
		let timestamps = vec![chrono::Utc::now().timestamp()];

		let batch = RecordBatch::try_new(
			schema,
			vec![
				Arc::new(StringArray::from(commit_hashes)),
				Arc::new(Int64Array::from(timestamps)),
			],
		)?;

		self.table_ops.clear_table("commits_git_metadata").await?;
		self.table_ops
			.store_batch("commits_git_metadata", batch)
			.await?;

		Ok(())
	}

	async fn create_commits_git_metadata_table(&self) -> Result<()> {
		let schema = Arc::new(Schema::new(vec![
			Field::new("commit_hash", DataType::Utf8, false),
			Field::new("indexed_at", DataType::Int64, false),
		]));

		self.table_ops
			.create_table_with_schema("commits_git_metadata", schema)
			.await
	}
}