kintsugi-daemon 0.4.0

Kintsugi resident daemon: local IPC server and the decision loop that classifies proposed commands and records them.
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
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
//! Kintsugi resident daemon library.
//!
//! Long-lived process that owns the event log and runs the decision loop. The
//! interception layer connects over a local socket, sends a [`ProposedCommand`],
//! and blocks on the returned [`Verdict`].
//!
//! In Phase 0 the daemon is a pure recorder: it logs every proposal and allows
//! it. The Tier-1 rule engine (Phase 1) plugs into [`Daemon::decide`] without
//! changing the IPC or logging paths.

#![forbid(unsafe_code)]

pub mod ipc;
pub mod watch;

use std::path::PathBuf;

use std::cell::{Cell, RefCell};

use anyhow::{Context, Result};
use directories::ProjectDirs;
use kintsugi_core::admin::{self, VaultState};
use kintsugi_core::{Decision, EventLog, Mode, ProposedCommand, TaintEvent, TaintState, Verdict};
use kintsugi_model::DependencyHint;

pub use ipc::{Client, Observation, Resolution, Server};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// The kill-switch flag file name, alongside the event-log database.
pub const KILL_SWITCH_FILE: &str = "panic.flag";

/// Path to the panic kill-switch flag (alongside the default event log).
pub fn kill_switch_path() -> PathBuf {
    default_db_path()
        .parent()
        .map(|p| p.join(KILL_SWITCH_FILE))
        .unwrap_or_else(|| std::env::temp_dir().join(KILL_SWITCH_FILE))
}

/// The fail-closed marker file name, alongside the event-log database.
pub const FAIL_CLOSED_FILE: &str = "fail-closed.flag";

/// Path to the fail-closed marker (alongside the default event log). Its mere
/// existence is the signal — the content is irrelevant. The interception layer
/// (shim/hook/MCP) reads it **without** the daemon, so that killing the daemon
/// can't be used to open the gate: with the marker present, an unreachable
/// daemon means *block*, not *run unguarded*.
pub fn fail_closed_marker_path() -> PathBuf {
    default_db_path().with_file_name(FAIL_CLOSED_FILE)
}

/// Whether the admin-set fail-closed marker is present. Cheap, daemon-free, and
/// callable from the interception fast path. In the locked posture the marker is
/// owned by the privileged account (root / a dedicated `kintsugi` user), so an
/// audited non-root agent cannot remove it to re-open the gate.
pub fn is_fail_closed_marked() -> bool {
    fail_closed_marker_path().exists()
}

/// Create or remove the fail-closed marker to match `on`. Best-effort, atomic
/// create; called by the admin flow when the locked `fail_closed` setting
/// changes so the posture survives a daemon restart and a kill.
pub fn set_fail_closed_marker(on: bool) -> std::io::Result<()> {
    let path = fail_closed_marker_path();
    if on {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        // 0644: world-readable (the shim must read it) but, in the locked posture,
        // owned by the privileged account so the audited user can't delete it.
        std::fs::write(&path, b"fail-closed\n")?;
    } else if path.exists() {
        std::fs::remove_file(&path)?;
    }
    Ok(())
}

/// Resolve the event-log database path. Override with `KINTSUGI_DB` (handy in tests).
pub fn default_db_path() -> PathBuf {
    if let Ok(p) = std::env::var("KINTSUGI_DB") {
        return PathBuf::from(p);
    }
    if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
        return dirs.data_dir().join("events.db");
    }
    std::env::temp_dir().join("kintsugi-events.db")
}

/// The resident decision loop: owns the event log, the warm scorer, classifies,
/// records.
pub struct Daemon {
    log: EventLog,
    mode: Mode,
    scorer: Box<dyn kintsugi_model::Scorer>,
    snapshot_dir: PathBuf,
    kill_path: PathBuf,
    /// The admin vault **path**, resolved once at daemon startup from the path the
    /// daemon itself chose (a caller's environment can't redirect it). The vault
    /// *contents* are read fresh from this path on every privileged op
    /// ([`current_vault`](Self::current_vault)) — never cached — so a re-provision
    /// or password change applies immediately, with no restart and no stale-copy bug.
    vault_path: PathBuf,
    /// Whether this log records a provision (`audit:provision`) — computed once at
    /// open. With the latch set, a *missing* vault is `Degraded`, not
    /// `Unprovisioned`: deleting the vault file is not a way back to bare
    /// approval on a machine that was provisioned.
    vault_expected: bool,
    /// The last challenge nonce issued (and its op), consumed once by `Shutdown`
    /// or `Approve`. The slot is deliberately single and one-shot: a challenge
    /// is bound to exactly one op (`"shutdown"` or `"approve:<id>"`) and one
    /// use. A consequence, accepted by design: an `AuthBegin` for approve
    /// supersedes any unconsumed shutdown challenge and vice versa — the
    /// op-binding check then rejects any proof minted for the overwritten op,
    /// so the supersede can never authorize the other operation (documented in
    /// docs/policy.md and pinned by `approval_auth.rs`).
    pending: RefCell<Option<(Vec<u8>, String)>>,
    /// Set when an authenticated shutdown has been accepted; the serve loop exits.
    shutdown: Cell<bool>,
    /// In-memory brute-force throttle for admin authentication.
    throttle: RefCell<AuthThrottle>,
    /// Session/file information-flow (taint) state for the Provenance feature.
    /// Event-sourced ([`TaintState`]): every transition is persisted to the
    /// durable taint stream and the state is rebuilt by replaying it on a cold
    /// start (see [`open`](Self::open)), so taint survives a daemon restart
    /// (Phase 6 hardening item D — closes the fail-open-on-restart gap).
    taint: RefCell<TaintState>,
    /// Consecutive-block counter per session for the negotiation circuit breaker
    /// (Phase 6). The hook is one-shot per tool call, so this resident state is the
    /// only place that can count an agent retrying a blocked action across calls.
    denial_streak: RefCell<std::collections::HashMap<String, u32>>,
    /// Caps how much model-inference time the recorder path can impose on the
    /// single-threaded serve loop, so a flood of risky shell records can't starve
    /// real hold/approve traffic. See [`ScoreBudget`].
    score_budget: RefCell<ScoreBudget>,
}

/// Rate-limit + lockout for admin authentication. The daemon is the single
/// authority, so a process-local counter is enough: after a few consecutive
/// failures it locks out for an exponentially growing window (defeating a script
/// hammering the admin password), and a success resets it.
#[derive(Default)]
struct AuthThrottle {
    failures: u32,
    locked_until: Option<std::time::Instant>,
}

impl AuthThrottle {
    /// Failed attempts allowed before the first lockout.
    const FREE_ATTEMPTS: u32 = 5;

    /// Remaining lockout duration, if currently locked out.
    fn lockout_remaining(&self) -> Option<std::time::Duration> {
        self.locked_until
            .and_then(|t| t.checked_duration_since(std::time::Instant::now()))
    }

    /// Count a failed attempt; arm/extend the lockout once past the free budget.
    fn record_failure(&mut self) {
        self.failures = self.failures.saturating_add(1);
        if self.failures >= Self::FREE_ATTEMPTS {
            // 30s, then doubling (60s, 120s, …) capped at one hour.
            let over = (self.failures - Self::FREE_ATTEMPTS).min(7);
            self.locked_until = Some(
                std::time::Instant::now()
                    + std::time::Duration::from_secs((30u64 << over).min(3600)),
            );
        }
    }

    fn reset(&mut self) {
        self.failures = 0;
        self.locked_until = None;
    }
}

/// Token-bucket budget for the *model scoring* on the recorder path.
///
/// The IPC serve loop is single-threaded: it reads one request, handles it to
/// completion, then accepts the next. `record_shell` scores risky shell events
/// with the local model so the Recorder rows can show a plain-English summary —
/// but that scoring is one synchronous inference on the serve thread. A local
/// peer (a runaway or compromised agent — the socket is owner-only, but that's
/// exactly who we defend against) that floods the socket with risky `Observe`
/// records would serialize one inference each and starve real hold/approve
/// traffic, blinding the user's safety control plane. Crucially, that scoring is
/// *cosmetic*: `record_shell` always records `Allow` (the command already ran),
/// and the danger `class` rides along regardless. So under sustained load we
/// shed the summary, not the record — the row is still logged with its class,
/// just without the prose. `capacity` is the burst a quiet session banks;
/// `refill_per_sec` is the steady ceiling on inferences/sec the recorder can
/// impose on the serve thread.
struct ScoreBudget {
    tokens: f64,
    capacity: f64,
    refill_per_sec: f64,
    last: std::time::Instant,
}

