1use crate::config::Context;
2use crate::db;
3use crate::graph::code_graph::{
4 self, GraphBlastRadiusTarget, GraphLifecycleAction, GraphLifecycleOutput, GraphPayload,
5};
6use crate::graph::report::{ProjectGraphReport, ProjectGraphReportOptions};
7use crate::models::PagedResponse;
8use crate::output::{self, Format};
9use crate::projection::sync::ProjectionSyncReport;
10use crate::search::fts::{self, ResolvedGraphSymbol};
11use serde::Serialize;
12use serde_json::{Value, json};
13
14const GOBBY_HINT: &str =
15 "Graph commands require FalkorDB, available with Gobby. See: https://github.com/GobbyAI/gobby";
16fn format_success_text(output: &GraphLifecycleOutput) -> String {
17 format!(
18 "{} for project {}: {}",
19 output.action.success_prefix(),
20 output.project_id,
21 output.summary
22 )
23}
24
25fn run_lifecycle_action(
26 ctx: &Context,
27 action: GraphLifecycleAction,
28 format: Format,
29) -> anyhow::Result<()> {
30 let output = match action {
31 GraphLifecycleAction::Clear => clear_project_graph(ctx)?,
32 GraphLifecycleAction::Rebuild => rebuild_project_graph(ctx)?,
33 };
34 match format {
35 Format::Json => output::print_json(&output.payload),
36 Format::Text => {
37 output::print_text(&format_success_text(&output))?;
38 output::print_json_compact(&output.payload)
39 }
40 }
41}
42
43fn lifecycle_output(
44 action: GraphLifecycleAction,
45 ctx: &Context,
46 payload: Value,
47) -> GraphLifecycleOutput {
48 let summary = code_graph::extract_summary_text(&payload).unwrap_or_else(|| payload.to_string());
49 GraphLifecycleOutput {
50 project_id: ctx.project_id.clone(),
51 action,
52 summary,
53 payload,
54 }
55}
56
57struct GraphFileSyncOutcome {
58 relationships_written: usize,
59 symbols_synced: usize,
60}
61
62fn sync_file_graph(ctx: &Context, file_path: &str) -> anyhow::Result<GraphFileSyncOutcome> {
63 code_graph::require_graph_reads(ctx)?;
64 let mut conn = db::connect_readwrite(&ctx.database_url)?;
65 let facts = db::read_graph_file_facts(&mut conn, &ctx.project_id, file_path)?;
66 if !db::mark_graph_sync_attempted(&mut conn, &ctx.project_id, file_path)? {
67 anyhow::bail!(
68 "indexed file `{file_path}` was not found for project {}",
69 ctx.project_id
70 );
71 }
72 let relationships_written = code_graph::sync_file_graph(
73 ctx,
74 &facts.file_path,
75 &facts.imports,
76 &facts.definitions,
77 &facts.calls,
78 )?;
79 db::mark_graph_synced(&mut conn, &ctx.project_id, file_path)?;
80 Ok(GraphFileSyncOutcome {
81 relationships_written,
82 symbols_synced: facts.definitions.len(),
83 })
84}
85
86fn clear_project_graph(ctx: &Context) -> anyhow::Result<GraphLifecycleOutput> {
87 code_graph::require_graph_reads(ctx)?;
88 let mut conn = db::connect_readwrite(&ctx.database_url)?;
89 let files_marked_pending = db::reset_graph_sync_for_project(&mut conn, &ctx.project_id)?;
90 code_graph::clear_project(ctx)?;
91 let report = ProjectionSyncReport::ok(0, 0);
92 Ok(lifecycle_output(
93 GraphLifecycleAction::Clear,
94 ctx,
95 json!({
96 "success": true,
97 "project_id": ctx.project_id,
98 "status": report.status,
99 "synced_files": report.synced_files,
100 "synced_symbols": report.synced_symbols,
101 "degraded": report.degraded,
102 "error": report.error,
103 "files_marked_pending": files_marked_pending,
104 "summary": format!("marked {files_marked_pending} files pending and cleared graph projection"),
105 }),
106 ))
107}
108
109fn rebuild_project_graph(ctx: &Context) -> anyhow::Result<GraphLifecycleOutput> {
110 code_graph::require_graph_reads(ctx)?;
111 let mut conn = db::connect_readwrite(&ctx.database_url)?;
112 let file_paths = db::list_indexed_file_paths(&mut conn, &ctx.project_id)?;
113 code_graph::clear_project(ctx)?;
114 db::reset_graph_sync_for_project(&mut conn, &ctx.project_id)?;
115
116 let mut files_synced = 0usize;
117 let mut symbols_synced = 0usize;
118 let mut errors = Vec::new();
119 for file_path in &file_paths {
120 let synced_symbols =
121 match db::mark_graph_sync_attempted(&mut conn, &ctx.project_id, file_path)
122 .and_then(|updated| {
123 if updated {
124 Ok(())
125 } else {
126 anyhow::bail!("indexed file no longer exists")
127 }
128 })
129 .and_then(|_| {
130 let facts = db::read_graph_file_facts(&mut conn, &ctx.project_id, file_path)?;
131 code_graph::sync_file_graph(
132 ctx,
133 &facts.file_path,
134 &facts.imports,
135 &facts.definitions,
136 &facts.calls,
137 )?;
138 db::mark_graph_synced(&mut conn, &ctx.project_id, file_path)?;
139 Ok(facts.definitions.len())
140 }) {
141 Ok(symbols) => symbols,
142 Err(err) => {
143 errors.push(format!("{file_path}: {err}"));
144 continue;
145 }
146 };
147 files_synced += 1;
148 symbols_synced += synced_symbols;
149 }
150
151 let report = if errors.is_empty() {
152 ProjectionSyncReport::ok(files_synced, symbols_synced)
153 } else {
154 ProjectionSyncReport::degraded(
155 "sync_failed",
156 errors.join("; "),
157 files_synced,
158 symbols_synced,
159 )
160 };
161 Ok(lifecycle_output(
162 GraphLifecycleAction::Rebuild,
163 ctx,
164 json!({
165 "success": true,
166 "project_id": ctx.project_id,
167 "status": report.status,
168 "synced_files": report.synced_files,
169 "synced_symbols": report.synced_symbols,
170 "degraded": report.degraded,
171 "error": report.error,
172 "files_processed": file_paths.len(),
173 "files_synced": files_synced,
174 "files_failed": errors.len(),
175 "errors": errors,
176 "summary": format!("synced {files_synced}/{} files", file_paths.len()),
177 }),
178 ))
179}
180
181pub fn clear(ctx: &Context, format: Format) -> anyhow::Result<()> {
182 run_lifecycle_action(ctx, GraphLifecycleAction::Clear, format)
183}
184
185pub fn rebuild(ctx: &Context, format: Format) -> anyhow::Result<()> {
186 run_lifecycle_action(ctx, GraphLifecycleAction::Rebuild, format)
187}
188
189pub fn sync_file(ctx: &Context, file_path: &str, format: Format) -> anyhow::Result<()> {
190 let sync = sync_file_graph(ctx, file_path)?;
191 let relationships_written = sync.relationships_written;
192 let report = ProjectionSyncReport::ok(1, sync.symbols_synced);
193 let summary = format!("synced {relationships_written} graph relationships for {file_path}");
194 let payload = json!({
195 "success": true,
196 "project_id": ctx.project_id,
197 "file_path": file_path,
198 "status": report.status,
199 "synced_files": report.synced_files,
200 "synced_symbols": report.synced_symbols,
201 "degraded": report.degraded,
202 "error": report.error,
203 "relationships_written": relationships_written,
204 "summary": summary,
205 });
206 match format {
207 Format::Json => output::print_json(&payload),
208 Format::Text => {
209 output::print_text(&format!(
210 "Synced code-index graph for project {}: {summary}",
211 ctx.project_id
212 ))?;
213 output::print_json_compact(&payload)
214 }
215 }
216}
217
218fn format_graph_payload_text(payload: &GraphPayload) -> String {
219 let mut lines = Vec::new();
220 lines.push(format!(
221 "nodes: {}, links: {}",
222 payload.nodes.len(),
223 payload.links.len()
224 ));
225 if let Some(center) = &payload.center {
226 lines.push(format!("center: {center}"));
227 }
228 for node in &payload.nodes {
229 let file = node.file_path.as_deref().unwrap_or("");
230 if file.is_empty() {
231 lines.push(format!(
232 "node {} [{}] {}",
233 node.id, node.node_type, node.name
234 ));
235 } else {
236 lines.push(format!(
237 "node {} [{}] {} {}",
238 node.id, node.node_type, node.name, file
239 ));
240 }
241 }
242 for link in &payload.links {
243 lines.push(format!(
244 "link {} -[{}]-> {}",
245 link.source, link.link_type, link.target
246 ));
247 }
248 lines.join("\n")
249}
250
251fn print_graph_payload(payload: &GraphPayload, format: Format) -> anyhow::Result<()> {
252 match format {
253 Format::Json => output::print_json(payload),
254 Format::Text => output::print_text(&format_graph_payload_text(payload)),
255 }
256}
257
258fn format_report_text(report: &ProjectGraphReport) -> anyhow::Result<String> {
259 Ok(serde_json::to_string_pretty(report)?)
260}
261
262pub fn report(ctx: &Context, top_n: usize, format: Format) -> anyhow::Result<()> {
263 let report = crate::graph::report::generate_report_with_options(
264 ctx,
265 ProjectGraphReportOptions { top_n },
266 )?;
267 match format {
268 Format::Json => output::print_json(&report),
269 Format::Text => output::print_text(&format_report_text(&report)?),
270 }
271}
272
273pub fn overview(ctx: &Context, limit: usize, format: Format) -> anyhow::Result<()> {
274 let payload = code_graph::project_overview_graph(ctx, limit)?;
275 print_graph_payload(&payload, format)
276}
277
278pub fn file(ctx: &Context, file_path: &str, format: Format) -> anyhow::Result<()> {
279 let payload = code_graph::file_graph(ctx, file_path)?;
280 print_graph_payload(&payload, format)
281}
282
283pub fn neighbors(
284 ctx: &Context,
285 symbol_id: &str,
286 limit: usize,
287 format: Format,
288) -> anyhow::Result<()> {
289 let payload = code_graph::symbol_neighbors(ctx, symbol_id, limit)?;
290 print_graph_payload(&payload, format)
291}
292
293pub fn graph_blast_radius(
294 ctx: &Context,
295 symbol_id: Option<&str>,
296 file_path: Option<&str>,
297 depth: usize,
298 limit: usize,
299 format: Format,
300) -> anyhow::Result<()> {
301 let target = match (symbol_id, file_path) {
302 (Some(symbol_id), None) => GraphBlastRadiusTarget::SymbolId(symbol_id.to_string()),
303 (None, Some(file_path)) => GraphBlastRadiusTarget::FilePath(file_path.to_string()),
304 _ => anyhow::bail!("provide exactly one of --symbol-id or --file"),
305 };
306 let payload = code_graph::blast_radius_graph(ctx, target, depth, limit)?;
307 print_graph_payload(&payload, format)
308}
309
310fn hint_for(ctx: &Context) -> Option<String> {
311 if ctx.falkordb.is_none() {
312 Some(GOBBY_HINT.to_string())
313 } else {
314 None
315 }
316}
317
318fn print_graph_hint_text(ctx: &Context) {
319 if ctx.falkordb.is_none() {
320 eprintln!("Hint: {GOBBY_HINT}");
321 }
322}
323
324fn graph_read_unavailable(error: &anyhow::Error) -> bool {
325 matches!(
326 error.downcast_ref::<code_graph::GraphReadError>(),
327 Some(
328 code_graph::GraphReadError::NotConfigured
329 | code_graph::GraphReadError::Unreachable { .. }
330 )
331 )
332}
333
334fn empty_paged_response<T: Serialize>(
335 ctx: &Context,
336 offset: usize,
337 limit: usize,
338 format: Format,
339) -> anyhow::Result<()> {
340 match format {
341 Format::Json => output::print_json(&PagedResponse::<T> {
342 project_id: ctx.project_id.clone(),
343 total: 0,
344 offset,
345 limit,
346 results: vec![],
347 hint: hint_for(ctx),
348 }),
349 Format::Text => Ok(()),
350 }
351}
352
353fn resolve_symbol(ctx: &Context, input: &str) -> Option<ResolvedGraphSymbol> {
356 let mut conn = match db::connect_readonly(&ctx.database_url) {
357 Ok(c) => c,
358 Err(e) => {
359 eprintln!("Failed to open index for graph resolution: {e}");
360 return None;
361 }
362 };
363 let (resolved, suggestions) = fts::resolve_graph_symbol(&mut conn, input, &ctx.project_id);
364 if resolved.is_none() {
365 if suggestions.is_empty() {
366 eprintln!("No symbol matching '{input}' found");
367 } else {
368 eprintln!(
369 "Ambiguous symbol '{input}'. Refine the query. Matches: {}",
370 suggestions.join(", ")
371 );
372 }
373 }
374 resolved
375}
376
377pub fn callers(
378 ctx: &Context,
379 symbol_name: &str,
380 limit: usize,
381 offset: usize,
382 format: Format,
383) -> anyhow::Result<()> {
384 if let Err(err) = code_graph::require_graph_reads(ctx) {
385 if graph_read_unavailable(&err) {
386 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
387 }
388 return Err(err);
389 }
390 let symbol = match resolve_symbol(ctx, symbol_name) {
391 Some(symbol) => symbol,
392 None => {
393 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
394 }
395 };
396 let total = match code_graph::count_callers(ctx, &symbol.id) {
397 Ok(total) => total,
398 Err(err) if graph_read_unavailable(&err) => {
399 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
400 }
401 Err(err) => return Err(err),
402 };
403 let results = match code_graph::find_callers(ctx, &symbol.id, offset, limit) {
404 Ok(results) => results,
405 Err(err) if graph_read_unavailable(&err) => {
406 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
407 }
408 Err(err) => return Err(err),
409 };
410
411 match format {
412 Format::Json => output::print_json(&PagedResponse {
413 project_id: ctx.project_id.clone(),
414 total,
415 offset,
416 limit,
417 results,
418 hint: hint_for(ctx),
419 }),
420 Format::Text => {
421 if results.is_empty() && offset == 0 {
422 println!("No callers found for '{}'", symbol.display_name);
423 print_graph_hint_text(ctx);
424 } else if results.is_empty() {
425 eprintln!("No callers at offset {offset} (total {total})");
426 } else {
427 for r in &results {
428 println!(
429 "{}:{} {} -> {}",
430 r.file_path, r.line, r.name, symbol.display_name
431 );
432 }
433 if total > offset + results.len() {
434 eprintln!(
435 "-- {} of {} results (use --offset {} for more)",
436 results.len(),
437 total,
438 offset + results.len()
439 );
440 }
441 }
442 Ok(())
443 }
444 }
445}
446
447pub fn usages(
448 ctx: &Context,
449 symbol_name: &str,
450 limit: usize,
451 offset: usize,
452 format: Format,
453) -> anyhow::Result<()> {
454 if let Err(err) = code_graph::require_graph_reads(ctx) {
455 if graph_read_unavailable(&err) {
456 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
457 }
458 return Err(err);
459 }
460 let symbol = match resolve_symbol(ctx, symbol_name) {
461 Some(symbol) => symbol,
462 None => {
463 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
464 }
465 };
466 let total = match code_graph::count_usages(ctx, &symbol.id) {
467 Ok(total) => total,
468 Err(err) if graph_read_unavailable(&err) => {
469 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
470 }
471 Err(err) => return Err(err),
472 };
473 let results = match code_graph::find_usages(ctx, &symbol.id, offset, limit) {
474 Ok(results) => results,
475 Err(err) if graph_read_unavailable(&err) => {
476 return empty_paged_response::<crate::models::GraphResult>(ctx, offset, limit, format);
477 }
478 Err(err) => return Err(err),
479 };
480
481 match format {
482 Format::Json => output::print_json(&PagedResponse {
483 project_id: ctx.project_id.clone(),
484 total,
485 offset,
486 limit,
487 results,
488 hint: hint_for(ctx),
489 }),
490 Format::Text => {
491 if results.is_empty() && offset == 0 {
492 println!("No usages found for '{}'", symbol.display_name);
493 print_graph_hint_text(ctx);
494 } else if results.is_empty() {
495 eprintln!("No usages at offset {offset} (total {total})");
496 } else {
497 for r in &results {
498 let rel = r.relation.as_deref().unwrap_or("unknown");
499 println!(
500 "{}:{} [{}] {} -> {}",
501 r.file_path, r.line, rel, r.name, symbol.display_name
502 );
503 }
504 if total > offset + results.len() {
505 eprintln!(
506 "-- {} of {} results (use --offset {} for more)",
507 results.len(),
508 total,
509 offset + results.len()
510 );
511 }
512 }
513 Ok(())
514 }
515 }
516}
517
518pub fn imports(ctx: &Context, file: &str, format: Format) -> anyhow::Result<()> {
519 if let Err(err) = code_graph::require_graph_reads(ctx) {
520 if graph_read_unavailable(&err) {
521 return empty_paged_response::<crate::models::GraphResult>(ctx, 0, 0, format);
522 }
523 return Err(err);
524 }
525 let results = match code_graph::get_imports(ctx, file) {
526 Ok(results) => results,
527 Err(err) if graph_read_unavailable(&err) => {
528 return empty_paged_response::<crate::models::GraphResult>(ctx, 0, 0, format);
529 }
530 Err(err) => return Err(err),
531 };
532 let total = results.len();
533 match format {
534 Format::Json => output::print_json(&PagedResponse {
535 project_id: ctx.project_id.clone(),
536 total,
537 offset: 0,
538 limit: total,
539 results,
540 hint: hint_for(ctx),
541 }),
542 Format::Text => {
543 if results.is_empty() {
544 println!("No imports found for '{file}'");
545 print_graph_hint_text(ctx);
546 } else {
547 for r in &results {
548 println!("{}", r.name);
549 }
550 }
551 Ok(())
552 }
553 }
554}
555
556pub fn blast_radius(
557 ctx: &Context,
558 target: &str,
559 depth: usize,
560 format: Format,
561) -> anyhow::Result<()> {
562 if let Err(err) = code_graph::require_graph_reads(ctx) {
563 if graph_read_unavailable(&err) {
564 return empty_paged_response::<crate::models::GraphResult>(ctx, 0, 0, format);
565 }
566 return Err(err);
567 }
568 let symbol = match resolve_symbol(ctx, target) {
569 Some(symbol) => symbol,
570 None => return empty_paged_response::<crate::models::GraphResult>(ctx, 0, 0, format),
571 };
572 let results = match code_graph::blast_radius(ctx, &symbol.id, depth) {
573 Ok(results) => results,
574 Err(err) if graph_read_unavailable(&err) => {
575 return empty_paged_response::<crate::models::GraphResult>(ctx, 0, 0, format);
576 }
577 Err(err) => return Err(err),
578 };
579 let total = results.len();
580 match format {
581 Format::Json => output::print_json(&PagedResponse {
582 project_id: ctx.project_id.clone(),
583 total,
584 offset: 0,
585 limit: total,
586 results,
587 hint: hint_for(ctx),
588 }),
589 Format::Text => {
590 if results.is_empty() {
591 println!("No blast radius found for '{}'", symbol.display_name);
592 print_graph_hint_text(ctx);
593 } else {
594 for r in &results {
595 let dist = r.distance.unwrap_or(0);
596 println!("{}:{} [distance={}] {}", r.file_path, r.line, dist, r.name);
597 }
598 }
599 Ok(())
600 }
601 }
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607 use crate::models::{GraphResult, ProjectionMetadata, ProjectionProvenance};
608 use serde_json::json;
609 use std::path::PathBuf;
610
611 fn make_ctx_no_falkordb() -> Context {
612 Context {
613 database_url: "postgresql://localhost/nonexistent".to_string(),
614 project_root: PathBuf::from("/nonexistent"),
615 project_id: "test-project".to_string(),
616 quiet: true,
617 falkordb: None,
618 qdrant: None,
619 embedding: None,
620 code_vectors: crate::config::CodeVectorSettings::default(),
621 daemon_url: None,
622 }
623 }
624
625 #[test]
626 fn graph_reads_degrade_when_falkor_missing() {
627 let ctx = make_ctx_no_falkordb();
628
629 imports(&ctx, "src/lib.rs", Format::Text).expect("imports degrade to empty output");
630 }
631
632 #[test]
633 fn report_text_structured_output() {
634 let report = crate::graph::report::empty_report("project-123");
635
636 let text = format_report_text(&report).expect("format report text");
637 let value: serde_json::Value = serde_json::from_str(&text).expect("structured JSON text");
638
639 assert_eq!(value["project_id"], "project-123");
640 assert_eq!(value["summary"]["node_count"], 0);
641 assert!(
642 value["markdown"]
643 .as_str()
644 .expect("markdown field")
645 .contains("# Project Graph Report")
646 );
647 assert!(!text.trim_start().starts_with('#'));
648 }
649
650 #[test]
651 fn report_requires_graph_service() {
652 let ctx = make_ctx_no_falkordb();
653
654 let err = report(&ctx, 10, Format::Json).expect_err("report must fail");
655
656 assert!(matches!(
657 err.downcast_ref::<crate::graph::report::ProjectGraphReportError>(),
658 Some(crate::graph::report::ProjectGraphReportError::GraphServiceNotConfigured)
659 ));
660 assert!(
661 err.to_string()
662 .contains("project graph report requires FalkorDB"),
663 "unexpected error: {err}"
664 );
665 }
666
667 #[test]
668 fn graph_lifecycle_commands_call_core_directly() {
669 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
670 let source = std::fs::read_to_string(manifest_dir.join("src/commands/graph.rs"))
671 .expect("read commands/graph.rs");
672 let clear_project = ["code_graph", "::clear_project(ctx)"].concat();
673 let sync_file_graph = ["code_graph", "::sync_file_graph("].concat();
674 let lifecycle_request = ["GraphLifecycleRequest", "::from_context"].concat();
675 let daemon_lifecycle = ["code_graph", "::run_lifecycle_action"].concat();
676
677 assert!(source.contains(&clear_project));
678 assert!(source.contains(&sync_file_graph));
679 assert!(!source.contains(&lifecycle_request));
680 assert!(!source.contains(&daemon_lifecycle));
681 }
682
683 #[test]
684 fn test_build_lifecycle_url_clear_uses_project_id_query() {
685 let url = code_graph::build_lifecycle_url(
686 "http://localhost:60887/",
687 GraphLifecycleAction::Clear,
688 "project-123",
689 )
690 .expect("url builds");
691
692 assert_eq!(
693 url.as_str(),
694 "http://localhost:60887/api/code-index/graph/clear?project_id=project-123"
695 );
696 }
697
698 #[test]
699 fn test_build_lifecycle_url_rebuild_uses_project_id_query() {
700 let url = code_graph::build_lifecycle_url(
701 "http://localhost:60887",
702 GraphLifecycleAction::Rebuild,
703 "project-123",
704 )
705 .expect("url builds");
706
707 assert_eq!(
708 url.as_str(),
709 "http://localhost:60887/api/code-index/graph/rebuild?project_id=project-123"
710 );
711 }
712
713 #[test]
714 fn test_require_daemon_url_errors_when_missing() {
715 let err = code_graph::require_daemon_url(None, GraphLifecycleAction::Clear)
716 .expect_err("must fail");
717
718 assert!(
719 err.to_string()
720 .contains("Gobby daemon URL is not configured"),
721 "unexpected error: {err}"
722 );
723 assert!(
724 err.to_string().contains("gcode graph clear"),
725 "unexpected error: {err}"
726 );
727 }
728
729 #[test]
730 fn test_format_http_error_includes_status_and_body() {
731 let url = reqwest::Url::parse("http://localhost:60887/api/code-index/graph/clear")
732 .expect("valid url");
733 let message = code_graph::format_http_error(
734 GraphLifecycleAction::Clear,
735 &url,
736 reqwest::StatusCode::BAD_GATEWAY,
737 "daemon upstream unavailable",
738 );
739
740 assert!(message.contains("HTTP 502"), "unexpected error: {message}");
741 assert!(
742 message.contains("daemon upstream unavailable"),
743 "unexpected error: {message}"
744 );
745 }
746
747 #[test]
748 fn test_parse_success_payload_fails_on_invalid_json() {
749 let err = code_graph::parse_success_payload(
750 GraphLifecycleAction::Rebuild,
751 reqwest::StatusCode::OK,
752 "not json",
753 )
754 .expect_err("invalid json must fail");
755
756 assert!(
757 err.to_string().contains("invalid JSON"),
758 "unexpected error: {err}"
759 );
760 assert!(
761 err.to_string().contains("HTTP 200 OK"),
762 "unexpected error: {err}"
763 );
764 }
765
766 #[test]
767 fn test_format_success_text_prefers_message_field() {
768 let payload = json!({
769 "message": "cleared 12 graph nodes",
770 "removed_nodes": 12
771 });
772 let output = GraphLifecycleOutput {
773 project_id: "project-123".to_string(),
774 action: GraphLifecycleAction::Clear,
775 summary: "cleared 12 graph nodes".to_string(),
776 payload,
777 };
778 let text = format_success_text(&output);
779
780 assert_eq!(
781 text,
782 "Cleared code-index graph for project project-123: cleared 12 graph nodes"
783 );
784 }
785
786 #[test]
787 fn test_format_success_text_falls_back_to_compact_json() {
788 let payload = json!({
789 "replayed": 18,
790 "synced": 18
791 });
792 let output = GraphLifecycleOutput {
793 project_id: "project-123".to_string(),
794 action: GraphLifecycleAction::Rebuild,
795 summary: payload.to_string(),
796 payload,
797 };
798 let text = format_success_text(&output);
799
800 assert_eq!(
801 text,
802 "Rebuilt code-index graph for project project-123: {\"replayed\":18,\"synced\":18}"
803 );
804 }
805
806 #[test]
807 fn top_level_read_commands_preserve_json_shape() {
808 let response = PagedResponse {
809 project_id: "project-123".to_string(),
810 total: 1,
811 offset: 0,
812 limit: 10,
813 results: vec![GraphResult {
814 id: "sym-1".to_string(),
815 name: "run".to_string(),
816 file_path: "src/lib.rs".to_string(),
817 line: 12,
818 relation: Some("CALLS".to_string()),
819 distance: Some(1),
820 metadata: None,
821 }],
822 hint: None,
823 };
824
825 let value = serde_json::to_value(&response).expect("serialize response");
826
827 assert_eq!(value["project_id"], "project-123");
828 assert_eq!(value["total"], 1);
829 assert_eq!(value["offset"], 0);
830 assert_eq!(value["limit"], 10);
831 assert_eq!(value["results"][0]["id"], "sym-1");
832 assert_eq!(value["results"][0]["name"], "run");
833 assert_eq!(value["results"][0]["file_path"], "src/lib.rs");
834 assert_eq!(value["results"][0]["line"], 12);
835 assert_eq!(value["results"][0]["relation"], "CALLS");
836 assert_eq!(value["results"][0]["distance"], 1);
837 assert!(value["hint"].is_null());
838 assert!(value["results"][0].get("metadata").is_none());
839
840 let response = PagedResponse {
841 project_id: "project-123".to_string(),
842 total: 1,
843 offset: 0,
844 limit: 10,
845 results: vec![GraphResult {
846 id: "sym-1".to_string(),
847 name: "run".to_string(),
848 file_path: "src/lib.rs".to_string(),
849 line: 12,
850 relation: Some("CALLS".to_string()),
851 distance: Some(1),
852 metadata: Some(
853 ProjectionMetadata::new(ProjectionProvenance::Extracted, "gcode")
854 .with_source_file_path("src/lib.rs"),
855 ),
856 }],
857 hint: None,
858 };
859 let value = serde_json::to_value(&response).expect("serialize metadata response");
860
861 assert_eq!(
862 value["results"][0]["metadata"]["source_file_path"],
863 "src/lib.rs"
864 );
865 }
866}