sysknife-cli 0.29.0

Approval-gated AI system administration CLI and MCP server
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! T1 — end-to-end smoke tests for the `sysknife` binary via `assert_cmd`.
//!
//! Before this batch, the binary had **zero** integration tests — every
//! argparse change, every `main.rs` wiring tweak, every stdout/stderr
//! stream confusion shipped undetected and surfaced as production bugs.
//! These tests boot the actual compiled binary (no mocking, no library
//! short-circuit) and exercise the failure surfaces a user is most
//! likely to hit:
//!
//!   1. `--help` returns 0 and prints something that mentions every
//!      top-level subcommand.
//!   2. `doctor` against an unreachable daemon returns non-zero and
//!      writes the failure to stderr while leaving stdout empty; with
//!      `--json` the failure envelope goes to stdout instead, because
//!      that is what automation parses.
//!   3. `history --since "not-a-timestamp"` returns non-zero with a
//!      clear error rather than panicking.
//!   4. Unknown subcommands surface as clap usage errors.
//!
//! All tests set `SYSKNIFE_SOCKET` to a non-existent absolute path so
//! the daemon-touching commands fail fast with a connection error
//! instead of trying the production `/run/sysknife/daemon.sock`.

use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;
use std::sync::Arc;
use sysknife_daemon::audit_chain::{AuditKey, ChainRow};
use sysknife_daemon::auth::CallerPrincipal;
use sysknife_daemon::transactions::{NewTransaction, TransactionStore};
use sysknife_types::{CallerRole, RiskLevel};

/// Path the CLI tries to connect to in tests — points at a directory we
/// own so the failure mode is "ENOENT" rather than "ECONNREFUSED on a
/// stale socket".
fn fake_socket(dir: &tempfile::TempDir) -> std::path::PathBuf {
    dir.path().join("does-not-exist.sock")
}

fn cli() -> Command {
    Command::cargo_bin("sysknife").expect("sysknife binary builds")
}

#[test]
fn help_lists_every_top_level_subcommand() {
    let output = cli()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("doctor"))
        .stdout(predicate::str::contains("history"))
        .stdout(predicate::str::contains("audit"))
        .stdout(predicate::str::contains("mcp-server"))
        .stdout(predicate::str::contains("completions"))
        .stdout(predicate::str::contains("daemon work may continue"));
    drop(output);
}

#[test]
fn unknown_subcommand_via_clap_usage_error() {
    // clap's external-subcommand mechanism turns any unknown first arg
    // into the free-form intent, so `sysknife nonsense-command` goes
    // through the planning path. To force a clap error we use an
    // unknown FLAG instead.
    cli()
        .arg("--no-such-flag")
        .assert()
        .code(2)
        .stderr(predicate::str::contains("unexpected").or(predicate::str::contains("unknown")));
}

#[test]
fn doctor_fails_loudly_when_daemon_socket_is_unreachable() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .arg("doctor")
        .assert()
        .failure()
        // The stream matters: automation parses stdout for the `--json` form,
        // so a diagnostic that leaks onto stdout corrupts it. Assert the
        // failure text lands on stderr and that stdout stays clean.
        .stderr(predicate::str::contains("daemon"))
        .stdout(predicate::str::is_empty());
}

#[test]
fn doctor_json_failure_goes_to_stdout_not_stderr() {
    // The counterpart contract: with `--json`, the machine-readable failure
    // envelope belongs on stdout so automation can parse it. Without this,
    // nothing pins which stream carries which form.
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .args(["doctor", "--json"])
        .assert()
        .failure()
        .stdout(predicate::str::contains("\"ok\":false"));
}

#[test]
fn history_rejects_unparseable_since_timestamp() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .arg("history")
        .arg("--since")
        .arg("not-a-timestamp")
        .assert()
        // The specific code is the contract, not merely "non-zero": a bad
        // `--since` is a config/usage error (4), and automation distinguishes
        // that from an execution failure (2) or a rejected plan (1).
        .code(4);
}

#[test]
fn audit_verify_exits_with_code_2_when_the_key_file_is_missing() {
    // `run_audit_verify` documents 0 = intact, 1 = tampered, 2 = could not
    // verify, and warns that "a CI pipeline expecting 0 or 1 must not
    // silently pass on a missing key file". Nothing pinned that: the only
    // exit-code coverage was `error.rs`'s pure mapping test, which cannot
    // catch the binary collapsing 2 into 0 or 1.
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("XDG_DATA_HOME", dir.path())
        .env("HOME", dir.path())
        .args(["audit", "verify", "--pubkey"])
        .arg(dir.path().join("no-such-key.pub"))
        .assert()
        .code(2);
}

