kintsugi 0.1.0

Kintsugi — a local-first safety layer for AI coding agents. Installs all binaries: kintsugi, kintsugi-daemon, kintsugi-hook, kintsugi-shim, kintsugi-exec.
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
//! P0.7 acceptance: `kintsugi log` shows recorded events, `kintsugi status` reports the
//! log, and `kintsugi init` wires interception. Unix-only for the symlink checks.
#![cfg(unix)]

use std::process::Command;

use kintsugi_core::{Class, Decision, EventLog, ProposedCommand, Verdict};

fn kintsugi() -> Command {
    Command::new(env!("CARGO_BIN_EXE_kintsugi"))
}

fn seed_log(db: &std::path::Path) {
    let log = EventLog::open(db).unwrap();
    let a = ProposedCommand::new("claude-code", "/tmp", vec!["ls".into()], "ls");
    log.log_event(&a, &Verdict::rules(Class::Safe, Decision::Allow, "t"), None)
        .unwrap();
    let b = ProposedCommand::new(
        "shim",
        "/tmp",
        vec!["rm".into(), "-rf".into()],
        "rm -rf data",
    );
    log.log_event(
        &b,
        &Verdict::rules(Class::Catastrophic, Decision::Hold, "t"),
        None,
    )
    .unwrap();
}

#[test]
fn undo_with_nothing_says_so() {
    let tmp = tempfile::tempdir().unwrap();
    let out = kintsugi()
        .arg("undo")
        .env("KINTSUGI_DB", tmp.path().join("events.db"))
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("Nothing to undo"));
}

#[test]
fn undo_restores_a_snapshotted_file() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    let snaps = tmp.path().join("snapshots");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    let file = work.join("data.txt");
    std::fs::write(&file, b"original").unwrap();

    // Seed a snapshot the same way the daemon would, then corrupt the file.
    {
        let log = EventLog::open(&db).unwrap();
        let cmd = ProposedCommand::new(
            "shim",
            &work,
            vec!["rm".into(), "data.txt".into()],
            "rm data.txt",
        );
        let manifest = kintsugi_core::capture_snapshot(&snaps, &cmd)
            .unwrap()
            .unwrap();
        log.record_snapshot(&manifest).unwrap();
    }
    std::fs::write(&file, b"corrupted").unwrap();

    let out = kintsugi()
        .arg("undo")
        .env("KINTSUGI_DB", &db)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "undo failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(String::from_utf8_lossy(&out.stdout).contains("undid"));
    assert_eq!(
        std::fs::read(&file).unwrap(),
        b"original",
        "file should be restored"
    );

    // Second undo finds nothing (snapshot marked reverted).
    let out2 = kintsugi()
        .arg("undo")
        .env("KINTSUGI_DB", &db)
        .output()
        .unwrap();
    assert!(String::from_utf8_lossy(&out2.stdout).contains("Nothing to undo"));
}

#[test]
fn queue_without_daemon_is_graceful() {
    let tmp = tempfile::tempdir().unwrap();
    let out = kintsugi()
        .arg("queue")
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .env("KINTSUGI_DB", tmp.path().join("e.db"))
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("isn't running"));
}

#[test]
fn run_without_daemon_errors() {
    let tmp = tempfile::tempdir().unwrap();
    // No daemon → `kintsugi run` should fail cleanly (non-zero), not panic.
    let out = kintsugi()
        .args(["run", "abc"])
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .env("KINTSUGI_DB", tmp.path().join("e.db"))
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("daemon"));
}

#[test]
fn approve_unknown_prefix_errors() {
    let tmp = tempfile::tempdir().unwrap();
    // No daemon → the command should fail cleanly (non-zero), not panic.
    let out = kintsugi()
        .args(["approve", "abc"])
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .env("KINTSUGI_DB", tmp.path().join("e.db"))
        .output()
        .unwrap();
    assert!(!out.status.success());
}

