codenexus 0.3.5

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! `architecture` service: high-level project structure overview.

use serde::Serialize;

#[cfg(feature = "analysis")]
use crate::analysis::architecture::{ArchitectureAnalyzer, ArchitectureOverview};
#[cfg(feature = "analysis")]
use crate::kit::{AsyncKit, AsyncReady, StorageModule};
#[cfg(all(feature = "analysis", any(feature = "cli", feature = "mcp")))]
use crate::service::error::kit_not_initialized;
#[cfg(all(feature = "analysis", any(feature = "cli", feature = "mcp")))]
use crate::service::error::to_api_error;
#[cfg(feature = "analysis")]
use crate::service::error::CodeNexusError;
#[cfg(feature = "analysis")]
use crate::service::project::resolve_project_id;
#[cfg(all(feature = "analysis", any(feature = "cli", feature = "mcp")))]
use crate::service::runtime::kit;

#[cfg(all(feature = "analysis", any(feature = "cli", feature = "mcp")))]
use sdforge::forge;
#[cfg(all(feature = "analysis", any(feature = "cli", feature = "mcp")))]
use sdforge::prelude::ApiError;

/// JSON-serializable architecture output.
#[cfg(feature = "analysis")]
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ArchitectureOutput {
    pub project: String,
    pub overview: ArchitectureOverview,
}

/// Runs architecture overview against an injected Kit (testable core).
///
/// Returns the full [`ArchitectureOverview`] including the enhanced fields:
/// `module_boundaries`, `dependency_directions`, `layers`, and
/// `cross_service_deps`.
#[cfg(feature = "analysis")]
pub fn run_architecture(
    kit: &AsyncKit<AsyncReady>,
    project: &str,
) -> Result<ArchitectureOutput, CodeNexusError> {
    let storage = kit.require::<StorageModule>()?;
    let project_id = resolve_project_id(&*storage, project)?;
    let analyzer = ArchitectureAnalyzer::new(&*storage);
    let overview: ArchitectureOverview = analyzer.overview(&project_id)?;
    Ok(ArchitectureOutput {
        project: project.to_string(),
        overview,
    })
}

/// CLI wrapper — prints result to stdout as JSON.
#[cfg(all(feature = "cli", feature = "analysis"))]
#[forge(
    name = "architecture",
    version = "0.3.5",
    description = "Show high-level architecture overview of a project.",
    cli = true
)]
async fn architecture(project: String) -> Result<(), ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    let output =
        run_architecture(&kit, &project).map_err(|e| to_api_error(e, "architecture_error"))?;
    let json = serde_json::to_string(&output)
        .map_err(|e| to_api_error(CodeNexusError::from(e), "architecture_error"))?;
    println!("{json}");
    Ok(())
}

/// MCP wrapper — returns result for MCP protocol.
#[cfg(all(feature = "mcp", feature = "analysis"))]
#[forge(
    name = "architecture",
    version = "0.3.5",
    tool_name = "architecture",
    description = "Show high-level architecture overview of a project."
)]
async fn architecture_mcp(project: String) -> Result<ArchitectureOutput, ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    run_architecture(&kit, &project).map_err(|e| to_api_error(e, "architecture_error"))
}

#[cfg(all(test, feature = "cli", feature = "analysis"))]
mod tests {
    use super::*;
    use crate::kit::{build_kit, AsyncKit, AsyncReady, KitBootstrapConfig, StorageModule};
    use crate::storage::capability::Storage;
    use tempfile::TempDir;

    fn fresh_db_path() -> (TempDir, std::path::PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("svc_architecture_testdb");
        (dir, path)
    }

    fn build_kit_for_db(db: &std::path::Path) -> AsyncKit<AsyncReady> {
        let config = KitBootstrapConfig::new(db.to_path_buf());
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(build_kit(&config))
            .expect("build_kit")
    }

    fn seed_project(storage: &dyn Storage, id: &str, name: &str) {
        storage
            .execute(&format!(
                "CREATE (:Project {{id: '{id}', name: '{name}', rootPath: '/demo', language: 'rust', fileCount: 1, indexedAt: 1000, lastCommit: 'abc'}});"
            ))
            .expect("create project");
    }