fn audit_fixture_cli(dir: &tempfile::TempDir) -> Command {
    let mut command = cli();
    command
        .env("SYSKNIFE_SOCKET", fake_socket(dir))
        .env("SYSKNIFE_DATABASE_PATH", dir.path().join("daemon.sqlite"))
        .env_remove("SYSKNIFE_CHECKPOINT_DB")
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path())
        .env("XDG_DATA_HOME", dir.path())
        .args(["audit", "verify", "--pubkey"])
        .arg(dir.path().join("audit-key.pub"));
    command
}

fn assert_empty_unanchored_store_is_inconclusive(dir: &tempfile::TempDir) {
    for json in [false, true] {
        let mut command = audit_fixture_cli(dir);
        if json {
            command.arg("--json");
        }
        let output = command.output().expect("run audit verify on empty store");
        assert_eq!(
            output.status.code(),
            Some(2),
            "json={json}; stdout: {}; stderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        if json {
            let report: serde_json::Value =
                serde_json::from_slice(&output.stdout).expect("one JSON report");
            assert_eq!(report["status"], "cannot_verify");
            assert_eq!(report["chain"]["rows_checked"], 0);
            assert_eq!(report["approval_events"]["rows_checked"], 0);
            assert_eq!(report["rows_censused"], 0);
            assert_eq!(report["audit_anchor"]["configured"], false);
        } else {
            let text = String::from_utf8_lossy(&output.stdout);
            assert!(text.starts_with("CANNOT VERIFY:"), "{text}");
            assert!(text.contains("empty"), "{text}");
            assert!(!text.starts_with("OK:"), "{text}");
        }
    }
}

#[test]
fn audit_verify_fresh_empty_unanchored_store_is_inconclusive() {
    let dir = tempfile::tempdir().expect("create audit fixture");
    let key =
        AuditKey::load_or_generate(&dir.path().join("audit-key")).expect("generate audit key");
    let store = TransactionStore::open_with_key(dir.path().join("daemon.sqlite"), Arc::new(key))
        .expect("create fresh empty store");
    assert!(store.fetch_chain_rows().unwrap().is_empty());
    assert!(store.fetch_event_rows().unwrap().is_empty());
    drop(store);
    assert_empty_unanchored_store_is_inconclusive(&dir);
}

#[test]
fn audit_verify_erased_recreated_empty_unanchored_store_is_inconclusive() {
    let dir = tempfile::tempdir().expect("create audit fixture");
    let db_path = dir.path().join("daemon.sqlite");
    let key = AuditKey::load_or_generate(&dir.path().join("audit-key"))
        .expect("generate retained audit key");
    let store = TransactionStore::open_with_key(&db_path, Arc::new(key.clone()))
        .expect("create populated audit store");
    store
        .record(NewTransaction {
            request_id: "erased-store".to_string(),
            request_hash: "erased-store-hash".to_string(),
            action_name: "UpdateSystem".to_string(),
            risk_level: RiskLevel::High,
            summary: "Synthetic audit fixture; no action is executed".to_string(),
            warnings: vec![],
            caller_role: CallerRole::Dev,
            caller_principal: CallerPrincipal::Uid(1000),
        })
        .expect("record signed fixture row");
    assert_eq!(store.fetch_chain_rows().unwrap().len(), 1);
    drop(store);
    let output = audit_fixture_cli(&dir).arg("--json").output().unwrap();
    assert_eq!(output.status.code(), Some(0));
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(report["status"], "intact");
    assert_eq!(report["chain"]["rows_checked"], 1);

    // Erase this test's database, retaining the same public/private key pair.
    // The readable replacement is indistinguishable from a fresh empty store.
    std::fs::remove_file(&db_path).expect("erase isolated fixture database");
    let store = TransactionStore::open_with_key(&db_path, Arc::new(key))
        .expect("recreate readable empty store");
    assert!(store.fetch_chain_rows().unwrap().is_empty());
    assert!(store.fetch_event_rows().unwrap().is_empty());
    drop(store);
    assert_empty_unanchored_store_is_inconclusive(&dir);
}