#[test]
fn panic_engages_and_resume_clears_kill_switch() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    let common = |c: &mut Command| {
        c.env("KINTSUGI_DB", &db)
            .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
            .env("NO_COLOR", "1");
    };

    let mut p = kintsugi();
    p.arg("panic");
    common(&mut p);
    let out = p.output().unwrap();
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("ENGAGED"));
    assert!(tmp.path().join("panic.flag").exists());

    // status reflects it.
    let mut s = kintsugi();
    s.arg("status");
    common(&mut s);
    let st = s.output().unwrap();
    assert!(String::from_utf8_lossy(&st.stdout).contains("KILL-SWITCH"));

    let mut r = kintsugi();
    r.arg("resume");
    common(&mut r);
    let out = r.output().unwrap();
    assert!(out.status.success());
    assert!(!tmp.path().join("panic.flag").exists());
}

#[test]
fn init_print_path_emits_export_line() {
    let tmp = tempfile::tempdir().unwrap();
    let out = kintsugi()
        .args(["init", "--print-path"])
        .env("KINTSUGI_DATA_DIR", tmp.path().join("data"))
        .output()
        .unwrap();
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("export PATH="));
    assert!(text.contains("shims"));
}

#[test]
fn init_tailors_guidance_by_profile() {
    // Personal (default) posture: focused safety-net guidance, no admin machinery.
    let tmp = tempfile::tempdir().unwrap();
    let personal = kintsugi()
        .args(["init", "--no-daemon"])
        .env("HOME", tmp.path())
        .env("KINTSUGI_DATA_DIR", tmp.path().join("data"))
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .output()
        .unwrap();
    assert!(personal.status.success());
    let p = String::from_utf8_lossy(&personal.stdout);
    assert!(p.contains("You're protected"), "personal guidance: {p}");
    assert!(
        p.contains("--enterprise"),
        "should hint the enterprise posture"
    );
    assert!(
        !p.contains("admin provision"),
        "personal must not push admin steps"
    );

    // Enterprise posture: the managed-control next steps.
    let tmp2 = tempfile::tempdir().unwrap();
    let ent = kintsugi()
        .args(["init", "--no-daemon", "--enterprise"])
        .env("HOME", tmp2.path())
        .env("KINTSUGI_DATA_DIR", tmp2.path().join("data"))
        .env("KINTSUGI_SOCKET", tmp2.path().join("none.sock"))
        .output()
        .unwrap();
    assert!(ent.status.success());
    let e = String::from_utf8_lossy(&ent.stdout);
    assert!(e.contains("Enterprise setup"), "enterprise guidance: {e}");
    assert!(e.contains("admin provision"));
    assert!(e.contains("service install"));
    assert!(e.contains("record install"));
}

#[test]
fn bare_invocation_prints_banner() {
    let tmp = tempfile::tempdir().unwrap();
    // Point at a dead socket + clean data dir so the banner deterministically
    // reports "not running" and suggests `kintsugi init`.
    let out = kintsugi()
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .env("KINTSUGI_DB", tmp.path().join("events.db"))
        .env("KINTSUGI_DATA_DIR", tmp.path())
        .output()
        .unwrap();
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("local-first"));
    assert!(text.contains("not running"));
    assert!(text.contains("kintsugi init"));
}

#[test]
fn log_respects_number_flag() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    seed_log(&db);
    let out = kintsugi()
        .args(["log", "-n", "1"])
        .env("KINTSUGI_DB", &db)
        .env("NO_COLOR", "1")
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    // Page 1 (newest first) shows only the most recent (rm -rf data).
    assert!(text.contains("rm -rf data"));
    // Footer reflects the total and links to the older page.
    assert!(text.contains("of 2"), "footer should show total:\n{text}");
    assert!(
        text.contains("--page 2"),
        "footer should link older page:\n{text}"
    );
}

