codenexus 0.4.0-rc.2

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
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! CLI integration tests — verifies the sdforge-based CLI boots, parses
//! arguments, and dispatches to service-layer handlers via inventory.
use std::process::Command;

/// Returns the codenexus binary path.
fn binary() -> &'static str {
    env!("CARGO_BIN_EXE_codenexus")
}

/// Runs `codenexus <args>` and returns (exit_code, stdout, stderr).
fn run(args: &[&str]) -> (i32, String, String) {
    let output = Command::new(binary())
        .args(args)
        // 本测试的文案断言是英文字面量("Quick start:"、"no subcommand");
        // 钉住子进程语言,断言在任何主机 locale 下都成立。
        .env("CODENEXUS_LANG", "en")
        .output()
        .unwrap_or_else(|e| panic!("failed to spawn codenexus: {e}"));
    (
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
    )
}

#[test]
fn help_lists_all_commands() {
    let (code, stdout, _) = run(&["--help"]);
    assert_eq!(code, 0, " --help should exit 0");
    assert!(stdout.contains("Usage:"), "should show Usage line");
    // Every user-facing subcommand (docs advertise 37 + the `mcp` serve mode)
    // must be listed in the `Commands:` section — a missing registration means
    // the command is unreachable from the CLI.
    for cmd in [
        "index",
        "query",
        "search",
        "trace",
        "impact",
        "context",
        "dead_code",
        "architecture",
        "complexity",
        "community",
        "cross_service",
        "route_map",
        "tool_map",
        "shape_check",
        "api_impact",
        "diagram",
        "arch_diff",
        "detect_changes",
        "rename",
        "lsp_goto_def",
        "lsp_hover",
        "export",
        "import",
        "setup",
        "hook",
        "skill",
        "ask",
        "ci",
        "lint",
        "taint",
        "supply",
        "evolve",
        "hub",
        "list",
        "status",
        "clean",
        "daemon",
    ] {
        assert!(
            stdout.contains(cmd),
            "`--help` should list the `{cmd}` command, got:\n{stdout}"
        );
    }
}

/// The `mcp` serve mode is registered with clap (so it shows up in `--help`)
/// even though its stdio server is dispatched before clap parsing.
#[test]
#[cfg(feature = "mcp")]
fn help_lists_mcp_serve_mode() {
    let (code, stdout, _) = run(&["--help"]);
    assert_eq!(code, 0, "--help should exit 0");
    assert!(
        stdout.contains("mcp"),
        "`--help` should list the `mcp` serve mode, got:\n{stdout}"
    );
}

#[test]
fn version_flag_prints_version() {
    let (code, stdout, _) = run(&["--version"]);
    assert_eq!(code, 0, "--version should exit 0");
    assert!(
        stdout.contains("codenexus") || stdout.contains("CodeNexus"),
        "version output should contain crate name, got: {stdout}"
    );
}

#[test]
fn no_subcommand_exits_gracefully() {
    let (code, stdout, _) = run(&[]);
    assert_eq!(code, 0, "no subcommand should exit 0");
    assert!(
        stdout.contains("--help"),
        "should suggest --help, got: {stdout}"
    );
}

#[test]
fn list_command_works_with_empty_db() {
    let tmp = tempfile::NamedTempFile::new().expect("create temp db file");
    let db_path = tmp.path().to_str().expect("db path to str");
    let (code, _stdout, stderr) = run(&["--db", db_path, "list"]);
    assert_eq!(code, 0, "list should exit 0 on empty db, stderr: {stderr}");
}

#[test]
fn status_command_works_with_empty_db() {
    let tmp = tempfile::NamedTempFile::new().expect("create temp db file");
    let db_path = tmp.path().to_str().expect("db path to str");
    let (code, _, stderr) = run(&["--db", db_path, "status"]);
    assert_eq!(
        code, 0,
        "status should exit 0 on empty db, stderr: {stderr}"
    );
}

#[test]
fn query_command_returns_result() {
    let tmp = tempfile::NamedTempFile::new().expect("create temp db file");
    let db_path = tmp.path().to_str().expect("db path to str");
    let (code, stdout, stderr) = run(&["--db", db_path, "query", "--cypher", "RETURN 1 AS one"]);
    assert_eq!(code, 0, "query should exit 0, stderr: {stderr}");
    assert!(
        stdout.contains("\"one\"") || stdout.contains("one"),
        "query output should contain column 'one', got: {stdout}"
    );
}

#[test]
fn unknown_subcommand_exits_with_error() {
    let (code, _, stderr) = run(&["nonexistent_command"]);
    assert_ne!(
        code, 0,
        "unknown command should exit non-zero, stderr: {stderr}"
    );
}