#[test]
fn audit_verify_exit_code_prefers_broken_chain_to_inconclusive_anchor() {
    let dir = tempfile::tempdir().expect("create CLI fixture directory");
    let db_path = dir.path().join("daemon.sqlite");
    let key =
        AuditKey::load_or_generate(&dir.path().join("audit-key")).expect("generate audit key");
    let store = TransactionStore::open_with_key(&db_path, Arc::new(key.clone()))
        .expect("create audit store");
    store
        .record(NewTransaction {
            request_id: "broken-chain-exit-code".to_string(),
            request_hash: "broken-chain-exit-code-hash".to_string(),
            action_name: "UpdateSystem".to_string(),
            risk_level: RiskLevel::High,
            summary: "Upgrade the system".to_string(),
            warnings: vec![],
            caller_role: CallerRole::Dev,
            caller_principal: CallerPrincipal::Uid(1000),
        })
        .expect("record audit row");
    drop(store);

    let wrong_key_path = dir.path().join("wrong-audit-key");
    let wrong_key = AuditKey::load_or_generate(&wrong_key_path).expect("generate mismatched key");
    assert_ne!(key.verifying_key_hex(), wrong_key.verifying_key_hex());

    cli()
        .env("SYSKNIFE_DATABASE_PATH", &db_path)
        .env("SYSKNIFE_CHECKPOINT_DB", "not-a-postgres-url")
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path())
        .args(["audit", "verify", "--pubkey"])
        .arg(dir.path().join("wrong-audit-key.pub"))
        .assert()
        // The wrong public key makes the local chain Broken (1), while the
        // unusable configured anchor is CannotVerify (2). A break must win.
        .code(1);
}

#[tokio::test]
#[ignore = "live Postgres; set SYSKNIFE_TEST_POSTGRES_URL and run with --ignored"]
async fn audit_verify_exits_with_code_1_when_anchor_is_truncated() {
    use sqlx_postgres::{PgConnectOptions, PgPoolOptions};
    use std::str::FromStr;
    use sysknife_daemon::audit_chain::resolve_audit_key_path;
    use sysknife_daemon::checkpoint_sink::{CheckpointSink, PostgresCheckpointSink};

    let required = std::env::var_os("SYSKNIFE_REQUIRE_POSTGRES").is_some();
    let url = std::env::var("SYSKNIFE_TEST_POSTGRES_URL")
        .ok()
        .filter(|url| !url.is_empty());
    let Some(url) = url else {
        assert!(
            !required,
            "SYSKNIFE_REQUIRE_POSTGRES is set but SYSKNIFE_TEST_POSTGRES_URL is unset"
        );
        return;
    };
    assert!(
        url.contains("sysknife_test"),
        "refusing destructive integration test against a non-test database"
    );

    const SCHEMA: &str = "cli_smoke_anchor_exit";
    let admin = PgPoolOptions::new()
        .max_connections(1)
        .connect_with(PgConnectOptions::from_str(&url).expect("valid test URL"))
        .await
        .expect("connect for schema setup");
    for statement in [
        format!("DROP SCHEMA IF EXISTS {SCHEMA} CASCADE"),
        format!("CREATE SCHEMA {SCHEMA}"),
    ] {
        sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(statement))
            .execute(&admin)
            .await
            .expect("prepare isolated schema");
    }
    let separator = if url.contains('?') { '&' } else { '?' };
    let scoped_url = format!("{url}{separator}options=-csearch_path%3D{SCHEMA}");

    let dir = tempfile::tempdir().expect("create CLI fixture directory");
    let db_path = dir.path().join("daemon.sqlite");
    let key =
        AuditKey::load_or_generate(&resolve_audit_key_path(&db_path)).expect("generate audit key");
    let store = TransactionStore::open_with_key(&db_path, Arc::new(key.clone()))
        .expect("create audit store");
    store
        .record(NewTransaction {
            request_id: "anchor-exit-code".to_string(),
            request_hash: "anchor-exit-code-hash".to_string(),
            action_name: "UpdateSystem".to_string(),
            risk_level: RiskLevel::High,
            summary: "Upgrade the system".to_string(),
            warnings: vec![],
            caller_role: CallerRole::Dev,
            caller_principal: CallerPrincipal::Uid(1000),
        })
        .expect("record intact local chain");
    drop(store);

    let sink = PostgresCheckpointSink::connect(&scoped_url)
        .await
        .expect("connect checkpoint sink");
    sink.append(&key.sign_checkpoint(2, "anchored-tip-beyond-local-chain", "2026-09-02T12:00:00Z"))
        .await
        .expect("store checkpoint beyond the local tip");
    drop(sink);

    let output = cli()
        .env("SYSKNIFE_DATABASE_PATH", &db_path)
        .env("SYSKNIFE_CHECKPOINT_DB", &scoped_url)
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path())
        .args(["audit", "verify", "--json"])
        .output()
        .expect("run audit verify");

    sqlx_core::query::query(sqlx_core::sql_str::AssertSqlSafe(format!(
        "DROP SCHEMA {SCHEMA} CASCADE"
    )))
    .execute(&admin)
    .await
    .expect("drop isolated schema");

    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let doc: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("--json emits one document");
    assert_eq!(
        doc["status"],
        "broken",
        "the --json verdict must reflect the anchor: {}",
        String::from_utf8_lossy(&output.stdout)
    );
}