#[test]
fn log_pagination_shows_older_page() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    seed_log(&db); // 2 events: ls (older), rm -rf data (newer)
    let out = kintsugi()
        .args(["log", "-n", "1", "--page", "2"])
        .env("KINTSUGI_DB", &db)
        .env("NO_COLOR", "1")
        .output()
        .unwrap();
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    // Page 2 is the older event (ls), not the newest.
    assert!(
        text.contains("ls"),
        "page 2 should show the older ls:\n{text}"
    );
    assert!(
        !text.contains("rm -rf data"),
        "newest is on page 1, not 2:\n{text}"
    );
    assert!(
        text.contains("--page 1"),
        "should link back to the newer page"
    );

    // Paging past the end is graceful, not an empty-state lie.
    let past = kintsugi()
        .args(["log", "-n", "1", "--page", "9"])
        .env("KINTSUGI_DB", &db)
        .env("NO_COLOR", "1")
        .output()
        .unwrap();
    assert!(past.status.success());
    assert!(String::from_utf8_lossy(&past.stdout).contains("no events on page 9"));
}

#[test]
fn log_shows_recorded_events() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    seed_log(&db);

    let out = kintsugi()
        .arg("log")
        .env("KINTSUGI_DB", &db)
        .env("NO_COLOR", "1")
        .output()
        .unwrap();

    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("ls"), "should list the ls event:\n{text}");
    assert!(text.contains("rm -rf data"));
    assert!(text.contains("allowed"));
    assert!(text.contains("held"));
    assert!(text.contains("[catastrophic]"));
}

#[test]
fn log_empty_shows_designed_empty_state() {
    let tmp = tempfile::tempdir().unwrap();
    let out = kintsugi()
        .arg("log")
        .env("KINTSUGI_DB", tmp.path().join("missing.db"))
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("No events yet"));
}

#[test]
fn status_reports_event_count_and_chain() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("events.db");
    seed_log(&db);

    let out = kintsugi()
        .arg("status")
        .env("KINTSUGI_DB", &db)
        // Point the socket somewhere unconnectable so daemon shows "stopped".
        .env("KINTSUGI_SOCKET", tmp.path().join("none.sock"))
        .output()
        .unwrap();

    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("events:  2"), "status:\n{text}");
    assert!(text.contains("intact"));
    assert!(text.contains("stopped"));
}