/// A corrupt DB file must exit 4 — the documented "Not found / database
/// corrupt" contract (skill/references/appendix.md "Exit Codes"; mapping in
/// src/service/error.rs: "NotFound, Index(corrupt), Kit(corrupt)" → 4) — with
/// a clear message. Regression guard: the Kit build failure used to be merely
/// warned about, so every command fell through to `kit_not_initialized`
/// (Internal → exit 1), masking the corruption and leaving the dedicated
/// `kit_exit_code` corruption downcast unreachable.
#[test]
fn corrupt_db_exits_4_with_clear_message() {
    let tmp = tempfile::NamedTempFile::new().expect("create temp db file");
    std::fs::write(tmp.path(), b"this is not a valid ladybugdb file").expect("write corrupt bytes");
    let db_path = tmp.path().to_str().expect("db path to str");

    let mut cases: Vec<Vec<String>> = vec![
        vec!["--db".into(), db_path.into(), "list".into()],
        vec!["--db".into(), db_path.into(), "status".into()],
        vec![
            "--db".into(),
            db_path.into(),
            "query".into(),
            "--cypher".into(),
            "RETURN 1 AS one".into(),
        ],
    ];
    // `index` is the command named by the corrupt_db exit-code spec; it also
    // builds the Kit before dispatch and must surface the same exit code.
    let repo = tempfile::TempDir::new().expect("create repo dir");
    cases.push(vec![
        "--db".into(),
        db_path.into(),
        "index".into(),
        "--path".into(),
        repo.path().to_str().expect("repo path to str").into(),
        "--name".into(),
        "corrupt_demo".into(),
    ]);

    for args in &cases {
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let (code, _stdout, stderr) = run(&arg_refs);
        assert_eq!(
            code, 4,
            "{args:?} on a corrupt DB should exit 4, stderr: {stderr}"
        );
        assert!(
            stderr.contains("database corrupt"),
            "{args:?} stderr should name the corruption, got: {stderr}"
        );
    }
}

// --- global `--format text|json` machine-readable output contract ---
// (sdforge `cli::output`; CodeNexus renders its own CLI boundary output, so
// the contract is pinned end to end here: stream choice and exit codes.)

/// Explicit `--format text` keeps the default behaviour byte for byte: the
/// human quick-start banner on stdout and exit 0.
#[test]
fn format_text_keeps_human_banner_and_exit_zero() {
    let (code, stdout, _) = run(&["--format", "text"]);
    assert_eq!(code, 0, "explicit text mode must keep the no-op exit code");
    assert!(
        stdout.contains("Quick start:"),
        "text mode must keep the banner, got: {stdout}"
    );
}

/// `--format json` turns the "no subcommand" condition into the contract's
/// UnifiedError JSON payload on stdout; the exit code follows the payload
/// class (`BAD_REQUEST` → 2), never a bare 1. The human banner would be
/// unparseable machine output.
#[test]
fn format_json_no_subcommand_emits_unified_error_json_on_stdout() {
    let (code, stdout, stderr) = run(&["--format", "json"]);
    assert_eq!(
        code, 2,
        "json usage error must exit with the payload's class code, stderr: {stderr}"
    );
    let payload: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
        panic!("stdout must carry exactly the JSON payload, got {stdout:?}: {e}")
    });
    assert_eq!(payload["code"], "BAD_REQUEST");
    assert!(
        payload["message"]
            .as_str()
            .unwrap_or_default()
            .contains("no subcommand"),
        "payload must explain the usage error, got: {payload}"
    );
    assert!(
        !stdout.contains("Quick start:"),
        "the human banner must not leak into json mode, got: {stdout}"
    );
}

/// `--format` is mounted with a `text|json` whitelist; anything else is
/// rejected by clap before any work happens.
#[test]
fn format_rejects_unknown_values() {
    let (code, _, stderr) = run(&["--format", "yaml", "list"]);
    assert_ne!(code, 0, "unknown --format value must be rejected");
    assert!(
        stderr.contains("yaml"),
        "clap must name the rejected value, stderr: {stderr}"
    );
}

/// Handler failures in `--format json` render the UnifiedError payload on
/// stdout (never the text `Error:` line on stderr), keeping CodeNexus's own
/// exit codes.
#[test]
fn format_json_handler_error_is_unified_error_on_stdout() {
    let tmp = tempfile::NamedTempFile::new().expect("create temp db file");
    let db_path = tmp.path().to_str().expect("db path to str");
    let (code, stdout, stderr) = run(&[
        "--db",
        db_path,
        "--format",
        "json",
        "query",
        "--cypher",
        "DEFINITELY NOT CYPHER",
    ]);
    assert_ne!(code, 0, "invalid cypher must fail, stderr: {stderr}");
    let payload: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
        panic!("stdout must carry exactly the JSON payload, got {stdout:?}: {e}")
    });
    assert_eq!(
        payload["code"], "BAD_REQUEST",
        "invalid cypher is an input error, got: {payload}"
    );
    assert_eq!(
        code, 2,
        "exit code must match the payload class (BAD_REQUEST → 2)"
    );
    assert!(
        payload["message"].as_str().is_some_and(|m| !m.is_empty()),
        "payload must carry a message, got: {payload}"
    );
    assert!(
        !stderr.contains("Error:"),
        "json mode must not use the text error line, stderr: {stderr}"
    );
}