#[test]
fn audit_export_emits_the_stored_rows_as_parseable_json() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("daemon.sqlite");
    let key = Arc::new(AuditKey::load_or_generate(&dir.path().join("audit-key")).unwrap());
    let store = TransactionStore::open_with_key(&db_path, key).unwrap();
    for request_id in ["req-1", "req-2"] {
        store
            .record(NewTransaction {
                request_id: request_id.to_string(),
                request_hash: format!("hash-{request_id}"),
                action_name: "UpdateSystem".to_string(),
                risk_level: RiskLevel::High,
                summary: "Upgrade the system".to_string(),
                warnings: vec![],
                caller_role: CallerRole::Dev,
                caller_principal: CallerPrincipal::Uid(1000),
            })
            .unwrap();
    }
    let stored = store.fetch_chain_rows().unwrap();
    drop(store);

    let output = cli()
        .env("SYSKNIFE_DATABASE_PATH", &db_path)
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path())
        .args(["audit", "export", "--limit", "1"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let exported: Vec<ChainRow> = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(exported.len(), 1);
    assert_eq!(exported[0], stored[0]);
    assert_eq!(
        exported[0].chain_hash.as_bytes(),
        stored[0].chain_hash.as_bytes()
    );
}

#[test]
fn audit_export_rejects_an_invalid_since_timestamp() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_DATABASE_PATH", dir.path().join("unused.sqlite"))
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path())
        .args(["audit", "export", "--since", "not-a-timestamp"])
        .assert()
        .code(4)
        .stderr(predicate::str::contains("--since"));
}

/// Missing checkpoint configuration has the same exit code as invalid audit
/// export configuration, before any key, database, or daemon is consulted.
#[test]
fn audit_checkpoint_without_a_database_is_a_configuration_error() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env_clear()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("XDG_CONFIG_HOME", dir.path())
        .env("XDG_DATA_HOME", dir.path())
        .env("HOME", dir.path())
        .args(["audit", "checkpoint"])
        .assert()
        .code(4)
        .stderr(predicate::str::contains("config/daemon error"))
        .stderr(predicate::str::contains(
            "no checkpoint database configured",
        ))
        .stdout(predicate::str::is_empty());

    // Once an external checkpoint database is configured, checkpointing must
    // read the same selected audit store as verify/export before connecting to
    // the sink. The deliberately invalid sink URL lets the test distinguish a
    // local-store lookup failure from reaching the external connection step.
    let db_path = dir.path().join("system-daemon.sqlite");
    let key_path = sysknife_daemon::audit_chain::resolve_audit_key_path(&db_path);
    let key = AuditKey::load_or_generate(&key_path).expect("create selected audit key");
    drop(
        TransactionStore::open_with_key(&db_path, Arc::new(key))
            .expect("create selected audit database"),
    );
    cli()
        .env_clear()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("SYSKNIFE_DATABASE_PATH", &db_path)
        .env("SYSKNIFE_CHECKPOINT_DB", "not-a-postgres-url")
        .env("XDG_CONFIG_HOME", dir.path())
        .env("XDG_DATA_HOME", dir.path())
        .env("HOME", dir.path())
        .args(["audit", "checkpoint"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "connecting to checkpoint database failed",
        ));
}

/// An empty intent fails inside the planner before any provider request, so
/// this pins the real process's planning-failure exit without an LLM service.
#[test]
fn a_blank_intent_returns_the_planning_failure_exit_code() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env_clear()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("XDG_CONFIG_HOME", dir.path())
        .env("XDG_DATA_HOME", dir.path())
        .env("HOME", dir.path())
        .env("SYSKNIFE_LLM_PROVIDER", "ollama")
        .env("SYSKNIFE_LLM_MODEL", "test-model")
        .args(["--dry-run", " "])
        .assert()
        .code(3)
        .stderr(predicate::str::contains("planning failed"))
        .stdout(predicate::str::is_empty());
}