impl ScoreBudget {
    fn new(capacity: f64, refill_per_sec: f64, now: std::time::Instant) -> Self {
        Self {
            tokens: capacity,
            capacity,
            refill_per_sec,
            last: now,
        }
    }

    /// Refill for elapsed time, then try to spend one token. Returns `false` when
    /// the budget is exhausted — the caller skips the expensive scoring and falls
    /// back to a rules-only (summary-less) record.
    fn try_spend(&mut self, now: std::time::Instant) -> bool {
        let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
        self.last = now;
        self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
        if self.tokens >= 1.0 {
            self.tokens -= 1.0;
            true
        } else {
            false
        }
    }
}

/// Agents whose CLI shows a WORKING interactive y/N prompt for an ambiguous
/// hold. For these, the hold is resolved by the agent's own UI, so a daemon
/// queue entry would just orphan (no one ever calls `resolve_pending`).
///
/// Everyone else — Gemini, Antigravity, OpenCode (its plugin throws on `ask`),
/// the `kintsugi-exec` MCP tool, and any future/unknown surface — has no
/// interactive prompt, so the human resolves the hold via the queue (the Held
/// screen / `kintsugi queue` / `approve`). Default to enqueueing, so a new
/// agent never silently drops a hold the user can't recover.
const AGENTS_WITH_NATIVE_ASK: &[&str] = &["claude-code", "qwen", "copilot", "cursor", "codex"];

/// Does THIS held command need a daemon-side queue entry?
///
/// Catastrophic always does (the dialect maps Hold→Deny, so the agent can't
/// resolve it and the human runs it via `kintsugi run`). Ambiguous needs one
/// for every agent EXCEPT those with a working native ask — see the constant.
fn needs_queue_entry(cmd: &ProposedCommand, class: kintsugi_core::Class) -> bool {
    if class == kintsugi_core::Class::Catastrophic {
        return true;
    }
    !AGENTS_WITH_NATIVE_ASK.contains(&cmd.agent.as_str())
}

/// The only op string [`shutdown_op`](Daemon::shutdown_op) serves. The proof's
/// op binding is checked against THIS constant, not against the caller's op
/// echo: a challenge minted for any other op (`"approve:<id>"`, junk) must
/// never authorize a shutdown by replaying the same op string back.
const SHUTDOWN_OP: &str = "shutdown";

/// Bound and canonicalize a caller-supplied op string before it reaches the audit
/// log. Keeps `approve:<uuid>` intact (the shape the protocol uses), replaces any
/// other byte with `?`, and caps the whole thing so a hostile peer cannot grow the
/// never-deletable log with megabyte-long "op" names.
fn sanitize_op(op: &str) -> String {
    const MAX: usize = 64;
    let mut out = String::with_capacity(op.len().min(MAX));
    for ch in op.chars().take(MAX) {
        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.') {
            out.push(ch);
        } else {
            out.push('?');
        }
    }
    if op.chars().count() > MAX {
        out.push('…');
    }
    out
}