#[test]
fn ci_gate_e2e_fails_on_high_risk_and_passes_with_fail_on_none() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let root = tmp.path();

    let git = |args: &[&str]| {
        Command::new("git")
            .arg("-C")
            .arg(root)
            .args(args)
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    };
    if !git(&["init"]) {
        eprintln!("skipping test: git unavailable");
        return;
    }

    // Commit 1: a hub function called by five callers across files.
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(
        root.join("src/hub.rs"),
        "pub fn hub_fn() -> i32 {\n    42\n}\n",
    )
    .unwrap();
    let mut callers = String::new();
    for i in 0..5 {
        callers.push_str(&format!(
            "pub fn caller_{i}() -> i32 {{\n    hub_fn()\n}}\n"
        ));
    }
    std::fs::write(root.join("src/callers.rs"), callers).unwrap();
    assert!(git(&["add", "."]));
    assert!(git(&[
        "-c",
        "user.email=t@t.com",
        "-c",
        "user.name=T",
        "commit",
        "-m",
        "init"
    ]));

    // Index the committed tree (binary writes .codenexus/<name>.lbug in cwd).
    let (code, _stdout, stderr) = run_in(root, &["index", "--path", ".", "--name", "gate_e2e"]);
    assert_eq!(code, 0, "index should exit 0, stderr: {stderr}");

    // Uncommitted edit inside hub_fn's line range.
    std::fs::write(
        root.join("src/hub.rs"),
        "pub fn hub_fn() -> i32 {\n    // changed\n    43\n}\n",
    )
    .unwrap();

    // Gate with fail_on=high: hub_fn has >=4 incoming CALLS edges → high risk
    // → verdict=fail and the process exits 2.
    let (code, stdout, stderr) = run_in(
        root,
        &[
            "--db",
            ".codenexus/gate_e2e.lbug",
            "ci",
            "--path",
            ".",
            "--base_mode",
            "unstaged",
            "--fail_on",
            "high",
        ],
    );
    let json_line = stdout
        .lines()
        .find(|l| l.starts_with('{'))
        .expect("ci should print a JSON receipt");
    let receipt: serde_json::Value = serde_json::from_str(json_line).expect("valid gate JSON");
    assert_eq!(receipt["verdict"], "fail", "gate must fail: {stderr}");
    assert_eq!(receipt["base_mode"], "unstaged");
    assert!(
        receipt["risk_counts"]["high"].as_u64().unwrap() >= 1,
        "hub_fn should be high risk: {receipt}"
    );
    assert!(
        receipt["markdown"]
            .as_str()
            .unwrap()
            .contains("CodeNexus Architecture Gate"),
        "markdown report must be present"
    );
    assert_eq!(code, 2, "failed gate must exit 2");

    // fail_on=none never fails → exit 0 even with the same diff.
    let (code, stdout, _) = run_in(
        root,
        &[
            "--db",
            ".codenexus/gate_e2e.lbug",
            "ci",
            "--path",
            ".",
            "--base_mode",
            "unstaged",
            "--fail_on",
            "none",
        ],
    );
    assert_eq!(code, 0, "fail_on=none must pass");
    let json_line = stdout
        .lines()
        .find(|l| l.starts_with('{'))
        .expect("gate JSON present");
    let receipt: serde_json::Value = serde_json::from_str(json_line).unwrap();
    assert_eq!(receipt["verdict"], "pass");
    assert_eq!(receipt["fail_on"], "none");
}

/// Runs the codenexus binary with `root` as the working directory.
fn run_in(root: &std::path::Path, args: &[&str]) -> (i32, String, String) {
    let output = Command::new(binary())
        .args(args)
        .current_dir(root)
        .output()
        .unwrap_or_else(|e| panic!("failed to spawn codenexus: {e}"));
    (
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
    )
}

/// `cn` 是 `codenexus` 的等形态别名二进制(同一源构建,同一 CLI 面)。
#[test]
fn cn_alias_binary_shares_the_cli_surface() {
    let cn = env!("CARGO_BIN_EXE_cn");
    let out = Command::new(cn)
        .arg("--version")
        .output()
        .unwrap_or_else(|e| panic!("failed to spawn cn: {e}"));
    assert!(out.status.success(), "cn --version should exit 0");
    let version = String::from_utf8_lossy(&out.stdout);
    assert!(
        version.contains(env!("CARGO_PKG_VERSION")),
        "cn --version should carry the crate version, got: {version}"
    );

    let help = Command::new(cn)
        .arg("--help")
        .output()
        .unwrap_or_else(|e| panic!("failed to spawn cn: {e}"));
    assert!(help.status.success(), "cn --help should exit 0");
    let help_text = String::from_utf8_lossy(&help.stdout);
    assert!(
        help_text.contains("Usage:"),
        "cn --help must render the CLI"
    );

    // `cn webui --help`:启用 webui feature 时该子命令与 --port 参数可见
    if cfg!(feature = "webui") {
        let webui_help = Command::new(cn)
            .args(["webui", "--help"])
            .output()
            .unwrap_or_else(|e| panic!("failed to spawn cn webui: {e}"));
        assert!(webui_help.status.success(), "cn webui --help should exit 0");
        let text = String::from_utf8_lossy(&webui_help.stdout);
        assert!(
            text.contains("--port"),
            "cn webui --help 应列出 --port:{text}"
        );
    }
}