/// A listening TCP socket completes the local provider's connection but never
/// returns an HTTP response. No real provider or daemon can be contacted.
#[test]
fn a_planning_timeout_does_not_claim_an_execution_failure() {
    let dir = tempfile::tempdir().unwrap();
    let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
    listener.set_nonblocking(true).unwrap();
    let provider_url = format!("http://{}", listener.local_addr().unwrap());
    let (accepted_tx, accepted_rx) = std::sync::mpsc::channel();
    let (stop_tx, stop_rx) = std::sync::mpsc::channel();
    let accept_thread = std::thread::spawn(move || {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
        loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    accepted_tx
                        .send(Ok(stream))
                        .expect("send accepted provider connection");
                    return;
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    if stop_rx.try_recv().is_ok() {
                        return;
                    }
                    if std::time::Instant::now() >= deadline {
                        let _ = accepted_tx.send(Err(
                            "the CLI did not reach the local provider before the test deadline"
                                .to_string(),
                        ));
                        return;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
                Err(error) => {
                    let _ = accepted_tx.send(Err(error.to_string()));
                    return;
                }
            }
        }
    });

    let mut command = assert_cmd::Command::cargo_bin("sysknife").expect("sysknife binary builds");
    command
        .timeout(std::time::Duration::from_secs(10))
        .env_clear()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("XDG_CONFIG_HOME", dir.path())
        .env("XDG_DATA_HOME", dir.path())
        .env("HOME", dir.path())
        .env("SYSKNIFE_LLM_PROVIDER", "ollama")
        .env("SYSKNIFE_LLM_MODEL", "test-model")
        .env("SYSKNIFE_OLLAMA_URL", provider_url)
        .args(["--dry-run", "--json", "--timeout", "5", "check disk usage"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("operation timed out after 5s"))
        .stderr(predicate::str::contains("execution failed").not())
        .stdout(predicate::str::is_empty());

    let provider_connection = match accepted_rx.recv_timeout(std::time::Duration::from_secs(3)) {
        Ok(Ok(stream)) => stream,
        Ok(Err(error)) => {
            let _ = stop_tx.send(());
            accept_thread
                .join()
                .expect("provider listener thread should exit");
            panic!("the CLI did not reach the local provider: {error}");
        }
        Err(error) => {
            let _ = stop_tx.send(());
            accept_thread
                .join()
                .expect("provider listener thread should exit");
            panic!("the CLI did not reach the local provider: {error}");
        }
    };
    accept_thread
        .join()
        .expect("provider listener thread should exit");
    drop(provider_connection);
}

#[test]
fn completions_subcommand_emits_a_shell_script() {
    cli()
        .arg("completions")
        .arg("bash")
        .assert()
        .success()
        // Bash completion scripts always start with `#!/usr/bin/env`
        // or define a `_sysknife` function — either is fine.
        .stdout(predicate::str::contains("_sysknife").or(predicate::str::starts_with("#")));
}

/// `--timeout` is the only bound on a scripted invocation that would
/// otherwise hang, and nothing exercised it.
///
/// The daemon has to *accept and then stay silent*: an unreachable socket
/// fails fast for an unrelated reason and would prove nothing about the
/// timeout. The listener thread is deliberately detached — joining it would
/// block the test forever, since it has no reason to stop accepting.
#[test]
fn timeout_flag_bounds_a_daemon_that_accepts_but_never_replies() {
    use std::os::unix::net::UnixListener;

    let dir = tempfile::tempdir().unwrap();
    let socket_path = dir.path().join("silent.sock");
    let listener = UnixListener::bind(&socket_path).expect("bind test socket");

    std::thread::spawn(move || {
        let mut held = Vec::new();
        while let Ok((stream, _)) = listener.accept() {
            // Hold the connection open and never write a reply.
            held.push(stream);
        }
    });

    let started = std::time::Instant::now();
    cli()
        .env("SYSKNIFE_SOCKET", &socket_path)
        .args(["--timeout", "1", "doctor"])
        .assert()
        // A command timeout keeps exit 2 but must not claim an action ran.
        .code(2)
        .stderr(predicate::str::contains("operation timed out after 1s"))
        .stderr(predicate::str::contains("execution failed").not());

    let elapsed = started.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(30),
        "--timeout 1 must give up promptly against a silent daemon, took {elapsed:?}"
    );
}

