cordance-cli 0.1.2

Cordance CLI — installs the `cordance` binary. The umbrella package `cordance` re-exports this entry; either install command works.
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
use assert_cmd::prelude::*;
use std::process::Command;

#[test]
fn cordance_init_creates_config() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("init");
    cmd.assert().success();
    assert!(dir.path().join("cordance.toml").exists());
}

#[test]
fn cordance_init_skips_if_exists() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(dir.path().join("cordance.toml"), "[project]\n").expect("write");
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("init");
    cmd.assert().success();
    // Content should be unchanged (the original stub)
    let content = std::fs::read_to_string(dir.path().join("cordance.toml")).expect("read");
    assert_eq!(content, "[project]\n");
}

#[test]
fn cordance_scan_json_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(".").arg("scan").arg("--json");
    cmd.assert().success();
}

#[test]
fn cordance_scan_plain_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(".").arg("scan");
    cmd.assert().success();
}

#[test]
fn cordance_pack_dry_run_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(".")
        .arg("pack")
        .arg("--output-mode")
        .arg("dry-run");
    cmd.assert().success();
}

#[test]
fn cordance_pack_diff_mode_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(".")
        .arg("pack")
        .arg("--output-mode")
        .arg("diff");
    cmd.assert().success();
}

#[test]
fn cordance_advise_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(".").arg("advise");
    cmd.assert().success();
}

#[test]
fn cordance_advise_json_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(".").arg("advise").arg("--json");
    cmd.assert().success();
}

#[test]
fn cordance_check_on_empty_target_exits_gracefully() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("check");
    // Should exit 1 (no sources.lock), not panic
    let status = cmd.status().expect("run");
    assert!(status.code().is_some());
}

#[test]
fn cordance_status_reports_operator_summary_without_writes() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(dir.path().join("doctrine-root")).expect("mkdir doctrine root");
    std::fs::write(
        dir.path().join("cordance.toml"),
        r#"
[doctrine]
source = "doctrine-root"
fallback_repo = "https://nonexistent.example.invalid/doctrine"
pin_commit = "auto"

[axiom]
source = "axiom-root"
algorithm_latest = "v-test-status"
"#,
    )
    .expect("write cordance.toml");

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("status");
    let output = cmd.output().expect("run cordance status");

    assert!(
        output.status.success(),
        "status failed: stdout={}, stderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    for needle in [
        "cordance status",
        "config: cordance.toml found",
        "source lock: missing",
        "advise:",
        "doctrine pin: none",
        "axiom pin: v-test-status",
        "readiness: attention",
    ] {
        assert!(
            stdout.contains(needle),
            "expected stdout to contain {needle:?}; got: {stdout}"
        );
    }
    assert!(
        !dir.path().join(".cordance").exists(),
        "status must be read-only and must not create .cordance"
    );
}

#[test]
fn cordance_explain_unknown_rule_exits_zero() {
    let dir = tempfile::tempdir().expect("tempdir");
    // Run pack first so that `.cordance/evidence-map.json` is on disk.
    let mut pack_cmd = Command::cargo_bin("cordance").expect("bin");
    pack_cmd
        .arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("pack")
        .arg("--output-mode")
        .arg("write");
    let _ = pack_cmd.output();

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("explain")
        .arg("nonexistent-rule-xyz-abc");
    cmd.assert().success();
}

#[test]
fn cordance_explain_finds_rule_after_pack() {
    let dir = tempfile::tempdir().expect("tempdir");
    // Run pack first to generate evidence-map.json.
    let mut pack_cmd = Command::cargo_bin("cordance").expect("bin");
    pack_cmd
        .arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("pack")
        .arg("--output-mode")
        .arg("write");
    let _ = pack_cmd.output(); // may fail in empty dir, that's fine.

    // explain should not panic regardless of whether the rule exists.
    let mut explain_cmd = Command::cargo_bin("cordance").expect("bin");
    explain_cmd
        .arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("explain")
        .arg("R-build-1");
    let _ = explain_cmd.output();
}

#[test]
fn cordance_cortex_push_dry_run_succeeds() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(".")
        .arg("cortex")
        .arg("push")
        .arg("--dry-run");
    cmd.assert().success();
}

