kintsugi_daemon/lib.rs
1//! Kintsugi resident daemon library.
2//!
3//! Long-lived process that owns the event log and runs the decision loop. The
4//! interception layer connects over a local socket, sends a [`ProposedCommand`],
5//! and blocks on the returned [`Verdict`].
6//!
7//! In Phase 0 the daemon is a pure recorder: it logs every proposal and allows
8//! it. The Tier-1 rule engine (Phase 1) plugs into [`Daemon::decide`] without
9//! changing the IPC or logging paths.
10
11#![forbid(unsafe_code)]
12
13pub mod ipc;
14pub mod watch;
15
16use std::path::PathBuf;
17
18use std::cell::{Cell, RefCell};
19
20use anyhow::{Context, Result};
21use directories::ProjectDirs;
22use kintsugi_core::admin::{self, VaultState};
23use kintsugi_core::{Decision, EventLog, Mode, ProposedCommand, TaintEvent, TaintState, Verdict};
24
25pub use ipc::{Client, Observation, Resolution, Server};
26
27pub const VERSION: &str = env!("CARGO_PKG_VERSION");
28
29/// The kill-switch flag file name, alongside the event-log database.
30pub const KILL_SWITCH_FILE: &str = "panic.flag";
31
32/// Path to the panic kill-switch flag (alongside the default event log).
33pub fn kill_switch_path() -> PathBuf {
34 default_db_path()
35 .parent()
36 .map(|p| p.join(KILL_SWITCH_FILE))
37 .unwrap_or_else(|| std::env::temp_dir().join(KILL_SWITCH_FILE))
38}
39
40/// The fail-closed marker file name, alongside the event-log database.
41pub const FAIL_CLOSED_FILE: &str = "fail-closed.flag";
42
43/// Path to the fail-closed marker (alongside the default event log). Its mere
44/// existence is the signal — the content is irrelevant. The interception layer
45/// (shim/hook/MCP) reads it **without** the daemon, so that killing the daemon
46/// can't be used to open the gate: with the marker present, an unreachable
47/// daemon means *block*, not *run unguarded*.
48pub fn fail_closed_marker_path() -> PathBuf {
49 default_db_path().with_file_name(FAIL_CLOSED_FILE)
50}
51
52/// Whether the admin-set fail-closed marker is present. Cheap, daemon-free, and
53/// callable from the interception fast path. In the locked posture the marker is
54/// owned by the privileged account (root / a dedicated `kintsugi` user), so an
55/// audited non-root agent cannot remove it to re-open the gate.
56pub fn is_fail_closed_marked() -> bool {
57 fail_closed_marker_path().exists()
58}
59
60/// Create or remove the fail-closed marker to match `on`. Best-effort, atomic
61/// create; called by the admin flow when the locked `fail_closed` setting
62/// changes so the posture survives a daemon restart and a kill.
63pub fn set_fail_closed_marker(on: bool) -> std::io::Result<()> {
64 let path = fail_closed_marker_path();
65 if on {
66 if let Some(parent) = path.parent() {
67 std::fs::create_dir_all(parent)?;
68 }
69 // 0644: world-readable (the shim must read it) but, in the locked posture,
70 // owned by the privileged account so the audited user can't delete it.
71 std::fs::write(&path, b"fail-closed\n")?;
72 } else if path.exists() {
73 std::fs::remove_file(&path)?;
74 }
75 Ok(())
76}
77
78/// Resolve the event-log database path. Override with `KINTSUGI_DB` (handy in tests).
79pub fn default_db_path() -> PathBuf {
80 if let Ok(p) = std::env::var("KINTSUGI_DB") {
81 return PathBuf::from(p);
82 }
83 if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
84 return dirs.data_dir().join("events.db");
85 }
86 std::env::temp_dir().join("kintsugi-events.db")
87}
88
89/// The resident decision loop: owns the event log, the warm scorer, classifies,
90/// records.
91pub struct Daemon {
92 log: EventLog,
93 mode: Mode,
94 scorer: Box<dyn kintsugi_model::Scorer>,
95 snapshot_dir: PathBuf,
96 kill_path: PathBuf,
97 /// The admin vault **path**, resolved once at daemon startup from the path the
98 /// daemon itself chose (a caller's environment can't redirect it). The vault
99 /// *contents* are read fresh from this path on every privileged op
100 /// ([`current_vault`](Self::current_vault)) — never cached — so a re-provision
101 /// or password change applies immediately, with no restart and no stale-copy bug.
102 vault_path: PathBuf,
103 /// The last challenge nonce issued (and its op), consumed once by `Shutdown`.
104 pending: RefCell<Option<(Vec<u8>, String)>>,
105 /// Set when an authenticated shutdown has been accepted; the serve loop exits.
106 shutdown: Cell<bool>,
107 /// In-memory brute-force throttle for admin authentication.
108 throttle: RefCell<AuthThrottle>,
109 /// Session/file information-flow (taint) state for the Provenance feature.
110 /// Event-sourced ([`TaintState`]): every transition is persisted to the
111 /// durable taint stream and the state is rebuilt by replaying it on a cold
112 /// start (see [`open`](Self::open)), so taint survives a daemon restart
113 /// (Phase 6 hardening item D — closes the fail-open-on-restart gap).
114 taint: RefCell<TaintState>,
115 /// Consecutive-block counter per session for the negotiation circuit breaker
116 /// (Phase 6). The hook is one-shot per tool call, so this resident state is the
117 /// only place that can count an agent retrying a blocked action across calls.
118 denial_streak: RefCell<std::collections::HashMap<String, u32>>,
119 /// Caps how much model-inference time the recorder path can impose on the
120 /// single-threaded serve loop, so a flood of risky shell records can't starve
121 /// real hold/approve traffic. See [`ScoreBudget`].
122 score_budget: RefCell<ScoreBudget>,
123}
124
125/// Rate-limit + lockout for admin authentication. The daemon is the single
126/// authority, so a process-local counter is enough: after a few consecutive
127/// failures it locks out for an exponentially growing window (defeating a script
128/// hammering the admin password), and a success resets it.
129#[derive(Default)]
130struct AuthThrottle {
131 failures: u32,
132 locked_until: Option<std::time::Instant>,
133}
134
135impl AuthThrottle {
136 /// Failed attempts allowed before the first lockout.
137 const FREE_ATTEMPTS: u32 = 5;
138
139 /// Remaining lockout duration, if currently locked out.
140 fn lockout_remaining(&self) -> Option<std::time::Duration> {
141 self.locked_until
142 .and_then(|t| t.checked_duration_since(std::time::Instant::now()))
143 }
144
145 /// Count a failed attempt; arm/extend the lockout once past the free budget.
146 fn record_failure(&mut self) {
147 self.failures = self.failures.saturating_add(1);
148 if self.failures >= Self::FREE_ATTEMPTS {
149 // 30s, then doubling (60s, 120s, …) capped at one hour.
150 let over = (self.failures - Self::FREE_ATTEMPTS).min(7);
151 self.locked_until = Some(
152 std::time::Instant::now()
153 + std::time::Duration::from_secs((30u64 << over).min(3600)),
154 );
155 }
156 }
157
158 fn reset(&mut self) {
159 self.failures = 0;
160 self.locked_until = None;
161 }
162}
163
164/// Token-bucket budget for the *model scoring* on the recorder path.
165///
166/// The IPC serve loop is single-threaded: it reads one request, handles it to
167/// completion, then accepts the next. `record_shell` scores risky shell events
168/// with the local model so the Recorder rows can show a plain-English summary —
169/// but that scoring is one synchronous inference on the serve thread. A local
170/// peer (a runaway or compromised agent — the socket is owner-only, but that's
171/// exactly who we defend against) that floods the socket with risky `Observe`
172/// records would serialize one inference each and starve real hold/approve
173/// traffic, blinding the user's safety control plane. Crucially, that scoring is
174/// *cosmetic*: `record_shell` always records `Allow` (the command already ran),
175/// and the danger `class` rides along regardless. So under sustained load we
176/// shed the summary, not the record — the row is still logged with its class,
177/// just without the prose. `capacity` is the burst a quiet session banks;
178/// `refill_per_sec` is the steady ceiling on inferences/sec the recorder can
179/// impose on the serve thread.
180struct ScoreBudget {
181 tokens: f64,
182 capacity: f64,
183 refill_per_sec: f64,
184 last: std::time::Instant,
185}
186
187impl ScoreBudget {
188 fn new(capacity: f64, refill_per_sec: f64, now: std::time::Instant) -> Self {
189 Self {
190 tokens: capacity,
191 capacity,
192 refill_per_sec,
193 last: now,
194 }
195 }
196
197 /// Refill for elapsed time, then try to spend one token. Returns `false` when
198 /// the budget is exhausted — the caller skips the expensive scoring and falls
199 /// back to a rules-only (summary-less) record.
200 fn try_spend(&mut self, now: std::time::Instant) -> bool {
201 let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
202 self.last = now;
203 self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
204 if self.tokens >= 1.0 {
205 self.tokens -= 1.0;
206 true
207 } else {
208 false
209 }
210 }
211}
212
213/// Agents whose CLI shows a WORKING interactive y/N prompt for an ambiguous
214/// hold. For these, the hold is resolved by the agent's own UI, so a daemon
215/// queue entry would just orphan (no one ever calls `resolve_pending`).
216///
217/// Everyone else — Gemini, Antigravity, OpenCode (its plugin throws on `ask`),
218/// the `kintsugi-exec` MCP tool, and any future/unknown surface — has no
219/// interactive prompt, so the human resolves the hold via the queue (the Held
220/// screen / `kintsugi queue` / `approve`). Default to enqueueing, so a new
221/// agent never silently drops a hold the user can't recover.
222const AGENTS_WITH_NATIVE_ASK: &[&str] = &["claude-code", "qwen", "copilot", "cursor", "codex"];
223
224/// Does THIS held command need a daemon-side queue entry?
225///
226/// Catastrophic always does (the dialect maps Hold→Deny, so the agent can't
227/// resolve it and the human runs it via `kintsugi run`). Ambiguous needs one
228/// for every agent EXCEPT those with a working native ask — see the constant.
229fn needs_queue_entry(cmd: &ProposedCommand, class: kintsugi_core::Class) -> bool {
230 if class == kintsugi_core::Class::Catastrophic {
231 return true;
232 }
233 !AGENTS_WITH_NATIVE_ASK.contains(&cmd.agent.as_str())
234}
235
236impl Daemon {
237 /// Open the daemon backed by the event log at `db_path`, creating parent dirs.
238 pub fn open(db_path: impl Into<PathBuf>) -> Result<Self> {
239 let db_path = db_path.into();
240 if let Some(parent) = db_path.parent() {
241 std::fs::create_dir_all(parent)
242 .with_context(|| format!("create data dir {}", parent.display()))?;
243 }
244 let data_dir = db_path
245 .parent()
246 .unwrap_or_else(|| std::path::Path::new("."))
247 .to_path_buf();
248 // Keep the data dir private to the owning user: the event log records raw
249 // commands verbatim (spine #3), which can include secrets passed on a
250 // command line. We never scrub the verbatim record, so we protect it at
251 // rest (0700 dir, 0600 db) instead of leaving it world-readable.
252 #[cfg(unix)]
253 ipc::set_mode(&data_dir, 0o700);
254 let snapshot_dir = data_dir.join("snapshots");
255 let kill_path = data_dir.join(KILL_SWITCH_FILE);
256 let log = EventLog::open(&db_path)
257 .with_context(|| format!("open event log at {}", db_path.display()))?;
258 // Owner-only on the db (and its WAL/SHM siblings) — it holds verbatim
259 // commands that may contain secrets.
260 #[cfg(unix)]
261 for suffix in ["", "-wal", "-shm"] {
262 let p = if suffix.is_empty() {
263 db_path.clone()
264 } else {
265 PathBuf::from(format!("{}{suffix}", db_path.display()))
266 };
267 if p.exists() {
268 ipc::set_mode(&p, 0o600);
269 }
270 }
271 // Resolve the admin vault path here at startup (the daemon is launched by
272 // the admin/systemd, so its environment — not a later caller's — decides the
273 // location). The contents are read fresh per op, never cached.
274 let vault_path = admin::default_vault_path();
275 // Rebuild information-flow taint by replaying the durable taint stream, so
276 // a restart reconstructs taint instead of failing open (Provenance item D).
277 // A load failure degrades to empty taint rather than aborting startup, but
278 // is logged loudly — the base rules and the rest of the daemon still run.
279 let taint = match log.load_taint_events() {
280 Ok(events) => TaintState::from_events(events.iter()),
281 Err(e) => {
282 eprintln!("kintsugi-daemon: failed to replay taint events: {e}");
283 TaintState::new()
284 }
285 };
286 Ok(Self {
287 log,
288 mode: Mode::default(),
289 scorer: kintsugi_model::default_scorer(),
290 snapshot_dir,
291 kill_path,
292 vault_path,
293 pending: RefCell::new(None),
294 shutdown: Cell::new(false),
295 throttle: RefCell::new(AuthThrottle::default()),
296 taint: RefCell::new(taint),
297 denial_streak: RefCell::new(std::collections::HashMap::new()),
298 // Burst of 8 banked by a quiet session; steady ceiling of 4 model
299 // scorings/sec on the serve thread under a sustained recorder flood.
300 score_budget: RefCell::new(ScoreBudget::new(8.0, 4.0, std::time::Instant::now())),
301 })
302 }
303
304 /// Apply a taint transition to the session/file taint state.
305 ///
306 /// Fed by the content-tool observation surface (Phase 6.2) and by reset
307 /// policy. Pure state update — the decision path consults this; it never lets
308 /// a model change it (spine: rules decide, model only explains).
309 ///
310 /// Persist-then-apply: the transition is written to the durable, append-only
311 /// taint stream first (so it survives a daemon restart via replay in
312 /// [`open`](Self::open)), then applied to live in-memory state. The persist is
313 /// best-effort — a write failure is logged but never panics the daemon or
314 /// drops protection for the current session; it only risks losing this taint
315 /// across a future restart.
316 ///
317 /// Segment G: the event's `source_id` is redacted *before* both the persist and
318 /// the apply. A source identifier is meant to be an identifier only, but a URL
319 /// can carry a credential (`https://u:tok@host/p`, a colonless PAT-as-username,
320 /// `?api_key=…`). Normalizing at this single ingest boundary means the redacted
321 /// form is the only one that ever reaches the append-only (unscrubbable) log
322 /// row, the replayed state, the provenance trail, or an agent-facing reason.
323 pub fn apply_taint(&self, event: &TaintEvent) {
324 let event = event.with_redacted_source_id();
325 if let Err(e) = self.log.record_taint_event(&event) {
326 eprintln!("kintsugi-daemon: failed to persist taint event: {e}");
327 }
328 self.taint.borrow_mut().apply(&event);
329 }
330
331 /// Whether the given session has been influenced by untrusted content. A
332 /// `None` (untracked) session is reported as not tainted.
333 pub fn is_session_tainted(&self, session: Option<&str>) -> bool {
334 self.taint.borrow().is_session_tainted(session)
335 }
336
337 /// The session's accumulated provenance labels, if any — the in-process read
338 /// the provenance trail (P6.4) will surface. Source identifiers are already
339 /// redacted at ingest (see [`apply_taint`](Self::apply_taint)), so callers and
340 /// the eventual IPC view only ever see secret-free ids.
341 pub fn session_provenance(&self, session: &str) -> Option<kintsugi_core::TaintSet> {
342 self.taint.borrow().session_taint(session).cloned()
343 }
344
345 /// Build the human-readable provenance trail for a command (P6.4): the session's
346 /// untrusted reads, then this command's sensitive read → egress sink → the
347 /// trifecta rule that fired. Identifiers only (no secret contents). This is the
348 /// forensic chain the CLI/TUI renders on a held trifecta and the audit replay
349 /// uses to reconstruct "everything descended from source X".
350 pub fn provenance_trail(&self, cmd: &ProposedCommand) -> Vec<kintsugi_core::ProvStep> {
351 use kintsugi_core::ProvStep;
352 let session = cmd.session.as_deref();
353 // The trail explains *untrusted-content provenance*. A clean session has
354 // none, so its trail is empty even if the command reads a secret or hits a
355 // sink — there is nothing for those legs to descend from, and no rule fires.
356 let Some(set) = session.and_then(|s| self.session_provenance(s)) else {
357 return Vec::new();
358 };
359 if !set.is_tainted() {
360 return Vec::new();
361 }
362 let mut trail = kintsugi_core::untrusted_trail(&set);
363 let sensitive = kintsugi_core::is_sensitive_read(cmd);
364 let egress = kintsugi_core::is_egress_sink(cmd);
365 if let Some(path) = &sensitive {
366 trail.push(ProvStep::SensitiveRead { path: path.clone() });
367 }
368 if let Some(target) = &egress {
369 trail.push(ProvStep::EgressSink {
370 target: target.clone(),
371 });
372 }
373 let outcome = kintsugi_core::evaluate_trifecta(true, sensitive.is_some(), egress.is_some());
374 if let Some(rule) = outcome.rule() {
375 trail.push(ProvStep::RuleFired {
376 rule: rule.to_string(),
377 });
378 }
379 trail
380 }
381
382 /// Apply the Provenance trifecta as a deterministic class **floor**: a command
383 /// in a tainted session that reads a secret and reaches an egress sink is the
384 /// lethal trifecta and is forced to the catastrophic hard floor. Escalation
385 /// only — it can raise the class, never lower it (spine: monotonic caution).
386 ///
387 /// The trifecta can fire only when the session is *currently* tainted. Taint
388 /// is durable across daemon restarts (item D): transitions are persisted and
389 /// replayed on [`open`](Self::open), so a restart no longer silently clears it.
390 /// This remains interception, not an unbypassable firewall (e.g. a tool run by
391 /// absolute path can dodge observation); the base rules still stand regardless.
392 fn trifecta_floor(
393 &self,
394 cmd: &ProposedCommand,
395 policy: &kintsugi_core::Policy,
396 base_class: kintsugi_core::Class,
397 base_rule: String,
398 ) -> (kintsugi_core::Class, String) {
399 use kintsugi_core::Trifecta;
400 if !policy.provenance_enabled() || !self.is_session_tainted(cmd.session.as_deref()) {
401 return (base_class, base_rule);
402 }
403 let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
404 let egress = kintsugi_core::is_egress_sink(cmd).is_some();
405 let outcome = kintsugi_core::evaluate_trifecta(true, sensitive, egress);
406 let floor = match outcome {
407 // The full trifecta: a hard floor that inherits the no-downgrade guard.
408 Trifecta::Block => kintsugi_core::Class::Catastrophic,
409 // Lesser bands: held (attended) / denied (unattended), tunable by policy.
410 Trifecta::Hold | Trifecta::Annotate => kintsugi_core::Class::Ambiguous,
411 Trifecta::None => return (base_class, base_rule),
412 };
413 let class = base_class.max(floor);
414 // Only relabel the reason when the trifecta actually raised the floor;
415 // otherwise the base rule was already at least this severe.
416 if class.severity() > base_class.severity() {
417 let rule = outcome.rule().unwrap_or("TRIFECTA");
418 (class, format!("{rule}:provenance ({base_rule})"))
419 } else {
420 (class, base_rule)
421 }
422 }
423
424 /// Whether an authenticated shutdown has been accepted (serve loop should exit).
425 pub fn should_shutdown(&self) -> bool {
426 self.shutdown.get()
427 }
428
429 /// Read the current admin vault, fresh from the daemon-resolved path. Called on
430 /// every privileged op so a re-provision / password change applies immediately —
431 /// the daemon is the authority on the *path* (a caller can't redirect it), and
432 /// the contents are never cached, so there is no stale-vault class of bug.
433 fn current_vault(&self) -> VaultState {
434 admin::load_vault(&self.vault_path)
435 }
436
437 /// Issue a challenge for a privileged op. `locked=false` means no vault, so the
438 /// caller may proceed without a proof.
439 fn auth_begin(&self, op: &str) -> ipc::Response {
440 match self.current_vault() {
441 VaultState::Degraded(_) => ipc::Response::Error {
442 message: "admin vault is degraded; refusing privileged operations".into(),
443 },
444 VaultState::Locked(v) => {
445 let nonce = match admin::random_auth_nonce() {
446 Ok(n) => n,
447 Err(_) => {
448 return ipc::Response::Error {
449 message: "could not generate a challenge".into(),
450 }
451 }
452 };
453 let (salt, params) = v.auth_challenge();
454 *self.pending.borrow_mut() = Some((nonce.clone(), op.to_string()));
455 ipc::Response::Challenge {
456 locked: true,
457 nonce: hex::encode(&nonce),
458 salt,
459 params,
460 }
461 }
462 VaultState::Unprovisioned => ipc::Response::Challenge {
463 locked: false,
464 nonce: String::new(),
465 salt: String::new(),
466 params: kintsugi_core::admin::KdfParams::production(),
467 },
468 }
469 }
470
471 /// Complete an authenticated shutdown. Enforced against the daemon's own vault,
472 /// read fresh from disk so a just-provisioned vault is honored without a restart.
473 fn shutdown_op(
474 &self,
475 op: &str,
476 nonce_hex: Option<&str>,
477 proof_hex: Option<&str>,
478 ) -> ipc::Response {
479 let vault = match self.current_vault() {
480 VaultState::Degraded(_) => {
481 self.record_admin(op, false, "vault degraded");
482 return ipc::Response::Error {
483 message: "admin vault is degraded; refusing to stop".into(),
484 };
485 }
486 // Unprovisioned: there is no lock, so a clean shutdown is allowed.
487 VaultState::Unprovisioned => {
488 self.record_admin(op, true, "unprovisioned");
489 self.shutdown.set(true);
490 return ipc::Response::Ack;
491 }
492 VaultState::Locked(v) => v,
493 };
494 // Brute-force lockout: after repeated failures, refuse without even
495 // checking the proof until the window elapses (the attempt is still
496 // logged). Defeats a script hammering the admin password.
497 if let Some(rem) = self.throttle.borrow().lockout_remaining() {
498 self.record_admin(op, false, "locked out");
499 return ipc::Response::Error {
500 message: format!(
501 "too many failed attempts; locked out for {}s",
502 rem.as_secs() + 1
503 ),
504 };
505 }
506 // The challenge is one-shot: take it regardless of the outcome.
507 let pending = self.pending.borrow_mut().take();
508 // A locked vault requires BOTH a nonce and a proof. If either is absent
509 // (the unauthenticated caller), fail without ever decoding a placeholder
510 // into the crypto path.
511 let ok = match (pending, nonce_hex, proof_hex) {
512 (Some((issued_nonce, issued_op)), Some(nonce_hex), Some(proof_hex)) => {
513 match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
514 (Ok(nonce), Ok(proof)) => {
515 issued_op == op
516 && issued_nonce == nonce
517 && vault.verify_proof(&nonce, op.as_bytes(), &proof)
518 }
519 _ => false,
520 }
521 }
522 _ => false,
523 };
524 if ok {
525 self.throttle.borrow_mut().reset();
526 self.record_admin(op, true, "authenticated");
527 self.shutdown.set(true);
528 ipc::Response::Ack
529 } else {
530 self.throttle.borrow_mut().record_failure();
531 // Distinguish a wrong password from a vault that simply can't carry a
532 // proof (provisioned before the asymmetric-auth scheme): the latter
533 // fails for *every* password, so a bare "authentication failed" reads
534 // as a bug. Point the user at the one-line fix instead.
535 if !vault.supports_proof() {
536 self.record_admin(op, false, "vault missing proof key");
537 return ipc::Response::Error {
538 message:
539 "admin vault has no auth key — re-run `kintsugi admin provision --force` \
540 (the daemon picks it up immediately, no restart needed)"
541 .into(),
542 };
543 }
544 self.record_admin(op, false, "authentication failed");
545 ipc::Response::Error {
546 message: "authentication failed".into(),
547 }
548 }
549 }
550
551 /// Record a privileged-operation attempt as a hash-chained audit event, so a
552 /// forced stop — successful or not — is always visible on the timeline.
553 fn record_admin(&self, op: &str, ok: bool, reason: &str) {
554 let raw = format!(
555 "admin {op} — {}",
556 if ok { "authenticated" } else { "denied" }
557 );
558 let cmd = ProposedCommand::new(
559 "admin",
560 std::path::Path::new("."),
561 vec!["admin".to_string(), op.to_string()],
562 raw,
563 );
564 let decision = if ok { Decision::Allow } else { Decision::Deny };
565 let verdict = Verdict::rules(
566 kintsugi_core::Class::Safe,
567 decision,
568 format!("admin:{op}:{reason}"),
569 );
570 let _ = self.log.log_event(&cmd, &verdict, None);
571 }
572
573 /// Whether the panic kill-switch is currently engaged.
574 pub fn kill_switch_engaged(&self) -> bool {
575 self.kill_path.exists()
576 }
577
578 /// The directory snapshots are stored under.
579 pub fn snapshot_dir(&self) -> &std::path::Path {
580 &self.snapshot_dir
581 }
582
583 /// Swap in a specific scorer (used by tests).
584 pub fn with_scorer(mut self, scorer: Box<dyn kintsugi_model::Scorer>) -> Self {
585 self.scorer = scorer;
586 self
587 }
588
589 /// The name of the active Tier-2 scorer backend.
590 pub fn scorer_name(&self) -> &str {
591 self.scorer.name()
592 }
593
594 /// Open the daemon at the default database path.
595 pub fn open_default() -> Result<Self> {
596 Self::open(default_db_path())
597 }
598
599 /// Set the operating mode (attended / unattended / notify).
600 pub fn with_mode(mut self, mode: Mode) -> Self {
601 self.mode = mode;
602 self
603 }
604
605 /// The current operating mode.
606 pub fn mode(&self) -> Mode {
607 self.mode
608 }
609
610 /// Decide what to do with a proposed command.
611 ///
612 /// Order: (1) load the effective policy (global ← repo) which may set the mode
613 /// and risk threshold; (2) classify with the Tier-1 rule engine; (3) **Tier-2
614 /// model** — for the ambiguous band only, fill `summary`+`risk` and, in
615 /// unattended mode, apply the graduated threshold (below → allow, at/above →
616 /// deny); the model summarizes a catastrophic command for the hold card but
617 /// never changes its decision; (4) apply policy allow/deny (never a
618 /// catastrophic downgrade); (5) apply decision memory.
619 ///
620 /// Security spine: rules classify; the model only explains and scores the
621 /// ambiguous band, and its influence is escalation-only. Safe stays on the
622 /// model-free fast path.
623 pub fn decide(&self, cmd: &ProposedCommand) -> Verdict {
624 // Panic kill-switch: halt everything, including Safe, the instant it is
625 // engaged. Checked first, before any other logic.
626 if self.kill_switch_engaged() {
627 let m = kintsugi_core::classify(cmd);
628 return Verdict::rules(m.class, Decision::Deny, "kill-switch: all actions halted");
629 }
630
631 let policy = load_policy(&cmd.cwd);
632 let mode = policy.mode.unwrap_or(self.mode);
633
634 let m = kintsugi_core::classify(cmd);
635 // Provenance (Phase 6): apply the trifecta as a deterministic class floor
636 // (escalation-only) before the model ever runs. Taint never downgrades.
637 let (class, rule) = self.trifecta_floor(cmd, &policy, m.class, m.rule);
638 let mut verdict = Verdict::rules(class, kintsugi_core::decide(class, mode), &rule);
639
640 // Tier-2 model: ambiguous band gets summary + risk (+ graduated decision);
641 // catastrophic gets a summary for the hold card. Safe is never scored.
642 match class {
643 kintsugi_core::Class::Ambiguous => {
644 let out = self.scorer.score(cmd, class, &rule);
645 verdict.summary = Some(out.summary);
646 verdict.risk = Some(out.risk);
647 verdict.tier = 2;
648 if mode == Mode::Unattended {
649 // Spine rule #2 (monotonic model influence): the model may only
650 // ADD caution. The unattended baseline for an ambiguous command
651 // is Deny (queued for a human); the model records risk for that
652 // review but NEVER downgrades Deny -> Allow. Auto-proceeding an
653 // ambiguous command unattended is only possible via an explicit
654 // human allowlist (.kintsugi.toml / decision memory) below — a human
655 // decision, not the model's.
656 verdict.reason = format!(
657 "model:risk={} ({}) — unattended holds ambiguous for review",
658 out.risk, rule
659 );
660 }
661 }
662 kintsugi_core::Class::Catastrophic => {
663 let out = self.scorer.score(cmd, class, &rule);
664 verdict.summary = Some(out.summary);
665 verdict.tier = 2;
666 }
667 kintsugi_core::Class::Safe => {}
668 }
669
670 // Policy can escalate (deny) or tame (allow) — never downgrade catastrophic.
671 let action = policy.action_for(&cmd.raw);
672 verdict = kintsugi_core::adjust_for_policy(verdict, action, mode);
673
674 // Decision memory has the final say — but, like policy, it can never
675 // auto-downgrade a CATASTROPHIC command (that hard floor only lifts via an
676 // in-the-moment human decision, never a stored/replayed one). Memory deny
677 // always applies (escalation-only).
678 let repo = repo_key(&cmd.cwd);
679 let hash = kintsugi_core::command_hash(&cmd.raw);
680 match self.log.memory_lookup(&repo, &hash) {
681 Ok(Some(Decision::Allow)) if verdict.class != kintsugi_core::Class::Catastrophic => {
682 verdict.decision = Decision::Allow;
683 verdict.reason = format!("memory:allow ({})", verdict.reason);
684 }
685 Ok(Some(Decision::Deny)) => {
686 verdict.decision = Decision::Deny;
687 verdict.reason = format!("memory:deny ({})", verdict.reason);
688 }
689 _ => {}
690 }
691 verdict
692 }
693
694 /// Handle one proposal: decide, snapshot if destructive+allowed, record, and —
695 /// if held — enqueue it for approval. Returns the verdict.
696 pub fn handle(&self, cmd: ProposedCommand) -> Verdict {
697 let mut verdict = self.decide(&cmd);
698 let (snapshot_id, snapshot_failed) = self.maybe_snapshot(&cmd, &verdict);
699 if verdict.decision == Decision::Allow && verdict.class != kintsugi_core::Class::Safe {
700 let note = if snapshot_failed {
701 Some("snapshot failed — NOT reversible by undo")
702 } else if !kintsugi_core::snapshot::is_fully_reversible(&cmd) {
703 Some("target can't be fully snapshotted — undo may not restore everything")
704 } else {
705 None
706 };
707 if let Some(n) = note {
708 verdict.reason = format!("{} [⚠ {n}]", verdict.reason);
709 }
710 }
711 if let Err(e) = self.log.log_event(&cmd, &verdict, snapshot_id.as_deref()) {
712 // Spine #4: a command we cannot write to the append-only log must not run
713 // unrecorded. Fail closed — refuse an Allow rather than execute it dark.
714 eprintln!("kintsugi-daemon: failed to record event: {e}");
715 if verdict.decision == Decision::Allow {
716 verdict.decision = Decision::Deny;
717 verdict.reason = format!(
718 "audit-log write failed; denied fail-closed ({})",
719 verdict.reason
720 );
721 }
722 }
723 if verdict.decision == Decision::Hold && needs_queue_entry(&cmd, verdict.class) {
724 if let Err(e) = self
725 .log
726 .enqueue_pending(&cmd, verdict.class, &verdict.reason)
727 {
728 eprintln!("kintsugi-daemon: failed to enqueue pending: {e}");
729 }
730 }
731 // Negotiation is the LAST step so the audit log and the approval queue keep
732 // the clean, rule-grounded reason; only the verdict returned to the agent
733 // carries the model-facing instruction. This never changes the decision —
734 // it only reframes a block — so it cannot unlock the gate (spine).
735 self.negotiate(cmd.session.as_deref(), verdict)
736 }
737
738 /// Reframe a *blocked* verdict for the agent (model-facing reason + the
739 /// "materially safer alternative / else ask the user" instruction) and drive the
740 /// consecutive-denial circuit breaker. Allow/ask are returned unchanged; an
741 /// Allow resets the session's streak. Decision-preserving by construction.
742 fn negotiate(&self, session: Option<&str>, mut verdict: Verdict) -> Verdict {
743 use kintsugi_core::Class;
744 // The agent receives a hard "no" for a Deny, or for a catastrophic Hold (the
745 // adapter maps that to deny — an in-agent allow would skip the snapshot). An
746 // ambiguous Hold becomes a native `ask`, which is not a negotiation deny.
747 let blocked = verdict.decision == Decision::Deny
748 || (verdict.decision == Decision::Hold && verdict.class == Class::Catastrophic);
749 if !blocked {
750 if verdict.decision == Decision::Allow {
751 if let Some(s) = session {
752 self.denial_streak.borrow_mut().remove(s);
753 }
754 }
755 return verdict;
756 }
757
758 // Count consecutive blocks per session; an untracked session can't be
759 // counted, so it just never trips (the reason is still grounded).
760 let tripped = match session {
761 Some(s) => {
762 let mut streaks = self.denial_streak.borrow_mut();
763 let count = streaks.entry(s.to_string()).or_insert(0);
764 *count += 1;
765 *count >= kintsugi_core::negotiate::CONSECUTIVE_DENY_LIMIT
766 }
767 None => false,
768 };
769
770 verdict.reason = if tripped {
771 kintsugi_core::negotiate::circuit_breaker_reason(&verdict.reason)
772 } else {
773 kintsugi_core::negotiate::model_deny_reason(&verdict.reason)
774 };
775 verdict
776 }
777
778 /// Approve or deny a queued command by id: record the human decision (and, on
779 /// allow, snapshot), then mark the queue entry resolved. The originating
780 /// caller (MCP poll / shim) executes; this never runs the command itself.
781 ///
782 /// A human may approve any class here — including catastrophic — which is the
783 /// deliberate human override (the *model* never can). Returns whether the id
784 /// was found in the queue.
785 pub fn resolve_pending(&self, id: &str, decision: Decision) -> Result<bool> {
786 // While the kill-switch is engaged, nothing is approvable.
787 if decision == Decision::Allow && self.kill_switch_engaged() {
788 anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before approving");
789 }
790 let status = if decision == Decision::Allow {
791 "approved"
792 } else {
793 "denied"
794 };
795 // Claim the entry exactly once. If the CAS doesn't win, the command was
796 // already resolved (or never queued) — return false rather than snapshot
797 // and log a second time, which is what would double-run an approved cmd.
798 if !self.log.cas_pending_status(id, "pending", status)? {
799 return Ok(false);
800 }
801 let Some(cmd) = self.log.pending_command(id)? else {
802 return Ok(false);
803 };
804 self.resolve(&ipc::Resolution {
805 command: cmd,
806 decision,
807 remember: false,
808 })?;
809 Ok(true)
810 }
811
812 /// Snapshot the paths a command will touch, when it is allowed and not Safe.
813 /// Returns the snapshot id to attach to the event, if one was taken.
814 fn maybe_snapshot(&self, cmd: &ProposedCommand, verdict: &Verdict) -> (Option<String>, bool) {
815 if verdict.decision != Decision::Allow || verdict.class == kintsugi_core::Class::Safe {
816 return (None, false);
817 }
818 match kintsugi_core::capture_snapshot(&self.snapshot_dir, cmd) {
819 Ok(Some(manifest)) => {
820 if let Err(e) = self.log.record_snapshot(&manifest) {
821 eprintln!("kintsugi-daemon: failed to record snapshot: {e}");
822 return (None, true);
823 }
824 (Some(manifest.id), false)
825 }
826 Ok(None) => (None, false),
827 Err(e) => {
828 eprintln!("kintsugi-daemon: snapshot failed: {e}");
829 (None, true)
830 }
831 }
832 }
833
834 /// Handle a human's resolution of a held command: record the final decision
835 /// and, if requested, remember it for this exact command in this repo.
836 pub fn resolve(&self, resolution: &ipc::Resolution) -> Result<()> {
837 // Kill-switch hard floor: while engaged, no Allow resolves — not via the
838 // queue (resolve_pending) and not via this direct path (shim hold card /
839 // raw Request::Resolve). Mirrors the guard in resolve_pending().
840 if resolution.decision == Decision::Allow && self.kill_switch_engaged() {
841 anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before allowing");
842 }
843 let cmd = &resolution.command;
844 // Re-classify so the recorded class is accurate even though a human chose.
845 let m = kintsugi_core::classify(cmd);
846 // A catastrophic command is never *remembered* as always-allow — the hard
847 // floor must re-prompt every time; `[r]` on a catastrophic acts as allow-once.
848 let remember = resolution.remember
849 && !(resolution.decision == Decision::Allow
850 && m.class == kintsugi_core::Class::Catastrophic);
851 let reason = match resolution.decision {
852 Decision::Allow if remember => "human:always-allow",
853 Decision::Allow => "human:allow",
854 Decision::Deny if remember => "human:always-deny",
855 Decision::Deny => "human:deny",
856 Decision::Hold => "human:hold",
857 };
858 let verdict = Verdict::rules(m.class, resolution.decision, reason);
859 // Snapshot before a human-approved destructive command runs.
860 let (snapshot_id, _) = self.maybe_snapshot(cmd, &verdict);
861 self.log.log_event(cmd, &verdict, snapshot_id.as_deref())?;
862
863 if remember && resolution.decision != Decision::Hold {
864 let repo = repo_key(&cmd.cwd);
865 let hash = kintsugi_core::command_hash(&cmd.raw);
866 self.log.remember(&repo, &hash, resolution.decision)?;
867 }
868
869 // If this command was queued (e.g. a shim hold the human just answered),
870 // mark the queue entry resolved so it leaves `kintsugi queue`.
871 if resolution.decision != Decision::Hold {
872 let status = if resolution.decision == Decision::Allow {
873 "approved"
874 } else {
875 "denied"
876 };
877 let _ = self.log.set_pending_status(&cmd.id.to_string(), status);
878 }
879 Ok(())
880 }
881
882 /// Record an observed filesystem change from the backstop watcher. Logged as
883 /// `agent = "fs-watch"`, decision Allow (it already happened) — its purpose is
884 /// to keep the timeline and undo complete for actions that bypassed
885 /// interception.
886 pub fn observe(&self, obs: &ipc::Observation) -> Result<()> {
887 let raw = format!("{} {}", obs.kind, obs.path);
888 let cwd = std::path::Path::new(&obs.path)
889 .parent()
890 .map(|p| p.to_path_buf())
891 .unwrap_or_default();
892 let cmd = ProposedCommand::new(
893 "fs-watch",
894 cwd,
895 vec![obs.kind.clone(), obs.path.clone()],
896 raw,
897 );
898 let verdict = Verdict::rules(
899 kintsugi_core::Class::Safe,
900 Decision::Allow,
901 format!("fs:{}", obs.kind),
902 );
903 self.log.log_event(&cmd, &verdict, None)?;
904 Ok(())
905 }
906
907 /// Record a shell command from a human shell session (passive recording, no
908 /// AI-agent hook). Logged as `agent = "shell"`, decision Allow — it is never
909 /// blocked (the recorder is an audit/undo trail, not a gate). We **classify**
910 /// it with the Tier-1 rules so the event carries the real class (a destructive
911 /// command a DBA ran is flagged in the timeline and `kintsugi report`), and we
912 /// **snapshot destructive commands** so `kintsugi undo` can recover a human's
913 /// mistake. The model never runs on this path.
914 ///
915 /// The hard floor stays honest: this is an audit record of the past, not a
916 /// gate. The "nothing un-warned" guarantee never applied to commands a human
917 /// ran outside Kintsugi; the "tamper-evident record of everything" one does,
918 /// which is exactly what this preserves.
919 pub fn record_shell(&self, cmd: &ProposedCommand) -> Result<()> {
920 // Provenance: the recorder is for human shell sessions, so force the agent
921 // label to "shell" regardless of what the caller sent. A local peer that
922 // can reach the socket therefore cannot forge a record attributed to an
923 // AI agent ("claude-code") or the watcher ("fs-watch"); the worst it can
924 // do is inject a self-reported *shell* event, which the Audit view treats
925 // accordingly. (The socket is already owner-only; this is defense in depth.)
926 let mut cmd = cmd.clone();
927 cmd.agent = "shell".to_string();
928 let m = kintsugi_core::classify(&cmd);
929 // Allow, not the rule's gate decision: the command already executed, so
930 // recording a Hold/Deny here would be a lie about what happened. The
931 // class still rides along (verdict.class) so the timeline flags danger.
932 let mut verdict = Verdict::rules(m.class, Decision::Allow, format!("recorded:{}", m.rule));
933 // Score risky commands with the model so the Recorder rows and the
934 // details drawer can show a plain-English summary alongside the raw
935 // command. The decision stays Allow — this is just metadata on a row
936 // that's already an audit record of the past.
937 //
938 // The model call is one synchronous inference on the single-threaded
939 // serve loop, so it's spent against a token-bucket budget: under a flood
940 // of risky records the budget empties and we record the row *without* the
941 // summary rather than let the recorder serialize unbounded inference and
942 // starve real hold/approve traffic. The class still rides in verdict.class
943 // either way, so the timeline never loses the danger signal — only the
944 // cosmetic prose. (Safe commands never score, so they never spend.)
945 let may_score = !matches!(m.class, kintsugi_core::Class::Safe)
946 && self
947 .score_budget
948 .borrow_mut()
949 .try_spend(std::time::Instant::now());
950 if may_score {
951 let out = self.scorer.score(&cmd, m.class, &m.rule);
952 verdict.summary = Some(out.summary);
953 verdict.tier = 2;
954 if m.class == kintsugi_core::Class::Ambiguous {
955 verdict.risk = Some(out.risk);
956 }
957 } else if m.class != kintsugi_core::Class::Safe {
958 // Budget shed: keep the danger tier on the row even without prose.
959 verdict.tier = 2;
960 }
961 // Recoverer: snapshot the paths a *destructive* human command will touch,
962 // so `kintsugi undo` can roll back a person's *filesystem* mistake (rm -rf,
963 // a clobbering overwrite) the same way it rolls back an agent's. The shell
964 // preexec hook fires before the command runs, so this is a just-in-time
965 // capture; `maybe_snapshot` no-ops for Safe commands and reflinks where it
966 // can, so the common case stays cheap. Best-effort: if the snapshot loses
967 // the race (or the fs can't reflink), the filesystem-watcher backstop still
968 // records the change. This is a filesystem recoverer — an in-database
969 // DROP/TRUNCATE is not a file, so it's flagged/recorded but recovery there
970 // is your DB's PITR/backups. The honest guarantee is "recoverable", not
971 // transactional.
972 let (snapshot_id, _) = self.maybe_snapshot(&cmd, &verdict);
973 self.log.log_event(&cmd, &verdict, snapshot_id.as_deref())?;
974 Ok(())
975 }
976
977 /// Dispatch an IPC request to its handler.
978 pub fn handle_request(&self, req: ipc::Request) -> ipc::Response {
979 match req {
980 ipc::Request::Propose(cmd) => ipc::Response::Verdict(self.handle(cmd)),
981 ipc::Request::Resolve(resolution) => match self.resolve(&resolution) {
982 Ok(()) => ipc::Response::Ack,
983 Err(e) => ipc::Response::Error {
984 message: e.to_string(),
985 },
986 },
987 ipc::Request::Observe(obs) => match self.observe(&obs) {
988 Ok(()) => ipc::Response::Ack,
989 Err(e) => ipc::Response::Error {
990 message: e.to_string(),
991 },
992 },
993 // Observation only labels — it never blocks and can't fail the caller:
994 // apply_taint persists best-effort and redacts the source_id (segment G).
995 ipc::Request::Ingest(observed) => {
996 self.apply_taint(&observed.into_taint_event());
997 ipc::Response::Ack
998 }
999 ipc::Request::Provenance(cmd) => ipc::Response::Provenance {
1000 tainted: self.is_session_tainted(cmd.session.as_deref()),
1001 trail: self.provenance_trail(&cmd),
1002 },
1003 ipc::Request::Record(cmd) => match self.record_shell(&cmd) {
1004 Ok(()) => ipc::Response::Ack,
1005 Err(e) => ipc::Response::Error {
1006 message: e.to_string(),
1007 },
1008 },
1009 ipc::Request::ListPending => match self.log.list_pending() {
1010 Ok(items) => ipc::Response::PendingList { items },
1011 Err(e) => ipc::Response::Error {
1012 message: e.to_string(),
1013 },
1014 },
1015 ipc::Request::PendingStatus { id } => match self.log.pending_status(&id) {
1016 Ok(status) => ipc::Response::Pending {
1017 status: status.unwrap_or_else(|| "gone".to_string()),
1018 },
1019 Err(e) => ipc::Response::Error {
1020 message: e.to_string(),
1021 },
1022 },
1023 ipc::Request::Approve { id } => self.resolve_pending_response(&id, Decision::Allow),
1024 ipc::Request::Deny { id } => self.resolve_pending_response(&id, Decision::Deny),
1025 ipc::Request::PrunePending => match self.log.prune_pending() {
1026 Ok(n) => ipc::Response::Pending {
1027 status: n.to_string(),
1028 },
1029 Err(e) => ipc::Response::Error {
1030 message: e.to_string(),
1031 },
1032 },
1033 ipc::Request::Status => ipc::Response::Status {
1034 scorer: self.scorer_name().to_string(),
1035 },
1036 ipc::Request::AuthBegin { op } => self.auth_begin(&op),
1037 ipc::Request::Shutdown { op, nonce, proof } => {
1038 self.shutdown_op(&op, nonce.as_deref(), proof.as_deref())
1039 }
1040 }
1041 }
1042
1043 fn resolve_pending_response(&self, id: &str, decision: Decision) -> ipc::Response {
1044 match self.resolve_pending(id, decision) {
1045 Ok(true) => ipc::Response::Ack,
1046 Ok(false) => ipc::Response::Error {
1047 message: format!("no pending command with id {id}"),
1048 },
1049 Err(e) => ipc::Response::Error {
1050 message: e.to_string(),
1051 },
1052 }
1053 }
1054
1055 /// Borrow the underlying event log (read-only queries).
1056 pub fn log(&self) -> &EventLog {
1057 &self.log
1058 }
1059}
1060
1061/// Load and merge the effective policy for a command's working directory:
1062/// global defaults (config dir) overridden by the repo's `.kintsugi.toml`.
1063pub fn load_policy(cwd: &std::path::Path) -> kintsugi_core::Policy {
1064 let global = read_policy_file(&global_policy_path()).unwrap_or_default();
1065 let repo = find_repo_policy(cwd)
1066 .and_then(|p| read_policy_file(&p))
1067 .unwrap_or_default();
1068 kintsugi_core::Policy::merge(global, repo)
1069}
1070
1071/// Path to the global policy file. Override with `KINTSUGI_CONFIG` (used in tests).
1072fn global_policy_path() -> PathBuf {
1073 if let Ok(p) = std::env::var("KINTSUGI_CONFIG") {
1074 return PathBuf::from(p);
1075 }
1076 if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
1077 return dirs.config_dir().join("config.toml");
1078 }
1079 std::env::temp_dir().join("kintsugi-config.toml")
1080}
1081
1082/// Find the nearest `.kintsugi.toml` from `cwd` upward.
1083fn find_repo_policy(cwd: &std::path::Path) -> Option<PathBuf> {
1084 let mut dir = Some(cwd);
1085 while let Some(d) = dir {
1086 let candidate = d.join(".kintsugi.toml");
1087 if candidate.is_file() {
1088 return Some(candidate);
1089 }
1090 dir = d.parent();
1091 }
1092 None
1093}
1094
1095fn read_policy_file(path: &std::path::Path) -> Option<kintsugi_core::Policy> {
1096 let text = std::fs::read_to_string(path).ok()?;
1097 match kintsugi_core::Policy::parse(&text) {
1098 Ok(p) => Some(p),
1099 Err(e) => {
1100 eprintln!(
1101 "kintsugi-daemon: ignoring invalid policy {}: {e}",
1102 path.display()
1103 );
1104 None
1105 }
1106 }
1107}
1108
1109/// Identify the "repo" a command runs in: the nearest ancestor containing a
1110/// `.git` directory, else the working directory itself.
1111pub fn repo_key(cwd: &std::path::Path) -> String {
1112 let mut dir = Some(cwd);
1113 while let Some(d) = dir {
1114 if d.join(".git").exists() {
1115 return d.to_string_lossy().to_string();
1116 }
1117 dir = d.parent();
1118 }
1119 cwd.to_string_lossy().to_string()
1120}
1121
1122/// Run the daemon: open the default log, bind the socket, serve forever.
1123pub fn run() -> Result<()> {
1124 let daemon = Daemon::open_default()?;
1125 let server = Server::bind()?;
1126 // Record our PID so `kintsugi stop` can find and stop us (any launch path).
1127 let _ = std::fs::write(pid_file_path(), std::process::id().to_string());
1128 eprintln!(
1129 "kintsugi-daemon {} listening on {}",
1130 VERSION,
1131 Server::endpoint().display()
1132 );
1133 server.serve_until(
1134 |req| daemon.handle_request(req),
1135 || daemon.should_shutdown(),
1136 )?;
1137 // An authenticated shutdown landed: clean up the PID file and exit.
1138 let _ = std::fs::remove_file(pid_file_path());
1139 eprintln!("kintsugi-daemon: authenticated shutdown — exiting.");
1140 Ok(())
1141}
1142
1143/// Path to the daemon's PID file (next to the event log).
1144pub fn pid_file_path() -> PathBuf {
1145 default_db_path().with_file_name("kintsugi.pid")
1146}
1147
1148#[cfg(test)]
1149mod queue_entry_tests {
1150 use super::needs_queue_entry;
1151 use kintsugi_core::{Class, ProposedCommand};
1152
1153 fn cmd(agent: &str) -> ProposedCommand {
1154 ProposedCommand::new(
1155 agent,
1156 std::path::Path::new("/tmp"),
1157 vec!["rm".into(), "x".into()],
1158 "rm x",
1159 )
1160 }
1161
1162 #[test]
1163 fn catastrophic_always_enqueues() {
1164 for a in [
1165 "claude-code",
1166 "qwen",
1167 "gemini",
1168 "mcp",
1169 "opencode",
1170 "anything",
1171 ] {
1172 assert!(
1173 needs_queue_entry(&cmd(a), Class::Catastrophic),
1174 "catastrophic must queue for {a}"
1175 );
1176 }
1177 }
1178
1179 #[test]
1180 fn ambiguous_skips_only_native_ask_agents() {
1181 // Native ask → resolved by the agent's own prompt, so NO queue entry.
1182 for a in ["claude-code", "qwen", "copilot", "cursor", "codex"] {
1183 assert!(
1184 !needs_queue_entry(&cmd(a), Class::Ambiguous),
1185 "{a} has native ask → no queue orphan"
1186 );
1187 }
1188 // No native ask → the human resolves via the queue, so it MUST enqueue.
1189 for a in ["gemini", "antigravity", "opencode", "mcp", "future-agent"] {
1190 assert!(
1191 needs_queue_entry(&cmd(a), Class::Ambiguous),
1192 "{a} has no prompt → must queue"
1193 );
1194 }
1195 }
1196}
1197
1198#[cfg(test)]
1199mod score_budget_tests {
1200 use super::ScoreBudget;
1201 use std::time::{Duration, Instant};
1202
1203 #[test]
1204 fn burst_is_bounded_then_refills_at_the_steady_rate() {
1205 let t0 = Instant::now();
1206 // Capacity 8, refill 4/sec.
1207 let mut b = ScoreBudget::new(8.0, 4.0, t0);
1208
1209 // A flood at t0 spends the whole burst and no more — the 9th is shed, so
1210 // a recorder flood can never serialize unbounded inference on the loop.
1211 for i in 0..8 {
1212 assert!(b.try_spend(t0), "burst token {i} should be granted");
1213 }
1214 assert!(!b.try_spend(t0), "9th in the same instant must be shed");
1215
1216 // After 1s, 4 tokens have refilled (the steady ceiling) — not the full 8.
1217 let t1 = t0 + Duration::from_secs(1);
1218 for i in 0..4 {
1219 assert!(b.try_spend(t1), "refilled token {i} should be granted");
1220 }
1221 assert!(!b.try_spend(t1), "refill is rate-capped, not a full reset");
1222 }
1223
1224 #[test]
1225 fn refill_never_exceeds_capacity() {
1226 let t0 = Instant::now();
1227 let mut b = ScoreBudget::new(8.0, 4.0, t0);
1228 for _ in 0..8 {
1229 assert!(b.try_spend(t0));
1230 }
1231 // Idle far longer than it takes to refill — tokens cap at `capacity`, so a
1232 // long-quiet session banks a burst of 8, never an unbounded backlog.
1233 let later = t0 + Duration::from_secs(3600);
1234 for i in 0..8 {
1235 assert!(b.try_spend(later), "banked token {i} after a long idle");
1236 }
1237 assert!(
1238 !b.try_spend(later),
1239 "cap holds: no more than `capacity` banked"
1240 );
1241 }
1242}