impl Daemon {
    /// Open the daemon backed by the event log at `db_path`, creating parent dirs.
    pub fn open(db_path: impl Into<PathBuf>) -> Result<Self> {
        let db_path = db_path.into();
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("create data dir {}", parent.display()))?;
        }
        let data_dir = db_path
            .parent()
            .unwrap_or_else(|| std::path::Path::new("."))
            .to_path_buf();
        // Keep the data dir private to the owning user: the event log records raw
        // commands verbatim (spine #3), which can include secrets passed on a
        // command line. We never scrub the verbatim record, so we protect it at
        // rest (0700 dir, 0600 db) instead of leaving it world-readable.
        #[cfg(unix)]
        ipc::set_mode(&data_dir, 0o700);
        let snapshot_dir = data_dir.join("snapshots");
        let kill_path = data_dir.join(KILL_SWITCH_FILE);
        let log = EventLog::open(&db_path)
            .with_context(|| format!("open event log at {}", db_path.display()))?;
        // Owner-only on the db (and its WAL/SHM siblings) — it holds verbatim
        // commands that may contain secrets.
        #[cfg(unix)]
        for suffix in ["", "-wal", "-shm"] {
            let p = if suffix.is_empty() {
                db_path.clone()
            } else {
                PathBuf::from(format!("{}{suffix}", db_path.display()))
            };
            if p.exists() {
                ipc::set_mode(&p, 0o600);
            }
        }
        // Resolve the admin vault path here at startup (the daemon is launched by
        // the admin/systemd, so its environment — not a later caller's — decides the
        // location). The contents are read fresh per op, never cached.
        let vault_path = admin::default_vault_path();
        // Rebuild information-flow taint by replaying the durable taint stream, so
        // a restart reconstructs taint instead of failing open (Provenance item D).
        // A load failure degrades to empty taint rather than aborting startup, but
        // is logged loudly — the base rules and the rest of the daemon still run.
        let taint = match log.load_taint_events() {
            Ok(events) => TaintState::from_events(events.iter()),
            Err(e) => {
                eprintln!("kintsugi-daemon: failed to replay taint events: {e}");
                TaintState::new()
            }
        };
        // The provision latch: a machine that recorded a provision must never fall
        // back to bare approval just because the vault file disappeared.
        let vault_expected = log.has_provision_marker().unwrap_or(false);
        Ok(Self {
            log,
            mode: Mode::default(),
            scorer: kintsugi_model::default_scorer(),
            snapshot_dir,
            kill_path,
            vault_path,
            vault_expected,
            pending: RefCell::new(None),
            shutdown: Cell::new(false),
            throttle: RefCell::new(AuthThrottle::default()),
            taint: RefCell::new(taint),
            denial_streak: RefCell::new(std::collections::HashMap::new()),
            // Burst of 8 banked by a quiet session; steady ceiling of 4 model
            // scorings/sec on the serve thread under a sustained recorder flood.
            score_budget: RefCell::new(ScoreBudget::new(8.0, 4.0, std::time::Instant::now())),
        })
    }

    /// Apply a taint transition to the session/file taint state.
    ///
    /// Fed by the content-tool observation surface (Phase 6.2) and by reset
    /// policy. Pure state update — the decision path consults this; it never lets
    /// a model change it (spine: rules decide, model only explains).
    ///
    /// Persist-then-apply: the transition is written to the durable, append-only
    /// taint stream first (so it survives a daemon restart via replay in
    /// [`open`](Self::open)), then applied to live in-memory state. The persist is
    /// best-effort — a write failure is logged but never panics the daemon or
    /// drops protection for the current session; it only risks losing this taint
    /// across a future restart.
    ///
    /// Segment G: the event's `source_id` is redacted *before* both the persist and
    /// the apply. A source identifier is meant to be an identifier only, but a URL
    /// can carry a credential (`https://u:tok@host/p`, a colonless PAT-as-username,
    /// `?api_key=…`). Normalizing at this single ingest boundary means the redacted
    /// form is the only one that ever reaches the append-only (unscrubbable) log
    /// row, the replayed state, the provenance trail, or an agent-facing reason.
    pub fn apply_taint(&self, event: &TaintEvent) {
        let event = event.with_redacted_source_id();
        if let Err(e) = self.log.record_taint_event(&event) {
            eprintln!("kintsugi-daemon: failed to persist taint event: {e}");
        }
        self.taint.borrow_mut().apply(&event);
    }

    /// Apply a file-write taint transition (V1.1): a tainted session wrote
    /// `path`, so a later reader of that path inherits the session's taint through
    /// [`TaintEvent::WriteFile`].
    ///
    /// Gated on the effective policy for the *writing session's* cwd — the same
    /// `[provenance] enabled` switch that arms the trifecta floor. With the guard
    /// off nothing is recorded: a path label would be inert state the operator
    /// explicitly disabled.
    ///
    /// A clean session can propagate nothing, so its write is skipped outright (it
    /// would be a no-op transition): that keeps frequent benign edits out of the
    /// append-only taint stream instead of appending a no-op row per file. Beyond
    /// that this follows [`apply_taint`](Self::apply_taint) exactly — persist, then
    /// apply — and carries no `source_id`, so there is nothing to redact (segment
    /// G). `path` is an identifier; write content never reaches this boundary.
    pub fn apply_write(&self, session: &str, path: &str, cwd: &std::path::Path) {
        if session.is_empty() || path.trim().is_empty() {
            return;
        }
        if !load_policy(cwd).provenance_enabled() {
            return;
        }
        if !self.is_session_tainted(Some(session)) {
            return;
        }
        self.apply_taint(&TaintEvent::WriteFile {
            session: session.to_string(),
            path: std::path::PathBuf::from(path),
        });
    }

    /// Apply a file-read taint transition (V1.1): a session read `path`, and if an
    /// earlier tainted session labelled that path, the reader inherits the taint.
    ///
    /// This is the consumer that makes write propagation mean anything — without
    /// it `TaintEvent::WriteFile` fills a map nothing reads, and "the agent
    /// exfiltrated what it learned by writing and re-reading a file" stays
    /// invisible. Same gating as [`apply_write`](Self::apply_write): the policy of
    /// the reading session's cwd decides, a clean path is skipped so ordinary
    /// reads never touch the append-only taint stream, and an already-tainted
    /// reader is a no-op.
    ///
    /// Observation only: it never blocks, never enqueues, and never influences a
    /// verdict; `path` is an identifier and the file's content is never read.
    pub fn apply_read(&self, session: &str, path: &str, cwd: &std::path::Path) {
        if session.is_empty() || path.trim().is_empty() {
            return;
        }
        if !load_policy(cwd).provenance_enabled() {
            return;
        }
        if self.is_session_tainted(Some(session)) {
            return; // already tainted: the transition would be a no-op
        }
        if !self
            .taint
            .borrow()
            .is_path_tainted(std::path::Path::new(path))
        {
            return; // nobody labelled this path
        }
        self.apply_taint(&TaintEvent::ReadFile {
            session: session.to_string(),
            path: std::path::PathBuf::from(path),
        });
    }

    /// Whether the given session has been influenced by untrusted content. A
    /// `None` (untracked) session is reported as not tainted.
    pub fn is_session_tainted(&self, session: Option<&str>) -> bool {
        self.taint.borrow().is_session_tainted(session)
    }

    /// The session's accumulated provenance labels, if any — the in-process read
    /// the provenance trail (P6.4) will surface. Source identifiers are already
    /// redacted at ingest (see [`apply_taint`](Self::apply_taint)), so callers and
    /// the eventual IPC view only ever see secret-free ids.
    pub fn session_provenance(&self, session: &str) -> Option<kintsugi_core::TaintSet> {
        self.taint.borrow().session_taint(session).cloned()
    }

    /// Build the human-readable provenance trail for a command (P6.4): the session's
    /// untrusted reads, then this command's sensitive read → egress sink → the
    /// trifecta rule that fired. Identifiers only (no secret contents). This is the
    /// forensic chain the CLI/TUI renders on a held trifecta and the audit replay
    /// uses to reconstruct "everything descended from source X".
    pub fn provenance_trail(&self, cmd: &ProposedCommand) -> Vec<kintsugi_core::ProvStep> {
        use kintsugi_core::ProvStep;
        let session = cmd.session.as_deref();
        // The trail explains *untrusted-content provenance*. A clean session has
        // none, so its trail is empty even if the command reads a secret or hits a
        // sink — there is nothing for those legs to descend from, and no rule fires.
        let Some(set) = session.and_then(|s| self.session_provenance(s)) else {
            return Vec::new();
        };
        if !set.is_tainted() {
            return Vec::new();
        }
        let mut trail = kintsugi_core::untrusted_trail(&set);
        let sensitive = kintsugi_core::is_sensitive_read(cmd);
        let egress = kintsugi_core::is_egress_sink(cmd);
        if let Some(path) = &sensitive {
            trail.push(ProvStep::SensitiveRead { path: path.clone() });
        }
        if let Some(target) = &egress {
            trail.push(ProvStep::EgressSink {
                target: target.clone(),
            });
        }
        let outcome = kintsugi_core::evaluate_trifecta(true, sensitive.is_some(), egress.is_some());
        if let Some(rule) = outcome.rule() {
            trail.push(ProvStep::RuleFired {
                rule: rule.to_string(),
            });
        }
        trail
    }

    /// Apply the Provenance trifecta as a deterministic class **floor**: a command
    /// in a tainted session that reads a secret and reaches an egress sink is the
    /// lethal trifecta and is forced to the catastrophic hard floor. Escalation
    /// only — it can raise the class, never lower it (spine: monotonic caution).
    ///
    /// The trifecta can fire only when the session is *currently* tainted. Taint
    /// is durable across daemon restarts (item D): transitions are persisted and
    /// replayed on [`open`](Self::open), so a restart no longer silently clears it.
    /// This remains interception, not an unbypassable firewall (e.g. a tool run by
    /// absolute path can dodge observation); the base rules still stand regardless.
    fn trifecta_floor(
        &self,
        cmd: &ProposedCommand,
        policy: &kintsugi_core::Policy,
        base_class: kintsugi_core::Class,
        base_rule: String,
    ) -> (kintsugi_core::Class, String) {
        use kintsugi_core::Trifecta;
        if !policy.provenance_enabled() || !self.is_session_tainted(cmd.session.as_deref()) {
            return (base_class, base_rule);
        }
        let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
        let egress = kintsugi_core::is_egress_sink(cmd).is_some();
        let outcome = kintsugi_core::evaluate_trifecta(true, sensitive, egress);
        let floor = match outcome {
            // The full trifecta: a hard floor that inherits the no-downgrade guard.
            Trifecta::Block => kintsugi_core::Class::Catastrophic,
            // Lesser bands: held (attended) / denied (unattended), tunable by policy.
            Trifecta::Hold | Trifecta::Annotate => kintsugi_core::Class::Ambiguous,
            Trifecta::None => return (base_class, base_rule),
        };
        let class = base_class.max(floor);
        // Only relabel the reason when the trifecta actually raised the floor;
        // otherwise the base rule was already at least this severe.
        if class.severity() > base_class.severity() {
            let rule = outcome.rule().unwrap_or("TRIFECTA");
            (class, format!("{rule}:provenance ({base_rule})"))
        } else {
            (class, base_rule)
        }
    }

    /// The advisory dependency hint for the ambiguous taint band (Phase 6 V1.1,
    /// hardening item H). Deterministic and I/O-free: string matching of the
    /// command against the session's — already-redacted — untrusted identifiers.
    ///
    /// The band is exactly what [`trifecta_floor`](Self::trifecta_floor)
    /// governs at the partial level: provenance enabled, the session currently
    /// tainted, and the command carrying exactly ONE leg — a sensitive read or
    /// an egress sink, i.e. `Trifecta::Hold`/`Annotate`. Not `Block` (that lands
    /// in the catastrophic arm, which keeps its summary-only behavior and never
    /// computes a hint) and not `None` (no leg: the floor is inert, and the
    /// command is judged purely on its own merits).
    ///
    /// Note the floor usually does not RAISE the class to get here — a
    /// leg-bearing command is already ambiguous at baseline, so the reason text
    /// alone can't prove band membership. This re-derives the floor's own three
    /// inputs instead (tainted + the same two predicates), which stays exactly
    /// in step with it by construction.
    fn dependency_hint(
        &self,
        cmd: &ProposedCommand,
        policy: &kintsugi_core::Policy,
    ) -> DependencyHint {
        use kintsugi_core::Trifecta;
        if !policy.provenance_enabled() {
            return DependencyHint::Unknown;
        }
        let Some(trail) = cmd
            .session
            .as_deref()
            .and_then(|s| self.session_provenance(s))
        else {
            return DependencyHint::Unknown;
        };
        if !trail.is_tainted() {
            return DependencyHint::Unknown;
        }
        let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
        let egress = kintsugi_core::is_egress_sink(cmd).is_some();
        match kintsugi_core::evaluate_trifecta(true, sensitive, egress) {
            Trifecta::Hold | Trifecta::Annotate => kintsugi_model::dependency_hint(cmd, &trail),
            Trifecta::Block | Trifecta::None => DependencyHint::Unknown,
        }
    }

    /// Whether an authenticated shutdown has been accepted (serve loop should exit).
    pub fn should_shutdown(&self) -> bool {
        self.shutdown.get()
    }

    /// Read the current admin vault, fresh from the daemon-resolved path. Called on
    /// every privileged op so a re-provision / password change applies immediately —
    /// the daemon is the authority on the *path* (a caller can't redirect it), and
    /// the contents are never cached, so there is no stale-vault class of bug.
    fn current_vault(&self) -> VaultState {
        match admin::load_vault(&self.vault_path) {
            // The file is gone but this machine was provisioned: treat it as
            // degraded so a deleted/renamed vault can never quietly re-enable
            // bare approval or a bare shutdown.
            VaultState::Unprovisioned if self.vault_expected => VaultState::Degraded(
                "the admin vault was provisioned on this machine but its file is missing"
                    .to_string(),
            ),
            other => other,
        }
    }

    /// Issue a challenge for a privileged op. `locked=false` means no vault, so the
    /// caller may proceed without a proof.
    fn auth_begin(&self, op: &str) -> ipc::Response {
        match self.current_vault() {
            VaultState::Degraded(_) => ipc::Response::Error {
                message: "admin vault is degraded; refusing privileged operations".into(),
            },
            VaultState::Locked(v) => {
                let nonce = match admin::random_auth_nonce() {
                    Ok(n) => n,
                    Err(_) => {
                        return ipc::Response::Error {
                            message: "could not generate a challenge".into(),
                        }
                    }
                };
                let (salt, params) = v.auth_challenge();
                *self.pending.borrow_mut() = Some((nonce.clone(), op.to_string()));
                ipc::Response::Challenge {
                    locked: true,
                    nonce: hex::encode(&nonce),
                    salt,
                    params,
                }
            }
            VaultState::Unprovisioned => ipc::Response::Challenge {
                locked: false,
                nonce: String::new(),
                salt: String::new(),
                params: kintsugi_core::admin::KdfParams::production(),
            },
        }
    }

    /// Complete an authenticated shutdown. Enforced against the daemon's own vault,
    /// read fresh from disk so a just-provisioned vault is honored without a restart.
    fn shutdown_op(
        &self,
        op: &str,
        nonce_hex: Option<&str>,
        proof_hex: Option<&str>,
    ) -> ipc::Response {
        // Pin the op: this handler serves `shutdown` only. Without the pin, a
        // challenge minted for another op (e.g. `AuthBegin("approve:<id>")`)
        // could authorize a shutdown by echoing the same op string back — the
        // proof would verify over that op — and an unprovisioned daemon would
        // shut down on ANY op string, no proof at all. Found by the Phase 7
        // approval-auth adversarial suite (`approval_auth.rs`); a monotonic
        // tightening (adds a refusal, never removes one).
        if op != SHUTDOWN_OP {
            self.record_admin(op, false, "op not served by shutdown");
            return ipc::Response::Error {
                message: format!("shutdown requires a `{SHUTDOWN_OP}` challenge"),
            };
        }
        let vault = match self.current_vault() {
            VaultState::Degraded(_) => {
                self.record_admin(op, false, "vault degraded");
                return ipc::Response::Error {
                    message: "admin vault is degraded; refusing to stop".into(),
                };
            }
            // Unprovisioned: there is no lock, so a clean shutdown is allowed.
            VaultState::Unprovisioned => {
                self.record_admin(op, true, "unprovisioned");
                self.shutdown.set(true);
                return ipc::Response::Ack;
            }
            VaultState::Locked(v) => v,
        };
        // Brute-force lockout, gated on a proof actually being offered: only a
        // request carrying a nonce/proof can guess anything, so only those are
        // throttled. A bare request cannot brute-force a secret, and counting it
        // would let any local peer lock the human out of their own privileged ops
        // (approve and shutdown share this budget) — a same-user DoS on the safety
        // workflow, which is the opposite of what the throttle is for.
        let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
        if proof_offered {
            if let Some(rem) = self.throttle.borrow().lockout_remaining() {
                self.record_admin(op, false, "locked out");
                return ipc::Response::Error {
                    message: format!(
                        "too many failed attempts; locked out for {}s",
                        rem.as_secs() + 1
                    ),
                };
            }
        }
        // The challenge is one-shot: take it regardless of the outcome.
        let pending = self.pending.borrow_mut().take();
        // A locked vault requires BOTH a nonce and a proof. If either is absent
        // (the unauthenticated caller), fail without ever decoding a placeholder
        // into the crypto path.
        let ok = match (pending, nonce_hex, proof_hex) {
            (Some((issued_nonce, issued_op)), Some(nonce_hex), Some(proof_hex)) => {
                match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
                    (Ok(nonce), Ok(proof)) => {
                        issued_op == op
                            && issued_nonce == nonce
                            && vault.verify_proof(&nonce, op.as_bytes(), &proof)
                    }
                    _ => false,
                }
            }
            _ => false,
        };
        if ok {
            self.throttle.borrow_mut().reset();
            self.record_admin(op, true, "authenticated");
            self.shutdown.set(true);
            ipc::Response::Ack
        } else {
            if proof_offered {
                self.throttle.borrow_mut().record_failure();
            }
            // Distinguish a wrong password from a vault that simply can't carry a
            // proof (provisioned before the asymmetric-auth scheme): the latter
            // fails for *every* password, so a bare "authentication failed" reads
            // as a bug. Point the user at the one-line fix instead.
            if !vault.supports_proof() {
                self.record_admin(op, false, "vault missing proof key");
                return ipc::Response::Error {
                    message:
                        "admin vault has no auth key — re-run `kintsugi admin provision --force` \
                              (the daemon picks it up immediately, no restart needed)"
                            .into(),
                };
            }
            self.record_admin(op, false, "authentication failed");
            ipc::Response::Error {
                message: "authentication failed".into(),
            }
        }
    }

    /// Complete an authenticated approval of queued command `id` (Phase 7,
    /// anchored trust — the proof-of-human gate on self-approval).
    ///
    /// The design mirrors [`shutdown_op`](Self::shutdown_op) exactly:
    /// - No vault → there is no secret to prove possession of, so approval is
    ///   bare (the owner-only socket is the boundary; documented honestly in
    ///   docs/security-assessment.md). This keeps the queue usable for users
    ///   who never provisioned a vault — the gate must never brick the queue.
    /// - Locked vault + bare request → **the threat case**: a same-user agent
    ///   process that reached the socket tries to approve its own held
    ///   command. Refused loudly with an actionable pointer at the human path,
    ///   audited as a hash-chained `self-approval blocked` event, and counted
    ///   by the same [`AuthThrottle`] as shutdown auth (5 free attempts, then
    ///   30 s → doubling lockout, capped at 1 h) so hammering is defeated.
    /// - Locked vault + nonce + proof → the one-shot pending challenge is
    ///   consumed, the proof is verified op-bound (`"approve:<id>"`, so a proof
    ///   can approve only the id it was issued for), and on success the
    ///   approval resolves through the *usual* [`resolve_pending`] path — the
    ///   kill-switch guard and the exactly-once CAS still apply. Auth decides
    ///   *who may talk*; the rules layer still decides *what may happen*
    ///   (spine: auth adds friction, it never unlocks).
    /// - Policy opt-out (`[security] require_approval_proof = false`) accepts
    ///   a bare approve again. The policy scope is the held command's repo
    ///   (the same `.kintsugi.toml` scope that produced the hold), so one repo
    ///   can opt out without weakening the default everywhere.
    ///
    /// `Deny` and `PrunePending` deliberately stay bare: an agent denying its
    /// own held command is a nuisance, not a threat, and prune touches only the
    /// queue, never the log.
    fn approve_op(
        &self,
        id: &str,
        nonce_hex: Option<&str>,
        proof_hex: Option<&str>,
    ) -> ipc::Response {
        let op = format!("approve:{id}");
        // The auth gate's policy scope: the held command's repo (same scope
        // that decided the hold); the daemon's own cwd when the id is unknown.
        let cwd = self
            .log
            .pending_command(id)
            .ok()
            .flatten()
            .map(|c| c.cwd)
            .unwrap_or_else(|| {
                std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
            });
        let require_proof = load_policy(&cwd).require_approval_proof();

        let vault = match self.current_vault() {
            VaultState::Degraded(_) => {
                self.record_admin(&op, false, "vault degraded");
                return ipc::Response::Error {
                    message: "admin vault is degraded; refusing privileged operations".into(),
                };
            }
            // Unprovisioned: no lock exists, so a bare approval is allowed —
            // the exact shutdown mirror.
            VaultState::Unprovisioned => {
                self.record_admin(&op, true, "unprovisioned");
                return self.resolve_pending_response(id, Decision::Allow);
            }
            VaultState::Locked(v) => v,
        };
        // Brute-force lockout, shared with shutdown auth (same bounds) and gated on
        // a proof actually being offered: a bare approve cannot guess a secret, so
        // counting it would hand any local peer a DoS on the human's own approval
        // and shutdown workflow. A success resets the shared budget.
        let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
        if proof_offered {
            if let Some(rem) = self.throttle.borrow().lockout_remaining() {
                self.record_admin(&op, false, "locked out");
                return ipc::Response::Error {
                    message: format!(
                        "too many failed attempts; locked out for {}s",
                        rem.as_secs() + 1
                    ),
                };
            }
        }
        // Absence is None, never an empty string: a placeholder must never
        // stand in for a real nonce/proof in the crypto path.
        let nonce_hex = nonce_hex.filter(|s| !s.trim().is_empty());
        let proof_hex = proof_hex.filter(|s| !s.trim().is_empty());
        match (nonce_hex, proof_hex) {
            // Bare under the opt-out: the pre-Phase-7 behavior, restored — but
            // never silent. An approval that reached the queue without proof is
            // exactly what a human reading the timeline must be able to see, so
            // it writes its own audit row; the log can never show this as
            // `human:allow` with nothing behind it.
            (None, None) if !require_proof => {
                self.record_admin(&op, true, "policy-opt-out");
                self.resolve_pending_response(id, Decision::Allow)
            }
            // Bare under the default: the self-approval attempt. Loud and audited —
            // never silent. Deliberately NOT counted against the brute-force budget:
            // it carries no proof, so it cannot be guessing, and counting it would
            // let one such request per window lock the human out of approving.
            (None, None) => {
                self.record_admin(&op, false, "self-approval blocked");
                ipc::Response::Error {
                    message: format!(
                        "approval requires proof — run `kintsugi approve {id}` (or \
                          `kintsugi run {id}`) and enter the admin password; see \
                          docs/policy.md to allow bare approval"
                    ),
                }
            }
            // The one-shot challenge is consumed regardless of the outcome.
            (Some(nonce_hex), Some(proof_hex)) => {
                let pending = self.pending.borrow_mut().take();
                let ok = match pending {
                    Some((issued_nonce, issued_op)) => {
                        match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
                            (Ok(nonce), Ok(proof)) => {
                                issued_op == op
                                    && issued_nonce == nonce
                                    && vault.verify_proof(&nonce, op.as_bytes(), &proof)
                            }
                            _ => false,
                        }
                    }
                    None => false,
                };
                if ok {
                    self.throttle.borrow_mut().reset();
                    self.record_admin(&op, true, "authenticated");
                    self.resolve_pending_response(id, Decision::Allow)
                } else {
                    self.throttle.borrow_mut().record_failure();
                    // Distinguish a wrong password from a vault that simply
                    // can't carry a proof (pre-v2): the latter fails for every
                    // password, so point at the one-line fix instead.
                    if !vault.supports_proof() {
                        self.record_admin(&op, false, "vault missing proof key");
                        return ipc::Response::Error {
                            message: "admin vault has no auth key — re-run `kintsugi admin \
                                  provision --force` (the daemon picks it up immediately, no \
                                  restart needed)"
                                .into(),
                        };
                    }
                    self.record_admin(&op, false, "authentication failed");
                    ipc::Response::Error {
                        message: "authentication failed".into(),
                    }
                }
            }
            // Half an attempt (a nonce without a proof or vice versa): not
            // bare, and not a proof — count it as a failed attempt.
            _ => {
                self.throttle.borrow_mut().record_failure();
                self.record_admin(&op, false, "authentication failed");
                ipc::Response::Error {
                    message: "authentication failed".into(),
                }
            }
        }
    }

    /// Record a privileged-operation attempt as a hash-chained audit event, so a
    /// forced stop — successful or not — is always visible on the timeline.
    fn record_admin(&self, op: &str, ok: bool, reason: &str) {
        // `op` is caller-supplied (`approve:<id>`) and lands in the append-only,
        // never-deletable event log, so it is validated and bounded here: without
        // this, any local peer could write attacker-chosen, unredacted text of up
        // to MAX_FRAME bytes into the audit trail on every refused attempt.
        let op = sanitize_op(op);
        let op = op.as_str();
        let raw = format!(
            "admin {op} — {}",
            if ok { "authenticated" } else { "denied" }
        );
        let cmd = ProposedCommand::new(
            "admin",
            std::path::Path::new("."),
            vec!["admin".to_string(), op.to_string()],
            raw,
        );
        let decision = if ok { Decision::Allow } else { Decision::Deny };
        let verdict = Verdict::rules(
            kintsugi_core::Class::Safe,
            decision,
            format!("admin:{op}:{reason}"),
        );
        let _ = self.log.log_event(&cmd, &verdict, None);
    }

    /// Whether the panic kill-switch is currently engaged.
    pub fn kill_switch_engaged(&self) -> bool {
        self.kill_path.exists()
    }

    /// The directory snapshots are stored under.
    pub fn snapshot_dir(&self) -> &std::path::Path {
        &self.snapshot_dir
    }

    /// Swap in a specific scorer (used by tests).
    pub fn with_scorer(mut self, scorer: Box<dyn kintsugi_model::Scorer>) -> Self {
        self.scorer = scorer;
        self
    }

    /// The name of the active Tier-2 scorer backend.
    pub fn scorer_name(&self) -> &str {
        self.scorer.name()
    }

    /// Open the daemon at the default database path.
    pub fn open_default() -> Result<Self> {
        Self::open(default_db_path())
    }

    /// Set the operating mode (attended / unattended / notify).
    pub fn with_mode(mut self, mode: Mode) -> Self {
        self.mode = mode;
        self
    }

    /// The current operating mode.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// Decide what to do with a proposed command.
    ///
    /// Order: (1) load the effective policy (global ← repo) which may set the mode
    /// and risk threshold; (2) classify with the Tier-1 rule engine; (3) **Tier-2
    /// model** — for the ambiguous band only, fill `summary`+`risk` and, in
    /// unattended mode, apply the graduated threshold (below → allow, at/above →
    /// deny); the model summarizes a catastrophic command for the hold card but
    /// never changes its decision; (4) apply policy allow/deny (never a
    /// catastrophic downgrade); (5) apply decision memory.
    ///
    /// Security spine: rules classify; the model only explains and scores the
    /// ambiguous band, and its influence is escalation-only. Safe stays on the
    /// model-free fast path.
    pub fn decide(&self, cmd: &ProposedCommand) -> Verdict {
        // Panic kill-switch: halt everything, including Safe, the instant it is
        // engaged. Checked first, before any other logic.
        if self.kill_switch_engaged() {
            let m = kintsugi_core::classify(cmd);
            return Verdict::rules(m.class, Decision::Deny, "kill-switch: all actions halted");
        }

        let policy = load_policy(&cmd.cwd);
        let mode = policy.mode.unwrap_or(self.mode);

        let m = kintsugi_core::classify(cmd);
        // Provenance (Phase 6): apply the trifecta as a deterministic class floor
        // (escalation-only) before the model ever runs. Taint never downgrades.
        let (class, rule) = self.trifecta_floor(cmd, &policy, m.class, m.rule);
        let mut verdict = Verdict::rules(class, kintsugi_core::decide(class, mode), &rule);

        // Tier-2 model: ambiguous band gets summary + risk (+ graduated decision);
        // catastrophic gets a summary for the hold card. Safe is never scored.
        match class {
            kintsugi_core::Class::Ambiguous => {
                // Phase 6 V1.1 · hardening item H: in the ambiguous TAINT band —
                // where the provenance floor engaged at the partial level — the
                // Tier-2 step gains a deterministic, advisory dependency hint:
                // does this command plausibly consume an identifier from the
                // session's untrusted trail? Pure string matching (no inference,
                // no I/O), so it adds no scoring call and cannot bypass the
                // recorder's ScoreBudget. Escalation-only (spine #2): the hint
                // may turn the attended Hold into a Deny; it can never unlock or
                // downgrade anything, and the human paths below (policy
                // allowlist, decision memory) still have the final say.
                let hint = self.dependency_hint(cmd, &policy);
                let out = self.scorer.score_with_hint(cmd, class, &rule, hint);
                verdict.summary = Some(out.summary);
                verdict.risk = Some(out.risk);
                verdict.tier = 2;
                if mode == Mode::Unattended {
                    // Spine rule #2 (monotonic model influence): the model may only
                    // ADD caution. The unattended baseline for an ambiguous command
                    // is Deny (queued for a human); the model records risk for that
                    // review but NEVER downgrades Deny -> Allow. Auto-proceeding an
                    // ambiguous command unattended is only possible via an explicit
                    // human allowlist (.kintsugi.toml / decision memory) below — a human
                    // decision, not the model's. The hint changes nothing here.
                    verdict.reason = format!(
                        "model:risk={} ({}) — unattended holds ambiguous for review",
                        out.risk, rule
                    );
                } else if hint == DependencyHint::LikelyDependent
                    && verdict.decision == Decision::Hold
                {
                    // The advisory escalation: Hold -> Deny, marked for audit.
                    // `advisory:dependent` appears in a reason ONLY here.
                    verdict.decision = Decision::Deny;
                    verdict.reason = format!("advisory:dependent ({})", verdict.reason);
                }
            }
            kintsugi_core::Class::Catastrophic => {
                let out = self.scorer.score(cmd, class, &rule);
                verdict.summary = Some(out.summary);
                verdict.tier = 2;
            }
            kintsugi_core::Class::Safe => {}
        }

        // Policy can escalate (deny) or tame (allow) — never downgrade catastrophic.
        let action = policy.action_for(&cmd.raw);
        verdict = kintsugi_core::adjust_for_policy(verdict, action, mode);

        // Decision memory has the final say — but, like policy, it can never
        // auto-downgrade a CATASTROPHIC command (that hard floor only lifts via an
        // in-the-moment human decision, never a stored/replayed one). Memory deny
        // always applies (escalation-only).
        let repo = repo_key(&cmd.cwd);
        let hash = kintsugi_core::command_hash(&cmd.raw);
        match self.log.memory_lookup(&repo, &hash) {
            Ok(Some(Decision::Allow)) if verdict.class != kintsugi_core::Class::Catastrophic => {
                verdict.decision = Decision::Allow;
                verdict.reason = format!("memory:allow ({})", verdict.reason);
            }
            Ok(Some(Decision::Deny)) => {
                verdict.decision = Decision::Deny;
                verdict.reason = format!("memory:deny ({})", verdict.reason);
            }
            _ => {}
        }
        verdict
    }

    /// Handle one proposal: decide, snapshot if destructive+allowed, record, and —
    /// if held — enqueue it for approval. Returns the verdict.
    pub fn handle(&self, cmd: ProposedCommand) -> Verdict {
        let mut verdict = self.decide(&cmd);
        let (snapshot_id, snapshot_failed) = self.maybe_snapshot(&cmd, &verdict);
        if verdict.decision == Decision::Allow && verdict.class != kintsugi_core::Class::Safe {
            let note = if snapshot_failed {
                Some("snapshot failed — NOT reversible by undo")
            } else if !kintsugi_core::snapshot::is_fully_reversible(&cmd) {
                Some("target can't be fully snapshotted — undo may not restore everything")
            } else {
                None
            };
            if let Some(n) = note {
                verdict.reason = format!("{} [⚠ {n}]", verdict.reason);
            }
        }
        if let Err(e) = self.log.log_event(&cmd, &verdict, snapshot_id.as_deref()) {
            // Spine #4: a command we cannot write to the append-only log must not run
            // unrecorded. Fail closed — refuse an Allow rather than execute it dark.
            eprintln!("kintsugi-daemon: failed to record event: {e}");
            if verdict.decision == Decision::Allow {
                verdict.decision = Decision::Deny;
                verdict.reason = format!(
                    "audit-log write failed; denied fail-closed ({})",
                    verdict.reason
                );
            }
        }
        if verdict.decision == Decision::Hold && needs_queue_entry(&cmd, verdict.class) {
            if let Err(e) = self
                .log
                .enqueue_pending(&cmd, verdict.class, &verdict.reason)
            {
                eprintln!("kintsugi-daemon: failed to enqueue pending: {e}");
            }
        }
        // Negotiation is the LAST step so the audit log and the approval queue keep
        // the clean, rule-grounded reason; only the verdict returned to the agent
        // carries the model-facing instruction. This never changes the decision —
        // it only reframes a block — so it cannot unlock the gate (spine).
        self.negotiate(cmd.session.as_deref(), verdict)
    }

    /// Reframe a *blocked* verdict for the agent (model-facing reason + the
    /// "materially safer alternative / else ask the user" instruction) and drive the
    /// consecutive-denial circuit breaker. Allow/ask are returned unchanged; an
    /// Allow resets the session's streak. Decision-preserving by construction.
    fn negotiate(&self, session: Option<&str>, mut verdict: Verdict) -> Verdict {
        use kintsugi_core::Class;
        // The agent receives a hard "no" for a Deny, or for a catastrophic Hold (the
        // adapter maps that to deny — an in-agent allow would skip the snapshot). An
        // ambiguous Hold becomes a native `ask`, which is not a negotiation deny.
        let blocked = verdict.decision == Decision::Deny
            || (verdict.decision == Decision::Hold && verdict.class == Class::Catastrophic);
        if !blocked {
            if verdict.decision == Decision::Allow {
                if let Some(s) = session {
                    self.denial_streak.borrow_mut().remove(s);
                }
            }
            return verdict;
        }

        // Count consecutive blocks per session; an untracked session can't be
        // counted, so it just never trips (the reason is still grounded).
        let tripped = match session {
            Some(s) => {
                let mut streaks = self.denial_streak.borrow_mut();
                let count = streaks.entry(s.to_string()).or_insert(0);
                *count += 1;
                *count >= kintsugi_core::negotiate::CONSECUTIVE_DENY_LIMIT
            }
            None => false,
        };

        verdict.reason = if tripped {
            kintsugi_core::negotiate::circuit_breaker_reason(&verdict.reason)
        } else {
            kintsugi_core::negotiate::model_deny_reason(&verdict.reason)
        };
        verdict
    }

    /// Approve or deny a queued command by id: record the human decision (and, on
    /// allow, snapshot), then mark the queue entry resolved. The originating
    /// caller (MCP poll / shim) executes; this never runs the command itself.
    ///
    /// A human may approve any class here — including catastrophic — which is the
    /// deliberate human override (the *model* never can). Returns whether the id
    /// was found in the queue.
    pub fn resolve_pending(&self, id: &str, decision: Decision) -> Result<bool> {
        // While the kill-switch is engaged, nothing is approvable.
        if decision == Decision::Allow && self.kill_switch_engaged() {
            anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before approving");
        }
        let status = if decision == Decision::Allow {
            "approved"
        } else {
            "denied"
        };
        // Claim the entry exactly once. If the CAS doesn't win, the command was
        // already resolved (or never queued) — return false rather than snapshot
        // and log a second time, which is what would double-run an approved cmd.
        if !self.log.cas_pending_status(id, "pending", status)? {
            return Ok(false);
        }
        let Some(cmd) = self.log.pending_command(id)? else {
            return Ok(false);
        };
        self.resolve(&ipc::Resolution {
            command: cmd,
            decision,
            remember: false,
        })?;
        Ok(true)
    }

    /// Snapshot the paths a command will touch, when it is allowed and not Safe.
    /// Returns the snapshot id to attach to the event, if one was taken.
    fn maybe_snapshot(&self, cmd: &ProposedCommand, verdict: &Verdict) -> (Option<String>, bool) {
        if verdict.decision != Decision::Allow || verdict.class == kintsugi_core::Class::Safe {
            return (None, false);
        }
        match kintsugi_core::capture_snapshot(&self.snapshot_dir, cmd) {
            Ok(Some(manifest)) => {
                if let Err(e) = self.log.record_snapshot(&manifest) {
                    eprintln!("kintsugi-daemon: failed to record snapshot: {e}");
                    return (None, true);
                }
                (Some(manifest.id), false)
            }
            Ok(None) => (None, false),
            Err(e) => {
                eprintln!("kintsugi-daemon: snapshot failed: {e}");
                (None, true)
            }
        }
    }

    /// Handle a human's resolution of a held command: record the final decision
    /// and, if requested, remember it for this exact command in this repo.
    pub fn resolve(&self, resolution: &ipc::Resolution) -> Result<()> {
        // Kill-switch hard floor: while engaged, no Allow resolves — not via the
        // queue (resolve_pending) and not via this direct path (shim hold card /
        // raw Request::Resolve). Mirrors the guard in resolve_pending().
        if resolution.decision == Decision::Allow && self.kill_switch_engaged() {
            anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before allowing");
        }
        let cmd = &resolution.command;
        // Re-classify so the recorded class is accurate even though a human chose.
        let m = kintsugi_core::classify(cmd);
        // A catastrophic command is never *remembered* as always-allow — the hard
        // floor must re-prompt every time; `[r]` on a catastrophic acts as allow-once.
        let remember = resolution.remember
            && !(resolution.decision == Decision::Allow
                && m.class == kintsugi_core::Class::Catastrophic);
        let reason = match resolution.decision {
            Decision::Allow if remember => "human:always-allow",
            Decision::Allow => "human:allow",
            Decision::Deny if remember => "human:always-deny",
            Decision::Deny => "human:deny",
            Decision::Hold => "human:hold",
        };
        let verdict = Verdict::rules(m.class, resolution.decision, reason);
        // Snapshot before a human-approved destructive command runs.
        let (snapshot_id, _) = self.maybe_snapshot(cmd, &verdict);
        self.log.log_event(cmd, &verdict, snapshot_id.as_deref())?;

        if remember && resolution.decision != Decision::Hold {
            let repo = repo_key(&cmd.cwd);
            let hash = kintsugi_core::command_hash(&cmd.raw);
            self.log.remember(&repo, &hash, resolution.decision)?;
        }

        // If this command was queued (e.g. a shim hold the human just answered),
        // mark the queue entry resolved so it leaves `kintsugi queue`.
        if resolution.decision != Decision::Hold {
            let status = if resolution.decision == Decision::Allow {
                "approved"
            } else {
                "denied"
            };
            let _ = self.log.set_pending_status(&cmd.id.to_string(), status);
        }
        Ok(())
    }

    /// Record an observed filesystem change from the backstop watcher. Logged as
    /// `agent = "fs-watch"`, decision Allow (it already happened) — its purpose is
    /// to keep the timeline and undo complete for actions that bypassed
    /// interception.
    pub fn observe(&self, obs: &ipc::Observation) -> Result<()> {
        let raw = format!("{} {}", obs.kind, obs.path);
        let cwd = std::path::Path::new(&obs.path)
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_default();
        let cmd = ProposedCommand::new(
            "fs-watch",
            cwd,
            vec![obs.kind.clone(), obs.path.clone()],
            raw,
        );
        let verdict = Verdict::rules(
            kintsugi_core::Class::Safe,
            Decision::Allow,
            format!("fs:{}", obs.kind),
        );
        self.log.log_event(&cmd, &verdict, None)?;
        Ok(())
    }

    /// Record a shell command from a human shell session (passive recording, no
    /// AI-agent hook). Logged as `agent = "shell"`, decision Allow — it is never
    /// blocked (the recorder is an audit/undo trail, not a gate). We **classify**
    /// it with the Tier-1 rules so the event carries the real class (a destructive
    /// command a DBA ran is flagged in the timeline and `kintsugi report`), and we
    /// **snapshot destructive commands** so `kintsugi undo` can recover a human's
    /// mistake. The model never runs on this path.
    ///
    /// The hard floor stays honest: this is an audit record of the past, not a
    /// gate. The "nothing un-warned" guarantee never applied to commands a human
    /// ran outside Kintsugi; the "tamper-evident record of everything" one does,
    /// which is exactly what this preserves.
    pub fn record_shell(&self, cmd: &ProposedCommand) -> Result<()> {
        // Provenance: the recorder is for human shell sessions, so force the agent
        // label to "shell" regardless of what the caller sent. A local peer that
        // can reach the socket therefore cannot forge a record attributed to an
        // AI agent ("claude-code") or the watcher ("fs-watch"); the worst it can
        // do is inject a self-reported *shell* event, which the Audit view treats
        // accordingly. (The socket is already owner-only; this is defense in depth.)
        let mut cmd = cmd.clone();
        cmd.agent = "shell".to_string();
        let m = kintsugi_core::classify(&cmd);
        // Allow, not the rule's gate decision: the command already executed, so
        // recording a Hold/Deny here would be a lie about what happened. The
        // class still rides along (verdict.class) so the timeline flags danger.
        let mut verdict = Verdict::rules(m.class, Decision::Allow, format!("recorded:{}", m.rule));
        // Score risky commands with the model so the Recorder rows and the
        // details drawer can show a plain-English summary alongside the raw
        // command. The decision stays Allow — this is just metadata on a row
        // that's already an audit record of the past.
        //
        // The model call is one synchronous inference on the single-threaded
        // serve loop, so it's spent against a token-bucket budget: under a flood
        // of risky records the budget empties and we record the row *without* the
        // summary rather than let the recorder serialize unbounded inference and
        // starve real hold/approve traffic. The class still rides in verdict.class
        // either way, so the timeline never loses the danger signal — only the
        // cosmetic prose. (Safe commands never score, so they never spend.)
        let may_score = !matches!(m.class, kintsugi_core::Class::Safe)
            && self
                .score_budget
                .borrow_mut()
                .try_spend(std::time::Instant::now());
        if may_score {
            let out = self.scorer.score(&cmd, m.class, &m.rule);
            verdict.summary = Some(out.summary);
            verdict.tier = 2;
            if m.class == kintsugi_core::Class::Ambiguous {
                verdict.risk = Some(out.risk);
            }
        } else if m.class != kintsugi_core::Class::Safe {
            // Budget shed: keep the danger tier on the row even without prose.
            verdict.tier = 2;
        }
        // Recoverer: snapshot the paths a *destructive* human command will touch,
        // so `kintsugi undo` can roll back a person's *filesystem* mistake (rm -rf,
        // a clobbering overwrite) the same way it rolls back an agent's. The shell
        // preexec hook fires before the command runs, so this is a just-in-time
        // capture; `maybe_snapshot` no-ops for Safe commands and reflinks where it
        // can, so the common case stays cheap. Best-effort: if the snapshot loses
        // the race (or the fs can't reflink), the filesystem-watcher backstop still
        // records the change. This is a filesystem recoverer — an in-database
        // DROP/TRUNCATE is not a file, so it's flagged/recorded but recovery there
        // is your DB's PITR/backups. The honest guarantee is "recoverable", not
        // transactional.
        let (snapshot_id, _) = self.maybe_snapshot(&cmd, &verdict);
        self.log.log_event(&cmd, &verdict, snapshot_id.as_deref())?;
        Ok(())
    }

    /// Dispatch an IPC request to its handler.
    pub fn handle_request(&self, req: ipc::Request) -> ipc::Response {
        match req {
            ipc::Request::Propose(cmd) => ipc::Response::Verdict(self.handle(cmd)),
            ipc::Request::Resolve(resolution) => match self.resolve(&resolution) {
                Ok(()) => ipc::Response::Ack,
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            ipc::Request::Observe(obs) => match self.observe(&obs) {
                Ok(()) => ipc::Response::Ack,
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            // Observation only labels — it never blocks and can't fail the caller:
            // apply_taint persists best-effort and redacts the source_id (segment G).
            ipc::Request::Ingest(observed) => {
                self.apply_taint(&observed.into_taint_event());
                ipc::Response::Ack
            }
            // Observation only: a write labels the path for future readers. It
            // never blocks, never enqueues, and never touches a command verdict.
            ipc::Request::WriteObserved { session, path, cwd } => {
                self.apply_write(&session, &path, &cwd);
                ipc::Response::Ack
            }
            // The reader half: a read of a labelled path taints the reader.
            ipc::Request::ReadObserved { session, path, cwd } => {
                self.apply_read(&session, &path, &cwd);
                ipc::Response::Ack
            }
            ipc::Request::Provenance(cmd) => ipc::Response::Provenance {
                tainted: self.is_session_tainted(cmd.session.as_deref()),
                trail: self.provenance_trail(&cmd),
            },
            ipc::Request::Record(cmd) => match self.record_shell(&cmd) {
                Ok(()) => ipc::Response::Ack,
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            ipc::Request::ListPending => match self.log.list_pending() {
                Ok(items) => ipc::Response::PendingList { items },
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            ipc::Request::PendingStatus { id } => match self.log.pending_status(&id) {
                Ok(status) => ipc::Response::Pending {
                    status: status.unwrap_or_else(|| "gone".to_string()),
                },
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            // Proof-of-human approval (Phase 7): authenticated on a locked
            // daemon, audited + throttled when bare. `Deny`/`PrunePending`
            // stay bare by design (nuisance, not threat / queue-only).
            ipc::Request::Approve { id, nonce, proof } => {
                self.approve_op(&id, nonce.as_deref(), proof.as_deref())
            }
            ipc::Request::Deny { id } => self.resolve_pending_response(&id, Decision::Deny),
            ipc::Request::PrunePending => match self.log.prune_pending() {
                Ok(n) => ipc::Response::Pending {
                    status: n.to_string(),
                },
                Err(e) => ipc::Response::Error {
                    message: e.to_string(),
                },
            },
            ipc::Request::Status => ipc::Response::Status {
                scorer: self.scorer_name().to_string(),
            },
            ipc::Request::AuthBegin { op } => self.auth_begin(&op),
            ipc::Request::Shutdown { op, nonce, proof } => {
                self.shutdown_op(&op, nonce.as_deref(), proof.as_deref())
            }
        }
    }

    fn resolve_pending_response(&self, id: &str, decision: Decision) -> ipc::Response {
        match self.resolve_pending(id, decision) {
            Ok(true) => ipc::Response::Ack,
            Ok(false) => ipc::Response::Error {
                message: format!("no pending command with id {id}"),
            },
            Err(e) => ipc::Response::Error {
                message: e.to_string(),
            },
        }
    }

    /// Borrow the underlying event log (read-only queries).
    pub fn log(&self) -> &EventLog {
        &self.log
    }
}

/// Load and merge the effective policy for a command's working directory:
/// global defaults (config dir) overridden by the repo's `.kintsugi.toml`.
pub fn load_policy(cwd: &std::path::Path) -> kintsugi_core::Policy {
    let global = read_policy_file(&global_policy_path()).unwrap_or_default();
    let repo = find_repo_policy(cwd)
        .and_then(|p| read_policy_file(&p))
        .unwrap_or_default();
    kintsugi_core::Policy::merge(global, repo)
}

/// Path to the global policy file. Override with `KINTSUGI_CONFIG` (used in tests).
fn global_policy_path() -> PathBuf {
    if let Ok(p) = std::env::var("KINTSUGI_CONFIG") {
        return PathBuf::from(p);
    }
    if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
        return dirs.config_dir().join("config.toml");
    }
    std::env::temp_dir().join("kintsugi-config.toml")
}

/// Find the nearest `.kintsugi.toml` from `cwd` upward.
fn find_repo_policy(cwd: &std::path::Path) -> Option<PathBuf> {
    let mut dir = Some(cwd);
    while let Some(d) = dir {
        let candidate = d.join(".kintsugi.toml");
        if candidate.is_file() {
            return Some(candidate);
        }
        dir = d.parent();
    }
    None
}

fn read_policy_file(path: &std::path::Path) -> Option<kintsugi_core::Policy> {
    let text = std::fs::read_to_string(path).ok()?;
    match kintsugi_core::Policy::parse(&text) {
        Ok(p) => Some(p),
        Err(e) => {
            eprintln!(
                "kintsugi-daemon: ignoring invalid policy {}: {e}",
                path.display()
            );
            None
        }
    }
}

/// Identify the "repo" a command runs in: the nearest ancestor containing a
/// `.git` directory, else the working directory itself.
pub fn repo_key(cwd: &std::path::Path) -> String {
    let mut dir = Some(cwd);
    while let Some(d) = dir {
        if d.join(".git").exists() {
            return d.to_string_lossy().to_string();
        }
        dir = d.parent();
    }
    cwd.to_string_lossy().to_string()
}

/// Run the daemon: open the default log, bind the socket, serve forever.
pub fn run() -> Result<()> {
    let daemon = Daemon::open_default()?;
    let server = Server::bind()?;
    // Record our PID so `kintsugi stop` can find and stop us (any launch path).
    let _ = std::fs::write(pid_file_path(), std::process::id().to_string());
    eprintln!(
        "kintsugi-daemon {} listening on {}",
        VERSION,
        Server::endpoint().display()
    );
    server.serve_until(
        |req| daemon.handle_request(req),
        || daemon.should_shutdown(),
    )?;
    // An authenticated shutdown landed: clean up the PID file and exit.
    let _ = std::fs::remove_file(pid_file_path());
    eprintln!("kintsugi-daemon: authenticated shutdown — exiting.");
    Ok(())
}

/// Path to the daemon's PID file (next to the event log).
pub fn pid_file_path() -> PathBuf {
    default_db_path().with_file_name("kintsugi.pid")
}

#[cfg(test)]
mod queue_entry_tests {
    use super::needs_queue_entry;
    use kintsugi_core::{Class, ProposedCommand};

    fn cmd(agent: &str) -> ProposedCommand {
        ProposedCommand::new(
            agent,
            std::path::Path::new("/tmp"),
            vec!["rm".into(), "x".into()],
            "rm x",
        )
    }

    #[test]
    fn catastrophic_always_enqueues() {
        for a in [
            "claude-code",
            "qwen",
            "gemini",
            "mcp",
            "opencode",
            "anything",
        ] {
            assert!(
                needs_queue_entry(&cmd(a), Class::Catastrophic),
                "catastrophic must queue for {a}"
            );
        }
    }

    #[test]
    fn ambiguous_skips_only_native_ask_agents() {
        // Native ask → resolved by the agent's own prompt, so NO queue entry.
        for a in ["claude-code", "qwen", "copilot", "cursor", "codex"] {
            assert!(
                !needs_queue_entry(&cmd(a), Class::Ambiguous),
                "{a} has native ask → no queue orphan"
            );
        }
        // No native ask → the human resolves via the queue, so it MUST enqueue.
        for a in ["gemini", "antigravity", "opencode", "mcp", "future-agent"] {
            assert!(
                needs_queue_entry(&cmd(a), Class::Ambiguous),
                "{a} has no prompt → must queue"
            );
        }
    }
}

#[cfg(test)]
mod score_budget_tests {
    use super::ScoreBudget;
    use std::time::{Duration, Instant};

    #[test]
    fn burst_is_bounded_then_refills_at_the_steady_rate() {
        let t0 = Instant::now();
        // Capacity 8, refill 4/sec.
        let mut b = ScoreBudget::new(8.0, 4.0, t0);

        // A flood at t0 spends the whole burst and no more — the 9th is shed, so
        // a recorder flood can never serialize unbounded inference on the loop.
        for i in 0..8 {
            assert!(b.try_spend(t0), "burst token {i} should be granted");
        }
        assert!(!b.try_spend(t0), "9th in the same instant must be shed");

        // After 1s, 4 tokens have refilled (the steady ceiling) — not the full 8.
        let t1 = t0 + Duration::from_secs(1);
        for i in 0..4 {
            assert!(b.try_spend(t1), "refilled token {i} should be granted");
        }
        assert!(!b.try_spend(t1), "refill is rate-capped, not a full reset");
    }

    #[test]
    fn refill_never_exceeds_capacity() {
        let t0 = Instant::now();
        let mut b = ScoreBudget::new(8.0, 4.0, t0);
        for _ in 0..8 {
            assert!(b.try_spend(t0));
        }
        // Idle far longer than it takes to refill — tokens cap at `capacity`, so a
        // long-quiet session banks a burst of 8, never an unbounded backlog.
        let later = t0 + Duration::from_secs(3600);
        for i in 0..8 {
            assert!(b.try_spend(later), "banked token {i} after a long idle");
        }
        assert!(
            !b.try_spend(later),
            "cap holds: no more than `capacity` banked"
        );
    }
}