    #[test]
    fn run_architecture_succeeds_on_empty_db() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert_eq!(output.project, "demo");
        assert!(output.overview.languages.is_empty());
        assert!(output.overview.packages.is_empty());
        assert!(output.overview.entry_points.is_empty());
        assert!(output.overview.routes.is_empty());
        assert!(output.overview.hotspots.is_empty());
    }

    #[test]
    fn run_architecture_returns_languages() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage
            .execute("CREATE (:File {id: 'f1', project: 'demo', name: 'main.rs', filePath: '/src/main.rs', language: 'rust', hash: '', lineCount: 0});")
            .expect("create file");
        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert_eq!(output.project, "demo");
        assert!(!output.overview.languages.is_empty());
    }

    #[test]
    fn run_architecture_with_routes() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage
            .execute("CREATE (:Route {id: 'r1', project: 'demo', name: '/api/users', qualifiedName: '/api/users', filePath: '', startLine: 0, endLine: 0, httpMethod: 'GET', path: '/api/users', parentQn: ''});")
            .expect("create route");
        storage
            .execute("CREATE (:Handler {id: 'h1', project: 'demo', name: 'list_users', qualifiedName: 'list_users', filePath: '', startLine: 0, endLine: 0, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});")
            .expect("create handler");
        storage
            .execute("CREATE (:CodeRelation {id: 'e1', source: 'h1', target: 'r1', type: 'HANDLES', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 1, project: 'demo'});")
            .expect("create edge");
        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert!(!output.overview.routes.is_empty());
    }

    #[test]
    fn output_serializes_to_json() {
        let out = ArchitectureOutput {
            project: "demo".into(),
            overview: ArchitectureOverview {
                languages: vec![],
                packages: vec![],
                entry_points: vec![],
                routes: vec![],
                hotspots: vec![],
                module_boundaries: vec![],
                dependency_directions: vec![],
                layers: vec![],
                cross_service_deps: vec![],
            },
        };
        let json = serde_json::to_string(&out).unwrap();
        assert!(json.contains("\"project\":\"demo\""));
        assert!(json.contains("\"overview\""));
    }

    // ===== T041: Enhanced architecture fields tests =====

    #[test]
    fn run_architecture_includes_module_boundaries() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        // Create functions in different modules
        storage.execute("CREATE (:Function {id: 'f_a1', project: 'demo', name: 'a1', qualifiedName: 'demo.a1', filePath: '/src/a/a1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a1");
        storage.execute("CREATE (:Function {id: 'f_b1', project: 'demo', name: 'b1', qualifiedName: 'demo.b1', filePath: '/src/b/b1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create b1");
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_a1', target: 'f_b1', type: 'CALLS', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 2, project: 'demo'});").expect("create cross-module edge");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert!(
            !output.overview.module_boundaries.is_empty(),
            "should detect module boundaries"
        );
        let module_names: Vec<&str> = output
            .overview
            .module_boundaries
            .iter()
            .map(|m| m.module_name.as_str())
            .collect();
        assert!(
            module_names.iter().any(|n| n.ends_with("src/a")),
            "should have module src/a, got: {module_names:?}"
        );
        assert!(
            module_names.iter().any(|n| n.ends_with("src/b")),
            "should have module src/b, got: {module_names:?}"
        );
    }

    #[test]
    fn run_architecture_includes_dependency_directions() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_a1', project: 'demo', name: 'a1', qualifiedName: 'demo.a1', filePath: '/src/a/a1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a1");
        storage.execute("CREATE (:Function {id: 'f_b1', project: 'demo', name: 'b1', qualifiedName: 'demo.b1', filePath: '/src/b/b1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create b1");
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_a1', target: 'f_b1', type: 'CALLS', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 2, project: 'demo'});").expect("create a->b edge");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert!(
            !output.overview.dependency_directions.is_empty(),
            "should detect dependency directions"
        );
        let dir = &output.overview.dependency_directions[0];
        assert!(
            dir.from_module.ends_with("src/a") || dir.to_module.ends_with("src/b"),
            "should have direction from src/a to src/b"
        );
    }

    #[test]
    fn run_architecture_includes_layers() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        // Controller: function that HANDLES_ROUTE
        storage.execute("CREATE (:Function {id: 'f_ctrl', project: 'demo', name: 'list_users', qualifiedName: 'demo.list_users', filePath: '/src/api/handler.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create controller");
        storage.execute("CREATE (:Route {id: 'r1', project: 'demo', name: '/api/users', qualifiedName: '/api/users', filePath: '', startLine: 0, endLine: 0, httpMethod: 'GET', path: '/api/users', parentQn: ''});").expect("create route");
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_ctrl', target: 'r1', type: 'HANDLES_ROUTE', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 1, project: 'demo'});").expect("create HANDLES_ROUTE edge");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert!(!output.overview.layers.is_empty(), "should detect layers");
        let controller = output
            .overview
            .layers
            .iter()
            .find(|l| l.layer == "Controller")
            .expect("should have Controller layer");
        assert!(
            controller.members.contains(&"demo.list_users".to_string()),
            "Controller layer should contain demo.list_users"
        );
    }

    #[test]
    fn run_architecture_serializes_enhanced_fields() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_architecture(&kit, "demo").expect("run should succeed");
        let json = serde_json::to_string(&output).unwrap();
        assert!(
            json.contains("\"module_boundaries\""),
            "json should contain module_boundaries"
        );
        assert!(
            json.contains("\"dependency_directions\""),
            "json should contain dependency_directions"
        );
        assert!(json.contains("\"layers\""), "json should contain layers");
        assert!(
            json.contains("\"cross_service_deps\""),
            "json should contain cross_service_deps"
        );
    }

    #[test]
    fn run_architecture_detects_circular_dependency() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_a1', project: 'demo', name: 'a1', qualifiedName: 'demo.a1', filePath: '/src/a/a1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a1");
        storage.execute("CREATE (:Function {id: 'f_b1', project: 'demo', name: 'b1', qualifiedName: 'demo.b1', filePath: '/src/b/b1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create b1");
        // A→B and B→A (circular)
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_a1', target: 'f_b1', type: 'CALLS', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 2, project: 'demo'});").expect("create a->b");
        storage.execute("CREATE (:CodeRelation {id: 'e2', source: 'f_b1', target: 'f_a1', type: 'CALLS', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 2, project: 'demo'});").expect("create b->a");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        let has_circular = output
            .overview
            .dependency_directions
            .iter()
            .any(|d| d.is_circular);
        assert!(has_circular, "should detect circular dependency");
    }

    #[test]
    fn run_architecture_module_boundary_cohesion() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        // Module A with internal calls only → cohesion = 1.0
        storage.execute("CREATE (:Function {id: 'f_a1', project: 'demo', name: 'a1', qualifiedName: 'demo.a1', filePath: '/src/a/a1.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a1");
        storage.execute("CREATE (:Function {id: 'f_a2', project: 'demo', name: 'a2', qualifiedName: 'demo.a2', filePath: '/src/a/a2.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a2");
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_a1', target: 'f_a2', type: 'CALLS', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 2, project: 'demo'});").expect("create internal edge");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        let module_a = output
            .overview
            .module_boundaries
            .iter()
            .find(|m| m.module_name.ends_with("src/a"))
            .expect("should find module src/a");
        assert_eq!(module_a.incoming_deps, 0);
        assert_eq!(module_a.outgoing_deps, 0);
        assert!(
            (module_a.cohesion - 1.0).abs() < 0.001,
            "cohesion should be 1.0 for isolated module"
        );
    }

    // ===== run_architecture: cross_service_deps via Route + fetch content =====

    #[test]
    fn run_architecture_includes_cross_service_deps() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Route {id: 'r1', project: 'demo', name: '/api/users', qualifiedName: '/api/users', filePath: '', startLine: 0, endLine: 0, httpMethod: 'GET', path: '/api/users', parentQn: ''});").expect("create route");
        storage.execute("CREATE (:Function {id: 'f_a', project: 'demo', name: 'caller', qualifiedName: 'demo.caller', filePath: '/src/a/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: 'fetch(\"/api/users\");', parentQn: ''});").expect("create caller");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert!(
            !output.overview.cross_service_deps.is_empty(),
            "should detect cross-service deps via Route + fetch content"
        );
    }

    #[test]
    fn run_architecture_with_packages() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:File {id: 'f1', project: 'demo', name: 'main.rs', filePath: '/src/main.rs', language: 'rust', hash: '', lineCount: 100});").expect("create file");
        storage.execute("CREATE (:Function {id: 'f_a', project: 'demo', name: 'a', qualifiedName: 'demo.a', filePath: '/src/main.rs', startLine: 1, endLine: 50, signature: '', returnType: '', isExported: true, docstring: '', content: '', parentQn: ''});").expect("create function");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert_eq!(output.project, "demo");
    }

    #[test]
    fn run_architecture_with_entry_points() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_main', project: 'demo', name: 'main', qualifiedName: 'demo.main', filePath: '/src/main.rs', startLine: 1, endLine: 50, signature: 'fn main()', returnType: '', isExported: true, docstring: '', content: '', parentQn: ''});").expect("create main");
        storage.execute("CREATE (:CodeRelation {id: 'e_ep', source: 'f_main', target: 'f_main', type: 'ENTRY_POINT', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 1, project: 'demo'});").expect("create entry point edge");

        let output = run_architecture(&kit, "demo").expect("run should succeed");
        assert_eq!(output.project, "demo");
    }

    #[test]
    fn run_architecture_unknown_project_returns_empty_overview() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        storage.execute("CREATE (:File {id: 'f1', project: 'other', name: 'main.rs', filePath: '/src/main.rs', language: 'rust', hash: '', lineCount: 0});").expect("create file in other project");

        let err = run_architecture(&kit, "demo").expect_err("unknown project should error");
        assert!(matches!(err, CodeNexusError::ProjectNotFound(_)));
    }

    // ===== #[forge] wrapper tests via init_kit =====

    #[serial_test::serial(kit_init)]
    #[test]
    fn architecture_wrapper_succeeds_via_init_kit() {
        use crate::service::runtime::{init_kit, reset_kit_for_testing};

        reset_kit_for_testing();
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        init_kit(kit).expect("init_kit");

        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(architecture("demo".to_string()));
        assert!(result.is_ok(), "wrapper should succeed: {:?}", result.err());

        reset_kit_for_testing();
    }

    #[serial_test::serial(kit_init)]
    #[test]
    fn architecture_wrapper_fails_when_kit_not_initialized() {
        use crate::service::runtime::reset_kit_for_testing;

        reset_kit_for_testing();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(architecture("demo".to_string()));
        assert!(result.is_err(), "wrapper should fail without kit");
        reset_kit_for_testing();
    }
}