#[test]
fn cortex_push_dry_run_writes_file_but_omits_handoff() {
    // BUILD_SPEC §6.6: dry-run must still persist the receipt JSON, but must
    // NOT print the operator-handoff line. The earlier inverted behaviour
    // (write only when `!dry_run`) is the regression this test guards
    // against.
    let dir = tempfile::tempdir().expect("tempdir");

    // Cortex push requires a pack first; pack from an empty tempdir is
    // best-effort because some required surfaces may be absent.
    let mut pack_cmd = Command::cargo_bin("cordance").expect("bin");
    pack_cmd
        .arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("pack")
        .arg("--output-mode")
        .arg("write");
    let _ = pack_cmd.output();

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("cortex")
        .arg("push")
        .arg("--dry-run");
    let output = cmd.output().expect("run cordance");
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("Cortex receipt:"),
        "expected receipt path in stdout; got: {stdout}"
    );
    assert!(
        !stdout.contains("To submit:"),
        "dry-run leaked the operator handoff text into stdout: {stdout}"
    );
    assert!(
        dir.path().join(".cordance/cortex-receipt.json").exists(),
        "dry-run failed to write the receipt file"
    );
}

#[test]
fn cortex_push_receipt_omits_pack_cortex_receipt_noop_warning() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(dir.path().join("doctrine-root")).expect("mkdir doctrine root");
    std::fs::write(
        dir.path().join("cordance.toml"),
        r#"
[doctrine]
source = "doctrine-root"
fallback_repo = "https://nonexistent.example.invalid/doctrine"
pin_commit = "auto"
"#,
    )
    .expect("write cordance.toml");

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("cortex")
        .arg("push")
        .arg("--dry-run");
    cmd.assert().success();

    let receipt_path = dir.path().join(".cordance/cortex-receipt.json");
    let receipt_json = std::fs::read_to_string(&receipt_path).expect("read receipt");
    let receipt: serde_json::Value = serde_json::from_str(&receipt_json).expect("parse receipt");
    let body = &receipt["cordance_execution_receipt_v1"];
    let forbidden = "cortex-receipt requested via --targets but pack emits no receipt";

    for field in ["allowed_claim_language", "residual_risk"] {
        let values = body[field]
            .as_array()
            .unwrap_or_else(|| panic!("{field} must be an array in {receipt_path:?}"));
        assert!(
            !values
                .iter()
                .any(|value| value.as_str().is_some_and(|text| text.contains(forbidden))),
            "{field} was polluted by pack CLI no-op warning: {values:?}"
        );
    }
}

#[test]
fn cortex_push_without_dry_run_prints_handoff() {
    // Inverse of the dry-run test: without `--dry-run` the handoff text must
    // appear AND the receipt file must exist.
    let dir = tempfile::tempdir().expect("tempdir");

    let mut pack_cmd = Command::cargo_bin("cordance").expect("bin");
    pack_cmd
        .arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("pack")
        .arg("--output-mode")
        .arg("write");
    let _ = pack_cmd.output();

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("cortex")
        .arg("push");
    let output = cmd.output().expect("run cordance");
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("Cortex receipt:"),
        "expected receipt path in stdout; got: {stdout}"
    );
    assert!(
        stdout.contains("To submit:"),
        "non-dry-run must print the operator handoff text; got: {stdout}"
    );
    assert!(
        dir.path().join(".cordance/cortex-receipt.json").exists(),
        "non-dry-run failed to write the receipt file"
    );
}

#[test]
fn cordance_pack_with_llm_none_works() {
    // `--llm none` must behave identically to no `--llm` flag: pack runs to
    // completion, no Ollama traffic, no `.cordance/llm-candidate.json` written.
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(".")
        .arg("pack")
        .arg("--output-mode")
        .arg("dry-run")
        .arg("--llm")
        .arg("none");
    cmd.assert().success();
}

#[test]
fn cordance_pack_llm_flag_accepts_ollama_model_override() {
    // The flag must parse and the dry-run must succeed even when an Ollama
    // model is named — if Ollama is unreachable the LLM block warns and
    // continues; the pack itself never fails.
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(".")
        .arg("pack")
        .arg("--output-mode")
        .arg("dry-run")
        .arg("--llm")
        .arg("none")
        .arg("--ollama-model")
        .arg("qwen2.5-coder:14b");
    cmd.assert().success();
}

/// Tests the "Ollama unavailable" path end-to-end. Ignored by default because
/// it depends on nothing listening on port 11434, which is not guaranteed on
/// every developer machine. Run with `cargo test -- --ignored`.
#[test]
#[ignore = "depends on port 11434 being free; run with --ignored locally"]
fn cordance_pack_with_llm_ollama_unavailable_warns_but_succeeds() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("pack")
        .arg("--output-mode")
        .arg("dry-run")
        .arg("--llm")
        .arg("ollama");
    cmd.assert().success();
}