/// `audit export` must give the same diagnosis as `audit verify` when the store
/// exists but cannot be read.
///
/// `Path::exists()` answers false for both ENOENT and EACCES, so probing with
/// it told an operator the root-owned 0700 system store did not exist and to
/// start the daemon, while the daemon was running and the fix was sudo. Export
/// was written without the `path_is_present` call that verify has carried since
/// #275.
///
/// Skipped as root, which stats straight through mode 000; the assertion on the
/// captured precondition is what turns that into a skip rather than a false
/// pass.
#[test]
#[cfg(unix)]
fn audit_export_distinguishes_unreadable_from_absent() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let store_dir = dir.path().join("state");
    std::fs::create_dir_all(&store_dir).unwrap();
    let db = store_dir.join("daemon.sqlite");
    std::fs::write(&db, b"not really a database").unwrap();
    std::fs::set_permissions(&store_dir, std::fs::Permissions::from_mode(0o000)).unwrap();

    // Capture the probe on this side of the restore. A test that chmods back
    // first and then probes reads the restored state and proves nothing.
    let unreadable = std::fs::metadata(&db).is_err();

    let assertion = if unreadable {
        Some(
            cli()
                .env("SYSKNIFE_DATABASE_PATH", &db)
                .env("SYSKNIFE_SOCKET", fake_socket(&dir))
                .args(["audit", "export"])
                .assert()
                .failure(),
        )
    } else {
        None
    };

    std::fs::set_permissions(&store_dir, std::fs::Permissions::from_mode(0o755)).unwrap();

    match assertion {
        Some(a) => {
            a.stderr(
                predicate::str::contains("not readable")
                    .or(predicate::str::contains("Permission denied")),
            );
        }
        None => {
            // Running as root, so mode 000 is not a barrier and there is
            // nothing to assert. Say so rather than passing quietly.
            eprintln!("skipped: this user stats through mode 000 (probably root)");
        }
    }
}
// ---------------------------------------------------------------------------
// --dangerously-skip-approval: the two-key rule, exercised on the real binary
// ---------------------------------------------------------------------------

/// The flag on its own must stop the run and explain the second key.
///
/// Driven through the compiled binary rather than the pure resolver, because
/// the property under test is that `dispatch` refuses *before* reaching a
/// subcommand. A unit test on `UnattendedConsent` would still pass if that
/// wiring were dropped.
#[test]
fn the_skip_approval_flag_alone_refuses_and_names_the_second_key() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env_remove("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT")
        .args(["--dangerously-skip-approval", "doctor"])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT")
                .and(predicate::str::contains("as root")),
        );
}

/// A value that is not exactly `1` must not satisfy the environment half. A
/// profile carrying `=0` or `=false` is the accident this guards against.
#[test]
fn a_non_exact_consent_value_does_not_arm_the_flag() {
    let dir = tempfile::tempdir().unwrap();
    for value in ["0", "false", "true", "yes", ""] {
        cli()
            .env("SYSKNIFE_SOCKET", fake_socket(&dir))
            .env("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT", value)
            .args(["--dangerously-skip-approval", "doctor"])
            .assert()
            .failure()
            .stderr(predicate::str::contains(
                "SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT",
            ));
    }
}

/// With both keys the refusal is gone and the banner is on stderr. The command
/// still fails, because the socket does not exist, and that is the point: the
/// run proceeded past the consent gate and failed for its own reason.
#[test]
fn both_keys_print_the_banner_and_let_the_command_run() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT", "1")
        .args(["--dangerously-skip-approval", "doctor"])
        .assert()
        .stderr(
            predicate::str::contains("UNATTENDED MODE")
                .and(predicate::str::contains("approval gate is OFF"))
                .and(predicate::str::contains("polkit allowlist"))
                .and(predicate::str::contains("is not set to").not()),
        );
}

/// The environment variable on its own changes nothing. An operator who exports
/// it in a profile and forgets has not armed anything.
#[test]
fn the_consent_variable_alone_is_inert() {
    let dir = tempfile::tempdir().unwrap();
    cli()
        .env("SYSKNIFE_SOCKET", fake_socket(&dir))
        .env("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT", "1")
        .args(["doctor"])
        .assert()
        .stderr(predicate::str::contains("UNATTENDED MODE").not());
}

/// `--help` has to carry the warning too. The flag is discovered there, and a
/// help entry that reads like an ordinary option teaches the wrong thing.
#[test]
fn help_says_what_the_skip_approval_flag_does_and_does_not_do() {
    cli()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("--dangerously-skip-approval"));

    cli().arg("--help").assert().success().stdout(
        predicate::str::contains("SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT")
            .or(predicate::str::contains("Requires")),
    );
}