#[test]
fn init_starts_daemon_and_status_reports_running() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let data = home.join(".local/share");
    let run = tmp.path().join("run");
    std::fs::create_dir_all(&run).unwrap();

    let common = |cmd: &mut Command| {
        cmd.env("HOME", &home)
            .env("XDG_DATA_HOME", &data)
            .env("KINTSUGI_DATA_DIR", &data)
            .env("KINTSUGI_DB", data.join("events.db"))
            .env("XDG_RUNTIME_DIR", &run)
            .env("KINTSUGI_CONFIG", tmp.path().join("none.toml"));
    };

    // Full init (starts the daemon as a detached child).
    let mut init = kintsugi();
    init.arg("init");
    common(&mut init);
    let out = init.output().unwrap();
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("daemon"));

    // Status should now see a running daemon. Poll: the daemon binds
    // asynchronously and a loaded CI runner can be slow — 5s wasn't enough
    // on the Ubuntu runner under contention, so give it ~20s.
    let mut text = String::new();
    for _ in 0..200 {
        let mut status = kintsugi();
        status.arg("status");
        common(&mut status);
        text = String::from_utf8_lossy(&status.output().unwrap().stdout).into_owned();
        if text.contains("running") {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    // Stop the daemon WE started by its recorded PID — not a broad `pkill`, which
    // would also kill daemons spawned by parallel test binaries.
    if let Ok(pid) = std::fs::read_to_string(data.join("kintsugi.pid")) {
        let _ = std::process::Command::new("kill").arg(pid.trim()).status();
    }

    assert!(
        text.contains("running"),
        "status should show running daemon:\n{text}"
    );
}

#[test]
fn init_no_daemon_creates_shims_and_wires_claude() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    // Use KINTSUGI_DATA_DIR so the shim location is deterministic on every OS
    // (the `directories` crate resolves the data dir differently per platform).
    let data = tmp.path().join("data");
    std::fs::create_dir_all(home.join(".claude")).unwrap();

    let run_init = || {
        kintsugi()
            .arg("init")
            .arg("--no-daemon")
            .env("HOME", &home)
            .env("KINTSUGI_DATA_DIR", &data)
            .env_remove("XDG_RUNTIME_DIR")
            .output()
            .unwrap()
    };

    let out = run_init();
    assert!(
        out.status.success(),
        "init failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // Shims created under the data dir.
    let shim_rm = data.join("shims/rm");
    assert!(
        shim_rm.is_symlink() || shim_rm.exists(),
        "rm shim should exist"
    );

    // Claude settings wired with our hook.
    let settings = home.join(".claude/settings.json");
    let body = std::fs::read_to_string(&settings).unwrap();
    assert!(
        body.contains("kintsugi-hook"),
        "settings should reference kintsugi-hook:\n{body}"
    );
    assert!(body.contains("PreToolUse"));

    // Idempotent: running again does not duplicate the hook.
    run_init();
    let body2 = std::fs::read_to_string(&settings).unwrap();
    assert_eq!(
        body2.matches("kintsugi-hook").count(),
        1,
        "hook must not duplicate"
    );
}

#[test]
fn init_wires_every_supported_cli_natively() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let data = tmp.path().join("data");
    // Create each CLI's config dir so detection fires for all of them.
    for dir in [
        ".claude", ".qwen", ".gemini", ".copilot", ".cursor", ".codex",
    ] {
        std::fs::create_dir_all(home.join(dir)).unwrap();
    }
    std::fs::create_dir_all(home.join(".config/opencode")).unwrap();

    let run_init = || {
        kintsugi()
            .arg("init")
            .arg("--no-daemon")
            .env("HOME", &home)
            .env("KINTSUGI_DATA_DIR", &data)
            .env_remove("XDG_RUNTIME_DIR")
            .output()
            .unwrap()
    };

    let out = run_init();
    assert!(
        out.status.success(),
        "init failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // Each CLI got its native config, with the right per-agent --agent flag and
    // the right event/structure for that CLI.
    let read = |p: &str| std::fs::read_to_string(home.join(p)).unwrap_or_default();

    let claude = read(".claude/settings.json");
    assert!(
        claude.contains("PreToolUse") && claude.contains("--agent claude"),
        "claude:\n{claude}"
    );

    let qwen = read(".qwen/settings.json");
    assert!(
        qwen.contains("PreToolUse") && qwen.contains("--agent qwen"),
        "qwen:\n{qwen}"
    );

    let gemini = read(".gemini/settings.json");
    assert!(
        gemini.contains("BeforeTool") && gemini.contains("--agent gemini"),
        "gemini:\n{gemini}"
    );

    let copilot = read(".copilot/hooks/kintsugi.json");
    assert!(
        copilot.contains("preToolUse") && copilot.contains("--agent copilot"),
        "copilot:\n{copilot}"
    );

    let cursor = read(".cursor/hooks.json");
    assert!(
        cursor.contains("beforeShellExecution") && cursor.contains("--agent cursor"),
        "cursor:\n{cursor}"
    );

    let codex = read(".codex/config.toml");
    assert!(
        codex.contains("PreToolUse") && codex.contains("--agent codex"),
        "codex:\n{codex}"
    );

    let opencode = read(".config/opencode/plugin/kintsugi.js");
    assert!(
        opencode.contains("tool.execute.before") && opencode.contains("--agent"),
        "opencode:\n{opencode}"
    );

    // Idempotent across the board: a second init duplicates nothing.
    run_init();
    for (p, needle) in [
        (".qwen/settings.json", "--agent qwen"),
        (".gemini/settings.json", "--agent gemini"),
        (".cursor/hooks.json", "--agent cursor"),
        (".codex/config.toml", "--agent codex"),
    ] {
        let body = read(p);
        assert_eq!(body.matches(needle).count(), 1, "{p} duplicated:\n{body}");
    }
}

#[test]
fn test_command_is_a_dry_run_classifier() {
    // Catastrophic, shown without running or contacting a daemon.
    let out = kintsugi()
        .args(["test", "rm -rf /"])
        .env("KINTSUGI_SOCKET", "/nonexistent/kintsugi.sock")
        .output()
        .unwrap();
    assert!(out.status.success());
    let t = String::from_utf8_lossy(&out.stdout);
    assert!(t.contains("CATASTROPHIC"), "{t}");
    assert!(t.contains("Dry run"), "{t}");

    // Safe.
    let safe = kintsugi().args(["test", "git status"]).output().unwrap();
    assert!(String::from_utf8_lossy(&safe.stdout).contains("SAFE"));

    // The AST pass surfaces danger hidden in a command substitution.
    let sub = kintsugi()
        .args(["test", "echo \"$(git push --force)\""])
        .output()
        .unwrap();
    let st = String::from_utf8_lossy(&sub.stdout);
    assert!(
        st.contains("CATASTROPHIC"),
        "substitution should be caught:\n{st}"
    );
}

/// Drives a live daemon through `kintsugi queue` and the `kintsugi run` branches, to
/// cover the queue/run handlers (which only exercise meaningfully against a real
/// daemon + queued items). Linux-only: it relies on `setsid` to run `kintsugi run`
/// in a session with no controlling terminal, so the catastrophic confirmation
/// (`/dev/tty`) declines deterministically instead of blocking on input.
#[cfg(target_os = "linux")]
#[test]
fn run_and_queue_against_live_daemon() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let data = home.join(".local/share");
    let run = tmp.path().join("run");
    std::fs::create_dir_all(&run).unwrap();
    let db = data.join("events.db");
    let cfg = tmp.path().join("none.toml");

    let common = |cmd: &mut Command| {
        cmd.env("HOME", &home)
            .env("XDG_DATA_HOME", &data)
            .env("KINTSUGI_DATA_DIR", &data)
            .env("KINTSUGI_DB", &db)
            .env("XDG_RUNTIME_DIR", &run)
            .env("KINTSUGI_CONFIG", &cfg)
            .env("NO_COLOR", "1");
    };

    // Start the daemon (detached child) and wait for it to bind.
    let mut init = kintsugi();
    init.arg("init");
    common(&mut init);
    assert!(init.output().unwrap().status.success());
    let mut up = false;
    for _ in 0..200 {
        let mut s = kintsugi();
        s.arg("status");
        common(&mut s);
        if String::from_utf8_lossy(&s.output().unwrap().stdout).contains("running") {
            up = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    assert!(up, "daemon should be running");

    // Enqueue two held commands into the daemon's DB: one from a hook (no waiter
    // → `kintsugi run`) and one in-band from MCP (a waiter → `kintsugi approve`).
    let (hook_id, mcp_id, deny_id);
    {
        let log = EventLog::open(&db).unwrap();
        let hook = ProposedCommand::new(
            "claude-code",
            "/tmp/proj",
            vec!["rm".into(), "-rf".into(), "build".into()],
            "rm -rf build",
        );
        hook_id = hook.id.to_string();
        log.enqueue_pending(&hook, Class::Catastrophic, "rm:recursive")
            .unwrap();
        let mcp = ProposedCommand::new(
            "mcp",
            "/tmp/proj",
            vec!["rm".into(), "-rf".into(), "dist".into()],
            "rm -rf dist",
        );
        mcp_id = mcp.id.to_string();
        log.enqueue_pending(&mcp, Class::Catastrophic, "rm:recursive")
            .unwrap();
        let extra = ProposedCommand::new(
            "shim",
            "/tmp/proj",
            vec!["rm".into(), "-rf".into(), "tmp".into()],
            "rm -rf tmp",
        );
        deny_id = extra.id.to_string();
        log.enqueue_pending(&extra, Class::Catastrophic, "rm:recursive")
            .unwrap();
    }

    let kill = || {
        if let Ok(pid) = std::fs::read_to_string(data.join("kintsugi.pid")) {
            let _ = Command::new("kill").arg(pid.trim()).status();
        }
    };

    // `kintsugi queue` lists both and shows the origin-aware verbs.
    let mut q = kintsugi();
    q.arg("queue");
    common(&mut q);
    let qt = String::from_utf8_lossy(&q.output().unwrap().stdout).into_owned();

    // `kintsugi run <mcp>` → in-band, redirected to approve (bails non-zero).
    let mut r1 = kintsugi();
    r1.args(["run", &mcp_id[..8]]);
    common(&mut r1);
    let r1o = r1.output().unwrap();
    let r1t = String::from_utf8_lossy(&r1o.stderr).into_owned();

    // `kintsugi run` with no id and 2 held → asks for an id (bails non-zero).
    let mut r2 = kintsugi();
    r2.arg("run");
    common(&mut r2);
    let r2o = r2.output().unwrap();
    let r2t = String::from_utf8_lossy(&r2o.stderr).into_owned();

    // `setsid kintsugi run <hook>` → no controlling tty → the confirmation declines
    // and nothing runs (covers the run-plan print + reversibility note + confirm).
    let mut r3 = Command::new("setsid");
    r3.arg(env!("CARGO_BIN_EXE_kintsugi"))
        .args(["run", &hook_id[..8]])
        .stdin(std::process::Stdio::null());
    common(&mut r3);
    let r3o = r3.output().unwrap();
    let r3t = String::from_utf8_lossy(&r3o.stdout).into_owned();

    // `kintsugi run <unknown>` while the queue is non-empty → no match (bails).
    let mut r4 = kintsugi();
    r4.args(["run", "zzzzzzzz"]);
    common(&mut r4);
    let r4o = r4.output().unwrap();
    let r4t = String::from_utf8_lossy(&r4o.stderr).into_owned();

    // Approve both, exercising the origin-aware messages: hook (use `kintsugi run`)
    // and in-band MCP (the agent may proceed).
    let mut a1 = kintsugi();
    a1.args(["approve", &hook_id[..8]]);
    common(&mut a1);
    let a1t = String::from_utf8_lossy(&a1.output().unwrap().stdout).into_owned();
    let mut a2 = kintsugi();
    a2.args(["approve", &mcp_id[..8]]);
    common(&mut a2);
    let a2t = String::from_utf8_lossy(&a2.output().unwrap().stdout).into_owned();

    // Deny the third (covers the deny branch).
    let mut d1 = kintsugi();
    d1.args(["deny", &deny_id[..8]]);
    common(&mut d1);
    let d1t = String::from_utf8_lossy(&d1.output().unwrap().stdout).into_owned();

    // Queue now empty → `kintsugi run` and `kintsugi queue` both say so.
    let mut r5 = kintsugi();
    r5.arg("run");
    common(&mut r5);
    let r5t = String::from_utf8_lossy(&r5.output().unwrap().stdout).into_owned();
    let mut q2 = kintsugi();
    q2.arg("queue");
    common(&mut q2);
    let q2t = String::from_utf8_lossy(&q2.output().unwrap().stdout).into_owned();

    // approve of an unknown id → clean error (covers the no-match arm).
    let mut au = kintsugi();
    au.args(["approve", "zzzzzzzz"]);
    common(&mut au);
    let auo = au.output().unwrap();

    kill();

    assert!(
        qt.contains("rm -rf build"),
        "queue lists the hook cmd:\n{qt}"
    );
    assert!(
        qt.contains("kintsugi run") && qt.contains("kintsugi approve"),
        "queue shows both verbs:\n{qt}"
    );
    assert!(
        !r1o.status.success() && r1t.contains("approve"),
        "in-band run redirects to approve:\n{r1t}"
    );
    assert!(
        !r2o.status.success() && r2t.contains("held"),
        "no-id with many held asks for an id:\n{r2t}"
    );
    assert!(
        r3t.contains("rm -rf build") && r3t.contains("Not run"),
        "no-tty run shows the plan and declines:\n{r3t}"
    );
    assert!(
        !r4o.status.success() && r4t.contains("no held command"),
        "unknown id:\n{r4t}"
    );
    assert!(
        a1t.contains("kintsugi run"),
        "hook approve points at run:\n{a1t}"
    );
    assert!(
        a2t.contains("proceed"),
        "in-band approve lets the agent proceed:\n{a2t}"
    );
    assert!(d1t.contains("denied"), "deny reports denied:\n{d1t}");
    assert!(r5t.contains("empty"), "empty queue run:\n{r5t}");
    assert!(q2t.contains("empty"), "empty queue listing:\n{q2t}");
    assert!(!auo.status.success(), "approve of unknown id errors");
}