#[test]
fn cli_rejects_target_outside_cwd() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    // Use a path that exists but is above cwd — e.g. system root.
    let outside = if cfg!(windows) { "C:\\" } else { "/" };
    cmd.arg("--target").arg(outside).arg("scan");
    cmd.assert()
        .failure()
        .stderr(predicates::str::contains("outside"));
}

#[test]
fn cli_accepts_target_inside_cwd() {
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(".").arg("scan").arg("--json");
    cmd.assert().success();
}

#[test]
fn cli_allow_outside_cwd_overrides_guard() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(tmp.path())
        .arg("--allow-outside-cwd")
        .arg("scan")
        .arg("--json");
    cmd.assert().success();
}

/// Round-3 bughunt #1: a relative symlink whose target uses `..` segments to
/// escape the temp directory must be rejected by the CLI's path guard. The
/// earlier guard relied on `Path::starts_with`, a syntactic prefix check —
/// so a target like `<tempdir>/trap` pointing at `../../../etc/passwd` slipped
/// through (the joined path still LOOKED like it started with the cwd, even
/// though `..` segments meant it didn't end there).
#[test]
#[cfg(unix)]
fn cli_rejects_relative_symlink_escaping_cwd() {
    use std::os::unix::fs::symlink;
    let dir = tempfile::tempdir().expect("tempdir");
    let link = dir.path().join("trap");
    // Relative target with enough `..` to escape the tempdir on any reasonable
    // path depth. Target is intentionally non-existent: the validator must
    // still reject without dereferencing.
    symlink(
        "../../../../../../../../../../../etc/passwd-nonexistent",
        &link,
    )
    .expect("symlink");

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target").arg(&link).arg("scan").arg("--json");
    cmd.assert()
        .failure()
        .stderr(predicates::str::contains("symlink").or(predicates::str::contains("outside")));
}

/// Round-3 redteam #2: the production `pack` path now flows through
/// `load_doctrine_with_fallback`, not the legacy `load_doctrine_or_default`.
/// We can't easily simulate a fallback clone from a unit test without network
/// access, but we can exercise the failure-on-doctrine path: when the doctrine
/// sibling is absent AND the fallback URL is unreachable, `pack` must still
/// succeed (the loader is non-fatal) and must record the doctrine load
/// failure on the `residual_risk` audit trail.
///
/// This test runs `pack` in `dry-run` mode in an empty tempdir with the
/// doctrine source pointed at a non-existent path. The fallback URL is set
/// to a syntactically valid but unresolvable hostname so the fallback fails
/// deterministically without making it past DNS.
#[test]
fn pack_uses_hardened_doctrine_loader_and_records_failure() {
    let dir = tempfile::tempdir().expect("tempdir");
    // Point doctrine at a path that won't exist, and configure a fallback URL
    // that will be rejected/unreachable so the hardened loader's failure path
    // is what we observe. We use a TLD that doesn't resolve so this test
    // does not depend on network policy.
    std::fs::write(
        dir.path().join("cordance.toml"),
        r#"
[doctrine]
source = "definitely-does-not-exist-engineering-doctrine"
fallback_repo = "https://nonexistent.example.invalid/doctrine"
pin_commit = "auto"
"#,
    )
    .expect("write cordance.toml");

    let mut cmd = Command::cargo_bin("cordance").expect("bin");
    cmd.arg("--target")
        .arg(dir.path())
        .arg("--allow-outside-cwd")
        .arg("pack")
        .arg("--output-mode")
        .arg("write");
    // The pack itself must succeed (doctrine failure is non-fatal), and the
    // resulting pack.json should land in `.cordance/`.
    cmd.assert().success();

    let pack_path = dir.path().join(".cordance/pack.json");
    assert!(
        pack_path.exists(),
        "pack.json was not written; hardened doctrine loader may have aborted"
    );
    let pack_json = std::fs::read_to_string(&pack_path).expect("read pack.json");
    // The residual_risk audit trail must show the doctrine load failure
    // produced by `load_doctrine_with_fallback`. Without that signal, a
    // future regression that silently swallows the failure would land
    // unnoticed.
    assert!(
        pack_json.contains("doctrine load failed"),
        "residual_risk did not record the doctrine load failure (pack.json snippet: {})",
        &pack_json[..pack_json.len().min(1024)]
    );
}