Skip to main content

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};
24use kintsugi_model::DependencyHint;
25
26pub use ipc::{Client, Observation, Resolution, Server};
27
28pub const VERSION: &str = env!("CARGO_PKG_VERSION");
29
30/// The kill-switch flag file name, alongside the event-log database.
31pub const KILL_SWITCH_FILE: &str = "panic.flag";
32
33/// Path to the panic kill-switch flag (alongside the default event log).
34pub fn kill_switch_path() -> PathBuf {
35    default_db_path()
36        .parent()
37        .map(|p| p.join(KILL_SWITCH_FILE))
38        .unwrap_or_else(|| std::env::temp_dir().join(KILL_SWITCH_FILE))
39}
40
41/// The fail-closed marker file name, alongside the event-log database.
42pub const FAIL_CLOSED_FILE: &str = "fail-closed.flag";
43
44/// Path to the fail-closed marker (alongside the default event log). Its mere
45/// existence is the signal — the content is irrelevant. The interception layer
46/// (shim/hook/MCP) reads it **without** the daemon, so that killing the daemon
47/// can't be used to open the gate: with the marker present, an unreachable
48/// daemon means *block*, not *run unguarded*.
49pub fn fail_closed_marker_path() -> PathBuf {
50    default_db_path().with_file_name(FAIL_CLOSED_FILE)
51}
52
53/// Whether the admin-set fail-closed marker is present. Cheap, daemon-free, and
54/// callable from the interception fast path. In the locked posture the marker is
55/// owned by the privileged account (root / a dedicated `kintsugi` user), so an
56/// audited non-root agent cannot remove it to re-open the gate.
57pub fn is_fail_closed_marked() -> bool {
58    fail_closed_marker_path().exists()
59}
60
61/// Create or remove the fail-closed marker to match `on`. Best-effort, atomic
62/// create; called by the admin flow when the locked `fail_closed` setting
63/// changes so the posture survives a daemon restart and a kill.
64pub fn set_fail_closed_marker(on: bool) -> std::io::Result<()> {
65    let path = fail_closed_marker_path();
66    if on {
67        if let Some(parent) = path.parent() {
68            std::fs::create_dir_all(parent)?;
69        }
70        // 0644: world-readable (the shim must read it) but, in the locked posture,
71        // owned by the privileged account so the audited user can't delete it.
72        std::fs::write(&path, b"fail-closed\n")?;
73    } else if path.exists() {
74        std::fs::remove_file(&path)?;
75    }
76    Ok(())
77}
78
79/// Resolve the event-log database path. Override with `KINTSUGI_DB` (handy in tests).
80pub fn default_db_path() -> PathBuf {
81    if let Ok(p) = std::env::var("KINTSUGI_DB") {
82        return PathBuf::from(p);
83    }
84    if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
85        return dirs.data_dir().join("events.db");
86    }
87    std::env::temp_dir().join("kintsugi-events.db")
88}
89
90/// The resident decision loop: owns the event log, the warm scorer, classifies,
91/// records.
92pub struct Daemon {
93    log: EventLog,
94    mode: Mode,
95    scorer: Box<dyn kintsugi_model::Scorer>,
96    snapshot_dir: PathBuf,
97    kill_path: PathBuf,
98    /// The admin vault **path**, resolved once at daemon startup from the path the
99    /// daemon itself chose (a caller's environment can't redirect it). The vault
100    /// *contents* are read fresh from this path on every privileged op
101    /// ([`current_vault`](Self::current_vault)) — never cached — so a re-provision
102    /// or password change applies immediately, with no restart and no stale-copy bug.
103    vault_path: PathBuf,
104    /// Whether this log records a provision (`audit:provision`) — computed once at
105    /// open. With the latch set, a *missing* vault is `Degraded`, not
106    /// `Unprovisioned`: deleting the vault file is not a way back to bare
107    /// approval on a machine that was provisioned.
108    vault_expected: bool,
109    /// The last challenge nonce issued (and its op), consumed once by `Shutdown`
110    /// or `Approve`. The slot is deliberately single and one-shot: a challenge
111    /// is bound to exactly one op (`"shutdown"` or `"approve:<id>"`) and one
112    /// use. A consequence, accepted by design: an `AuthBegin` for approve
113    /// supersedes any unconsumed shutdown challenge and vice versa — the
114    /// op-binding check then rejects any proof minted for the overwritten op,
115    /// so the supersede can never authorize the other operation (documented in
116    /// docs/policy.md and pinned by `approval_auth.rs`).
117    pending: RefCell<Option<(Vec<u8>, String)>>,
118    /// Set when an authenticated shutdown has been accepted; the serve loop exits.
119    shutdown: Cell<bool>,
120    /// In-memory brute-force throttle for admin authentication.
121    throttle: RefCell<AuthThrottle>,
122    /// Session/file information-flow (taint) state for the Provenance feature.
123    /// Event-sourced ([`TaintState`]): every transition is persisted to the
124    /// durable taint stream and the state is rebuilt by replaying it on a cold
125    /// start (see [`open`](Self::open)), so taint survives a daemon restart
126    /// (Phase 6 hardening item D — closes the fail-open-on-restart gap).
127    taint: RefCell<TaintState>,
128    /// Consecutive-block counter per session for the negotiation circuit breaker
129    /// (Phase 6). The hook is one-shot per tool call, so this resident state is the
130    /// only place that can count an agent retrying a blocked action across calls.
131    denial_streak: RefCell<std::collections::HashMap<String, u32>>,
132    /// Caps how much model-inference time the recorder path can impose on the
133    /// single-threaded serve loop, so a flood of risky shell records can't starve
134    /// real hold/approve traffic. See [`ScoreBudget`].
135    score_budget: RefCell<ScoreBudget>,
136}
137
138/// Rate-limit + lockout for admin authentication. The daemon is the single
139/// authority, so a process-local counter is enough: after a few consecutive
140/// failures it locks out for an exponentially growing window (defeating a script
141/// hammering the admin password), and a success resets it.
142#[derive(Default)]
143struct AuthThrottle {
144    failures: u32,
145    locked_until: Option<std::time::Instant>,
146}
147
148impl AuthThrottle {
149    /// Failed attempts allowed before the first lockout.
150    const FREE_ATTEMPTS: u32 = 5;
151
152    /// Remaining lockout duration, if currently locked out.
153    fn lockout_remaining(&self) -> Option<std::time::Duration> {
154        self.locked_until
155            .and_then(|t| t.checked_duration_since(std::time::Instant::now()))
156    }
157
158    /// Count a failed attempt; arm/extend the lockout once past the free budget.
159    fn record_failure(&mut self) {
160        self.failures = self.failures.saturating_add(1);
161        if self.failures >= Self::FREE_ATTEMPTS {
162            // 30s, then doubling (60s, 120s, …) capped at one hour.
163            let over = (self.failures - Self::FREE_ATTEMPTS).min(7);
164            self.locked_until = Some(
165                std::time::Instant::now()
166                    + std::time::Duration::from_secs((30u64 << over).min(3600)),
167            );
168        }
169    }
170
171    fn reset(&mut self) {
172        self.failures = 0;
173        self.locked_until = None;
174    }
175}
176
177/// Token-bucket budget for the *model scoring* on the recorder path.
178///
179/// The IPC serve loop is single-threaded: it reads one request, handles it to
180/// completion, then accepts the next. `record_shell` scores risky shell events
181/// with the local model so the Recorder rows can show a plain-English summary —
182/// but that scoring is one synchronous inference on the serve thread. A local
183/// peer (a runaway or compromised agent — the socket is owner-only, but that's
184/// exactly who we defend against) that floods the socket with risky `Observe`
185/// records would serialize one inference each and starve real hold/approve
186/// traffic, blinding the user's safety control plane. Crucially, that scoring is
187/// *cosmetic*: `record_shell` always records `Allow` (the command already ran),
188/// and the danger `class` rides along regardless. So under sustained load we
189/// shed the summary, not the record — the row is still logged with its class,
190/// just without the prose. `capacity` is the burst a quiet session banks;
191/// `refill_per_sec` is the steady ceiling on inferences/sec the recorder can
192/// impose on the serve thread.
193struct ScoreBudget {
194    tokens: f64,
195    capacity: f64,
196    refill_per_sec: f64,
197    last: std::time::Instant,
198}
199
200impl ScoreBudget {
201    fn new(capacity: f64, refill_per_sec: f64, now: std::time::Instant) -> Self {
202        Self {
203            tokens: capacity,
204            capacity,
205            refill_per_sec,
206            last: now,
207        }
208    }
209
210    /// Refill for elapsed time, then try to spend one token. Returns `false` when
211    /// the budget is exhausted — the caller skips the expensive scoring and falls
212    /// back to a rules-only (summary-less) record.
213    fn try_spend(&mut self, now: std::time::Instant) -> bool {
214        let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
215        self.last = now;
216        self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
217        if self.tokens >= 1.0 {
218            self.tokens -= 1.0;
219            true
220        } else {
221            false
222        }
223    }
224}
225
226/// Agents whose CLI shows a WORKING interactive y/N prompt for an ambiguous
227/// hold. For these, the hold is resolved by the agent's own UI, so a daemon
228/// queue entry would just orphan (no one ever calls `resolve_pending`).
229///
230/// Everyone else — Gemini, Antigravity, OpenCode (its plugin throws on `ask`),
231/// the `kintsugi-exec` MCP tool, and any future/unknown surface — has no
232/// interactive prompt, so the human resolves the hold via the queue (the Held
233/// screen / `kintsugi queue` / `approve`). Default to enqueueing, so a new
234/// agent never silently drops a hold the user can't recover.
235const AGENTS_WITH_NATIVE_ASK: &[&str] = &["claude-code", "qwen", "copilot", "cursor", "codex"];
236
237/// Does THIS held command need a daemon-side queue entry?
238///
239/// Catastrophic always does (the dialect maps Hold→Deny, so the agent can't
240/// resolve it and the human runs it via `kintsugi run`). Ambiguous needs one
241/// for every agent EXCEPT those with a working native ask — see the constant.
242fn needs_queue_entry(cmd: &ProposedCommand, class: kintsugi_core::Class) -> bool {
243    if class == kintsugi_core::Class::Catastrophic {
244        return true;
245    }
246    !AGENTS_WITH_NATIVE_ASK.contains(&cmd.agent.as_str())
247}
248
249/// The only op string [`shutdown_op`](Daemon::shutdown_op) serves. The proof's
250/// op binding is checked against THIS constant, not against the caller's op
251/// echo: a challenge minted for any other op (`"approve:<id>"`, junk) must
252/// never authorize a shutdown by replaying the same op string back.
253const SHUTDOWN_OP: &str = "shutdown";
254
255/// Bound and canonicalize a caller-supplied op string before it reaches the audit
256/// log. Keeps `approve:<uuid>` intact (the shape the protocol uses), replaces any
257/// other byte with `?`, and caps the whole thing so a hostile peer cannot grow the
258/// never-deletable log with megabyte-long "op" names.
259fn sanitize_op(op: &str) -> String {
260    const MAX: usize = 64;
261    let mut out = String::with_capacity(op.len().min(MAX));
262    for ch in op.chars().take(MAX) {
263        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.') {
264            out.push(ch);
265        } else {
266            out.push('?');
267        }
268    }
269    if op.chars().count() > MAX {
270        out.push('…');
271    }
272    out
273}
274
275impl Daemon {
276    /// Open the daemon backed by the event log at `db_path`, creating parent dirs.
277    pub fn open(db_path: impl Into<PathBuf>) -> Result<Self> {
278        let db_path = db_path.into();
279        if let Some(parent) = db_path.parent() {
280            std::fs::create_dir_all(parent)
281                .with_context(|| format!("create data dir {}", parent.display()))?;
282        }
283        let data_dir = db_path
284            .parent()
285            .unwrap_or_else(|| std::path::Path::new("."))
286            .to_path_buf();
287        // Keep the data dir private to the owning user: the event log records raw
288        // commands verbatim (spine #3), which can include secrets passed on a
289        // command line. We never scrub the verbatim record, so we protect it at
290        // rest (0700 dir, 0600 db) instead of leaving it world-readable.
291        #[cfg(unix)]
292        ipc::set_mode(&data_dir, 0o700);
293        let snapshot_dir = data_dir.join("snapshots");
294        let kill_path = data_dir.join(KILL_SWITCH_FILE);
295        let log = EventLog::open(&db_path)
296            .with_context(|| format!("open event log at {}", db_path.display()))?;
297        // Owner-only on the db (and its WAL/SHM siblings) — it holds verbatim
298        // commands that may contain secrets.
299        #[cfg(unix)]
300        for suffix in ["", "-wal", "-shm"] {
301            let p = if suffix.is_empty() {
302                db_path.clone()
303            } else {
304                PathBuf::from(format!("{}{suffix}", db_path.display()))
305            };
306            if p.exists() {
307                ipc::set_mode(&p, 0o600);
308            }
309        }
310        // Resolve the admin vault path here at startup (the daemon is launched by
311        // the admin/systemd, so its environment — not a later caller's — decides the
312        // location). The contents are read fresh per op, never cached.
313        let vault_path = admin::default_vault_path();
314        // Rebuild information-flow taint by replaying the durable taint stream, so
315        // a restart reconstructs taint instead of failing open (Provenance item D).
316        // A load failure degrades to empty taint rather than aborting startup, but
317        // is logged loudly — the base rules and the rest of the daemon still run.
318        let taint = match log.load_taint_events() {
319            Ok(events) => TaintState::from_events(events.iter()),
320            Err(e) => {
321                eprintln!("kintsugi-daemon: failed to replay taint events: {e}");
322                TaintState::new()
323            }
324        };
325        // The provision latch: a machine that recorded a provision must never fall
326        // back to bare approval just because the vault file disappeared.
327        let vault_expected = log.has_provision_marker().unwrap_or(false);
328        Ok(Self {
329            log,
330            mode: Mode::default(),
331            scorer: kintsugi_model::default_scorer(),
332            snapshot_dir,
333            kill_path,
334            vault_path,
335            vault_expected,
336            pending: RefCell::new(None),
337            shutdown: Cell::new(false),
338            throttle: RefCell::new(AuthThrottle::default()),
339            taint: RefCell::new(taint),
340            denial_streak: RefCell::new(std::collections::HashMap::new()),
341            // Burst of 8 banked by a quiet session; steady ceiling of 4 model
342            // scorings/sec on the serve thread under a sustained recorder flood.
343            score_budget: RefCell::new(ScoreBudget::new(8.0, 4.0, std::time::Instant::now())),
344        })
345    }
346
347    /// Apply a taint transition to the session/file taint state.
348    ///
349    /// Fed by the content-tool observation surface (Phase 6.2) and by reset
350    /// policy. Pure state update — the decision path consults this; it never lets
351    /// a model change it (spine: rules decide, model only explains).
352    ///
353    /// Persist-then-apply: the transition is written to the durable, append-only
354    /// taint stream first (so it survives a daemon restart via replay in
355    /// [`open`](Self::open)), then applied to live in-memory state. The persist is
356    /// best-effort — a write failure is logged but never panics the daemon or
357    /// drops protection for the current session; it only risks losing this taint
358    /// across a future restart.
359    ///
360    /// Segment G: the event's `source_id` is redacted *before* both the persist and
361    /// the apply. A source identifier is meant to be an identifier only, but a URL
362    /// can carry a credential (`https://u:tok@host/p`, a colonless PAT-as-username,
363    /// `?api_key=…`). Normalizing at this single ingest boundary means the redacted
364    /// form is the only one that ever reaches the append-only (unscrubbable) log
365    /// row, the replayed state, the provenance trail, or an agent-facing reason.
366    pub fn apply_taint(&self, event: &TaintEvent) {
367        let event = event.with_redacted_source_id();
368        if let Err(e) = self.log.record_taint_event(&event) {
369            eprintln!("kintsugi-daemon: failed to persist taint event: {e}");
370        }
371        self.taint.borrow_mut().apply(&event);
372    }
373
374    /// Apply a file-write taint transition (V1.1): a tainted session wrote
375    /// `path`, so a later reader of that path inherits the session's taint through
376    /// [`TaintEvent::WriteFile`].
377    ///
378    /// Gated on the effective policy for the *writing session's* cwd — the same
379    /// `[provenance] enabled` switch that arms the trifecta floor. With the guard
380    /// off nothing is recorded: a path label would be inert state the operator
381    /// explicitly disabled.
382    ///
383    /// A clean session can propagate nothing, so its write is skipped outright (it
384    /// would be a no-op transition): that keeps frequent benign edits out of the
385    /// append-only taint stream instead of appending a no-op row per file. Beyond
386    /// that this follows [`apply_taint`](Self::apply_taint) exactly — persist, then
387    /// apply — and carries no `source_id`, so there is nothing to redact (segment
388    /// G). `path` is an identifier; write content never reaches this boundary.
389    pub fn apply_write(&self, session: &str, path: &str, cwd: &std::path::Path) {
390        if session.is_empty() || path.trim().is_empty() {
391            return;
392        }
393        if !load_policy(cwd).provenance_enabled() {
394            return;
395        }
396        if !self.is_session_tainted(Some(session)) {
397            return;
398        }
399        self.apply_taint(&TaintEvent::WriteFile {
400            session: session.to_string(),
401            path: std::path::PathBuf::from(path),
402        });
403    }
404
405    /// Apply a file-read taint transition (V1.1): a session read `path`, and if an
406    /// earlier tainted session labelled that path, the reader inherits the taint.
407    ///
408    /// This is the consumer that makes write propagation mean anything — without
409    /// it `TaintEvent::WriteFile` fills a map nothing reads, and "the agent
410    /// exfiltrated what it learned by writing and re-reading a file" stays
411    /// invisible. Same gating as [`apply_write`](Self::apply_write): the policy of
412    /// the reading session's cwd decides, a clean path is skipped so ordinary
413    /// reads never touch the append-only taint stream, and an already-tainted
414    /// reader is a no-op.
415    ///
416    /// Observation only: it never blocks, never enqueues, and never influences a
417    /// verdict; `path` is an identifier and the file's content is never read.
418    pub fn apply_read(&self, session: &str, path: &str, cwd: &std::path::Path) {
419        if session.is_empty() || path.trim().is_empty() {
420            return;
421        }
422        if !load_policy(cwd).provenance_enabled() {
423            return;
424        }
425        if self.is_session_tainted(Some(session)) {
426            return; // already tainted: the transition would be a no-op
427        }
428        if !self
429            .taint
430            .borrow()
431            .is_path_tainted(std::path::Path::new(path))
432        {
433            return; // nobody labelled this path
434        }
435        self.apply_taint(&TaintEvent::ReadFile {
436            session: session.to_string(),
437            path: std::path::PathBuf::from(path),
438        });
439    }
440
441    /// Whether the given session has been influenced by untrusted content. A
442    /// `None` (untracked) session is reported as not tainted.
443    pub fn is_session_tainted(&self, session: Option<&str>) -> bool {
444        self.taint.borrow().is_session_tainted(session)
445    }
446
447    /// The session's accumulated provenance labels, if any — the in-process read
448    /// the provenance trail (P6.4) will surface. Source identifiers are already
449    /// redacted at ingest (see [`apply_taint`](Self::apply_taint)), so callers and
450    /// the eventual IPC view only ever see secret-free ids.
451    pub fn session_provenance(&self, session: &str) -> Option<kintsugi_core::TaintSet> {
452        self.taint.borrow().session_taint(session).cloned()
453    }
454
455    /// Build the human-readable provenance trail for a command (P6.4): the session's
456    /// untrusted reads, then this command's sensitive read → egress sink → the
457    /// trifecta rule that fired. Identifiers only (no secret contents). This is the
458    /// forensic chain the CLI/TUI renders on a held trifecta and the audit replay
459    /// uses to reconstruct "everything descended from source X".
460    pub fn provenance_trail(&self, cmd: &ProposedCommand) -> Vec<kintsugi_core::ProvStep> {
461        use kintsugi_core::ProvStep;
462        let session = cmd.session.as_deref();
463        // The trail explains *untrusted-content provenance*. A clean session has
464        // none, so its trail is empty even if the command reads a secret or hits a
465        // sink — there is nothing for those legs to descend from, and no rule fires.
466        let Some(set) = session.and_then(|s| self.session_provenance(s)) else {
467            return Vec::new();
468        };
469        if !set.is_tainted() {
470            return Vec::new();
471        }
472        let mut trail = kintsugi_core::untrusted_trail(&set);
473        let sensitive = kintsugi_core::is_sensitive_read(cmd);
474        let egress = kintsugi_core::is_egress_sink(cmd);
475        if let Some(path) = &sensitive {
476            trail.push(ProvStep::SensitiveRead { path: path.clone() });
477        }
478        if let Some(target) = &egress {
479            trail.push(ProvStep::EgressSink {
480                target: target.clone(),
481            });
482        }
483        let outcome = kintsugi_core::evaluate_trifecta(true, sensitive.is_some(), egress.is_some());
484        if let Some(rule) = outcome.rule() {
485            trail.push(ProvStep::RuleFired {
486                rule: rule.to_string(),
487            });
488        }
489        trail
490    }
491
492    /// Apply the Provenance trifecta as a deterministic class **floor**: a command
493    /// in a tainted session that reads a secret and reaches an egress sink is the
494    /// lethal trifecta and is forced to the catastrophic hard floor. Escalation
495    /// only — it can raise the class, never lower it (spine: monotonic caution).
496    ///
497    /// The trifecta can fire only when the session is *currently* tainted. Taint
498    /// is durable across daemon restarts (item D): transitions are persisted and
499    /// replayed on [`open`](Self::open), so a restart no longer silently clears it.
500    /// This remains interception, not an unbypassable firewall (e.g. a tool run by
501    /// absolute path can dodge observation); the base rules still stand regardless.
502    fn trifecta_floor(
503        &self,
504        cmd: &ProposedCommand,
505        policy: &kintsugi_core::Policy,
506        base_class: kintsugi_core::Class,
507        base_rule: String,
508    ) -> (kintsugi_core::Class, String) {
509        use kintsugi_core::Trifecta;
510        if !policy.provenance_enabled() || !self.is_session_tainted(cmd.session.as_deref()) {
511            return (base_class, base_rule);
512        }
513        let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
514        let egress = kintsugi_core::is_egress_sink(cmd).is_some();
515        let outcome = kintsugi_core::evaluate_trifecta(true, sensitive, egress);
516        let floor = match outcome {
517            // The full trifecta: a hard floor that inherits the no-downgrade guard.
518            Trifecta::Block => kintsugi_core::Class::Catastrophic,
519            // Lesser bands: held (attended) / denied (unattended), tunable by policy.
520            Trifecta::Hold | Trifecta::Annotate => kintsugi_core::Class::Ambiguous,
521            Trifecta::None => return (base_class, base_rule),
522        };
523        let class = base_class.max(floor);
524        // Only relabel the reason when the trifecta actually raised the floor;
525        // otherwise the base rule was already at least this severe.
526        if class.severity() > base_class.severity() {
527            let rule = outcome.rule().unwrap_or("TRIFECTA");
528            (class, format!("{rule}:provenance ({base_rule})"))
529        } else {
530            (class, base_rule)
531        }
532    }
533
534    /// The advisory dependency hint for the ambiguous taint band (Phase 6 V1.1,
535    /// hardening item H). Deterministic and I/O-free: string matching of the
536    /// command against the session's — already-redacted — untrusted identifiers.
537    ///
538    /// The band is exactly what [`trifecta_floor`](Self::trifecta_floor)
539    /// governs at the partial level: provenance enabled, the session currently
540    /// tainted, and the command carrying exactly ONE leg — a sensitive read or
541    /// an egress sink, i.e. `Trifecta::Hold`/`Annotate`. Not `Block` (that lands
542    /// in the catastrophic arm, which keeps its summary-only behavior and never
543    /// computes a hint) and not `None` (no leg: the floor is inert, and the
544    /// command is judged purely on its own merits).
545    ///
546    /// Note the floor usually does not RAISE the class to get here — a
547    /// leg-bearing command is already ambiguous at baseline, so the reason text
548    /// alone can't prove band membership. This re-derives the floor's own three
549    /// inputs instead (tainted + the same two predicates), which stays exactly
550    /// in step with it by construction.
551    fn dependency_hint(
552        &self,
553        cmd: &ProposedCommand,
554        policy: &kintsugi_core::Policy,
555    ) -> DependencyHint {
556        use kintsugi_core::Trifecta;
557        if !policy.provenance_enabled() {
558            return DependencyHint::Unknown;
559        }
560        let Some(trail) = cmd
561            .session
562            .as_deref()
563            .and_then(|s| self.session_provenance(s))
564        else {
565            return DependencyHint::Unknown;
566        };
567        if !trail.is_tainted() {
568            return DependencyHint::Unknown;
569        }
570        let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
571        let egress = kintsugi_core::is_egress_sink(cmd).is_some();
572        match kintsugi_core::evaluate_trifecta(true, sensitive, egress) {
573            Trifecta::Hold | Trifecta::Annotate => kintsugi_model::dependency_hint(cmd, &trail),
574            Trifecta::Block | Trifecta::None => DependencyHint::Unknown,
575        }
576    }
577
578    /// Whether an authenticated shutdown has been accepted (serve loop should exit).
579    pub fn should_shutdown(&self) -> bool {
580        self.shutdown.get()
581    }
582
583    /// Read the current admin vault, fresh from the daemon-resolved path. Called on
584    /// every privileged op so a re-provision / password change applies immediately —
585    /// the daemon is the authority on the *path* (a caller can't redirect it), and
586    /// the contents are never cached, so there is no stale-vault class of bug.
587    fn current_vault(&self) -> VaultState {
588        match admin::load_vault(&self.vault_path) {
589            // The file is gone but this machine was provisioned: treat it as
590            // degraded so a deleted/renamed vault can never quietly re-enable
591            // bare approval or a bare shutdown.
592            VaultState::Unprovisioned if self.vault_expected => VaultState::Degraded(
593                "the admin vault was provisioned on this machine but its file is missing"
594                    .to_string(),
595            ),
596            other => other,
597        }
598    }
599
600    /// Issue a challenge for a privileged op. `locked=false` means no vault, so the
601    /// caller may proceed without a proof.
602    fn auth_begin(&self, op: &str) -> ipc::Response {
603        match self.current_vault() {
604            VaultState::Degraded(_) => ipc::Response::Error {
605                message: "admin vault is degraded; refusing privileged operations".into(),
606            },
607            VaultState::Locked(v) => {
608                let nonce = match admin::random_auth_nonce() {
609                    Ok(n) => n,
610                    Err(_) => {
611                        return ipc::Response::Error {
612                            message: "could not generate a challenge".into(),
613                        }
614                    }
615                };
616                let (salt, params) = v.auth_challenge();
617                *self.pending.borrow_mut() = Some((nonce.clone(), op.to_string()));
618                ipc::Response::Challenge {
619                    locked: true,
620                    nonce: hex::encode(&nonce),
621                    salt,
622                    params,
623                }
624            }
625            VaultState::Unprovisioned => ipc::Response::Challenge {
626                locked: false,
627                nonce: String::new(),
628                salt: String::new(),
629                params: kintsugi_core::admin::KdfParams::production(),
630            },
631        }
632    }
633
634    /// Complete an authenticated shutdown. Enforced against the daemon's own vault,
635    /// read fresh from disk so a just-provisioned vault is honored without a restart.
636    fn shutdown_op(
637        &self,
638        op: &str,
639        nonce_hex: Option<&str>,
640        proof_hex: Option<&str>,
641    ) -> ipc::Response {
642        // Pin the op: this handler serves `shutdown` only. Without the pin, a
643        // challenge minted for another op (e.g. `AuthBegin("approve:<id>")`)
644        // could authorize a shutdown by echoing the same op string back — the
645        // proof would verify over that op — and an unprovisioned daemon would
646        // shut down on ANY op string, no proof at all. Found by the Phase 7
647        // approval-auth adversarial suite (`approval_auth.rs`); a monotonic
648        // tightening (adds a refusal, never removes one).
649        if op != SHUTDOWN_OP {
650            self.record_admin(op, false, "op not served by shutdown");
651            return ipc::Response::Error {
652                message: format!("shutdown requires a `{SHUTDOWN_OP}` challenge"),
653            };
654        }
655        let vault = match self.current_vault() {
656            VaultState::Degraded(_) => {
657                self.record_admin(op, false, "vault degraded");
658                return ipc::Response::Error {
659                    message: "admin vault is degraded; refusing to stop".into(),
660                };
661            }
662            // Unprovisioned: there is no lock, so a clean shutdown is allowed.
663            VaultState::Unprovisioned => {
664                self.record_admin(op, true, "unprovisioned");
665                self.shutdown.set(true);
666                return ipc::Response::Ack;
667            }
668            VaultState::Locked(v) => v,
669        };
670        // Brute-force lockout, gated on a proof actually being offered: only a
671        // request carrying a nonce/proof can guess anything, so only those are
672        // throttled. A bare request cannot brute-force a secret, and counting it
673        // would let any local peer lock the human out of their own privileged ops
674        // (approve and shutdown share this budget) — a same-user DoS on the safety
675        // workflow, which is the opposite of what the throttle is for.
676        let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
677        if proof_offered {
678            if let Some(rem) = self.throttle.borrow().lockout_remaining() {
679                self.record_admin(op, false, "locked out");
680                return ipc::Response::Error {
681                    message: format!(
682                        "too many failed attempts; locked out for {}s",
683                        rem.as_secs() + 1
684                    ),
685                };
686            }
687        }
688        // The challenge is one-shot: take it regardless of the outcome.
689        let pending = self.pending.borrow_mut().take();
690        // A locked vault requires BOTH a nonce and a proof. If either is absent
691        // (the unauthenticated caller), fail without ever decoding a placeholder
692        // into the crypto path.
693        let ok = match (pending, nonce_hex, proof_hex) {
694            (Some((issued_nonce, issued_op)), Some(nonce_hex), Some(proof_hex)) => {
695                match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
696                    (Ok(nonce), Ok(proof)) => {
697                        issued_op == op
698                            && issued_nonce == nonce
699                            && vault.verify_proof(&nonce, op.as_bytes(), &proof)
700                    }
701                    _ => false,
702                }
703            }
704            _ => false,
705        };
706        if ok {
707            self.throttle.borrow_mut().reset();
708            self.record_admin(op, true, "authenticated");
709            self.shutdown.set(true);
710            ipc::Response::Ack
711        } else {
712            if proof_offered {
713                self.throttle.borrow_mut().record_failure();
714            }
715            // Distinguish a wrong password from a vault that simply can't carry a
716            // proof (provisioned before the asymmetric-auth scheme): the latter
717            // fails for *every* password, so a bare "authentication failed" reads
718            // as a bug. Point the user at the one-line fix instead.
719            if !vault.supports_proof() {
720                self.record_admin(op, false, "vault missing proof key");
721                return ipc::Response::Error {
722                    message:
723                        "admin vault has no auth key — re-run `kintsugi admin provision --force` \
724                              (the daemon picks it up immediately, no restart needed)"
725                            .into(),
726                };
727            }
728            self.record_admin(op, false, "authentication failed");
729            ipc::Response::Error {
730                message: "authentication failed".into(),
731            }
732        }
733    }
734
735    /// Complete an authenticated approval of queued command `id` (Phase 7,
736    /// anchored trust — the proof-of-human gate on self-approval).
737    ///
738    /// The design mirrors [`shutdown_op`](Self::shutdown_op) exactly:
739    /// - No vault → there is no secret to prove possession of, so approval is
740    ///   bare (the owner-only socket is the boundary; documented honestly in
741    ///   docs/security-assessment.md). This keeps the queue usable for users
742    ///   who never provisioned a vault — the gate must never brick the queue.
743    /// - Locked vault + bare request → **the threat case**: a same-user agent
744    ///   process that reached the socket tries to approve its own held
745    ///   command. Refused loudly with an actionable pointer at the human path,
746    ///   audited as a hash-chained `self-approval blocked` event, and counted
747    ///   by the same [`AuthThrottle`] as shutdown auth (5 free attempts, then
748    ///   30 s → doubling lockout, capped at 1 h) so hammering is defeated.
749    /// - Locked vault + nonce + proof → the one-shot pending challenge is
750    ///   consumed, the proof is verified op-bound (`"approve:<id>"`, so a proof
751    ///   can approve only the id it was issued for), and on success the
752    ///   approval resolves through the *usual* [`resolve_pending`] path — the
753    ///   kill-switch guard and the exactly-once CAS still apply. Auth decides
754    ///   *who may talk*; the rules layer still decides *what may happen*
755    ///   (spine: auth adds friction, it never unlocks).
756    /// - Policy opt-out (`[security] require_approval_proof = false`) accepts
757    ///   a bare approve again. The policy scope is the held command's repo
758    ///   (the same `.kintsugi.toml` scope that produced the hold), so one repo
759    ///   can opt out without weakening the default everywhere.
760    ///
761    /// `Deny` and `PrunePending` deliberately stay bare: an agent denying its
762    /// own held command is a nuisance, not a threat, and prune touches only the
763    /// queue, never the log.
764    fn approve_op(
765        &self,
766        id: &str,
767        nonce_hex: Option<&str>,
768        proof_hex: Option<&str>,
769    ) -> ipc::Response {
770        let op = format!("approve:{id}");
771        // The auth gate's policy scope: the held command's repo (same scope
772        // that decided the hold); the daemon's own cwd when the id is unknown.
773        let cwd = self
774            .log
775            .pending_command(id)
776            .ok()
777            .flatten()
778            .map(|c| c.cwd)
779            .unwrap_or_else(|| {
780                std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
781            });
782        let require_proof = load_policy(&cwd).require_approval_proof();
783
784        let vault = match self.current_vault() {
785            VaultState::Degraded(_) => {
786                self.record_admin(&op, false, "vault degraded");
787                return ipc::Response::Error {
788                    message: "admin vault is degraded; refusing privileged operations".into(),
789                };
790            }
791            // Unprovisioned: no lock exists, so a bare approval is allowed —
792            // the exact shutdown mirror.
793            VaultState::Unprovisioned => {
794                self.record_admin(&op, true, "unprovisioned");
795                return self.resolve_pending_response(id, Decision::Allow);
796            }
797            VaultState::Locked(v) => v,
798        };
799        // Brute-force lockout, shared with shutdown auth (same bounds) and gated on
800        // a proof actually being offered: a bare approve cannot guess a secret, so
801        // counting it would hand any local peer a DoS on the human's own approval
802        // and shutdown workflow. A success resets the shared budget.
803        let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
804        if proof_offered {
805            if let Some(rem) = self.throttle.borrow().lockout_remaining() {
806                self.record_admin(&op, false, "locked out");
807                return ipc::Response::Error {
808                    message: format!(
809                        "too many failed attempts; locked out for {}s",
810                        rem.as_secs() + 1
811                    ),
812                };
813            }
814        }
815        // Absence is None, never an empty string: a placeholder must never
816        // stand in for a real nonce/proof in the crypto path.
817        let nonce_hex = nonce_hex.filter(|s| !s.trim().is_empty());
818        let proof_hex = proof_hex.filter(|s| !s.trim().is_empty());
819        match (nonce_hex, proof_hex) {
820            // Bare under the opt-out: the pre-Phase-7 behavior, restored — but
821            // never silent. An approval that reached the queue without proof is
822            // exactly what a human reading the timeline must be able to see, so
823            // it writes its own audit row; the log can never show this as
824            // `human:allow` with nothing behind it.
825            (None, None) if !require_proof => {
826                self.record_admin(&op, true, "policy-opt-out");
827                self.resolve_pending_response(id, Decision::Allow)
828            }
829            // Bare under the default: the self-approval attempt. Loud and audited —
830            // never silent. Deliberately NOT counted against the brute-force budget:
831            // it carries no proof, so it cannot be guessing, and counting it would
832            // let one such request per window lock the human out of approving.
833            (None, None) => {
834                self.record_admin(&op, false, "self-approval blocked");
835                ipc::Response::Error {
836                    message: format!(
837                        "approval requires proof — run `kintsugi approve {id}` (or \
838                          `kintsugi run {id}`) and enter the admin password; see \
839                          docs/policy.md to allow bare approval"
840                    ),
841                }
842            }
843            // The one-shot challenge is consumed regardless of the outcome.
844            (Some(nonce_hex), Some(proof_hex)) => {
845                let pending = self.pending.borrow_mut().take();
846                let ok = match pending {
847                    Some((issued_nonce, issued_op)) => {
848                        match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
849                            (Ok(nonce), Ok(proof)) => {
850                                issued_op == op
851                                    && issued_nonce == nonce
852                                    && vault.verify_proof(&nonce, op.as_bytes(), &proof)
853                            }
854                            _ => false,
855                        }
856                    }
857                    None => false,
858                };
859                if ok {
860                    self.throttle.borrow_mut().reset();
861                    self.record_admin(&op, true, "authenticated");
862                    self.resolve_pending_response(id, Decision::Allow)
863                } else {
864                    self.throttle.borrow_mut().record_failure();
865                    // Distinguish a wrong password from a vault that simply
866                    // can't carry a proof (pre-v2): the latter fails for every
867                    // password, so point at the one-line fix instead.
868                    if !vault.supports_proof() {
869                        self.record_admin(&op, false, "vault missing proof key");
870                        return ipc::Response::Error {
871                            message: "admin vault has no auth key — re-run `kintsugi admin \
872                                  provision --force` (the daemon picks it up immediately, no \
873                                  restart needed)"
874                                .into(),
875                        };
876                    }
877                    self.record_admin(&op, false, "authentication failed");
878                    ipc::Response::Error {
879                        message: "authentication failed".into(),
880                    }
881                }
882            }
883            // Half an attempt (a nonce without a proof or vice versa): not
884            // bare, and not a proof — count it as a failed attempt.
885            _ => {
886                self.throttle.borrow_mut().record_failure();
887                self.record_admin(&op, false, "authentication failed");
888                ipc::Response::Error {
889                    message: "authentication failed".into(),
890                }
891            }
892        }
893    }
894
895    /// Record a privileged-operation attempt as a hash-chained audit event, so a
896    /// forced stop — successful or not — is always visible on the timeline.
897    fn record_admin(&self, op: &str, ok: bool, reason: &str) {
898        // `op` is caller-supplied (`approve:<id>`) and lands in the append-only,
899        // never-deletable event log, so it is validated and bounded here: without
900        // this, any local peer could write attacker-chosen, unredacted text of up
901        // to MAX_FRAME bytes into the audit trail on every refused attempt.
902        let op = sanitize_op(op);
903        let op = op.as_str();
904        let raw = format!(
905            "admin {op} — {}",
906            if ok { "authenticated" } else { "denied" }
907        );
908        let cmd = ProposedCommand::new(
909            "admin",
910            std::path::Path::new("."),
911            vec!["admin".to_string(), op.to_string()],
912            raw,
913        );
914        let decision = if ok { Decision::Allow } else { Decision::Deny };
915        let verdict = Verdict::rules(
916            kintsugi_core::Class::Safe,
917            decision,
918            format!("admin:{op}:{reason}"),
919        );
920        let _ = self.log.log_event(&cmd, &verdict, None);
921    }
922
923    /// Whether the panic kill-switch is currently engaged.
924    pub fn kill_switch_engaged(&self) -> bool {
925        self.kill_path.exists()
926    }
927
928    /// The directory snapshots are stored under.
929    pub fn snapshot_dir(&self) -> &std::path::Path {
930        &self.snapshot_dir
931    }
932
933    /// Swap in a specific scorer (used by tests).
934    pub fn with_scorer(mut self, scorer: Box<dyn kintsugi_model::Scorer>) -> Self {
935        self.scorer = scorer;
936        self
937    }
938
939    /// The name of the active Tier-2 scorer backend.
940    pub fn scorer_name(&self) -> &str {
941        self.scorer.name()
942    }
943
944    /// Open the daemon at the default database path.
945    pub fn open_default() -> Result<Self> {
946        Self::open(default_db_path())
947    }
948
949    /// Set the operating mode (attended / unattended / notify).
950    pub fn with_mode(mut self, mode: Mode) -> Self {
951        self.mode = mode;
952        self
953    }
954
955    /// The current operating mode.
956    pub fn mode(&self) -> Mode {
957        self.mode
958    }
959
960    /// Decide what to do with a proposed command.
961    ///
962    /// Order: (1) load the effective policy (global ← repo) which may set the mode
963    /// and risk threshold; (2) classify with the Tier-1 rule engine; (3) **Tier-2
964    /// model** — for the ambiguous band only, fill `summary`+`risk` and, in
965    /// unattended mode, apply the graduated threshold (below → allow, at/above →
966    /// deny); the model summarizes a catastrophic command for the hold card but
967    /// never changes its decision; (4) apply policy allow/deny (never a
968    /// catastrophic downgrade); (5) apply decision memory.
969    ///
970    /// Security spine: rules classify; the model only explains and scores the
971    /// ambiguous band, and its influence is escalation-only. Safe stays on the
972    /// model-free fast path.
973    pub fn decide(&self, cmd: &ProposedCommand) -> Verdict {
974        // Panic kill-switch: halt everything, including Safe, the instant it is
975        // engaged. Checked first, before any other logic.
976        if self.kill_switch_engaged() {
977            let m = kintsugi_core::classify(cmd);
978            return Verdict::rules(m.class, Decision::Deny, "kill-switch: all actions halted");
979        }
980
981        let policy = load_policy(&cmd.cwd);
982        let mode = policy.mode.unwrap_or(self.mode);
983
984        let m = kintsugi_core::classify(cmd);
985        // Provenance (Phase 6): apply the trifecta as a deterministic class floor
986        // (escalation-only) before the model ever runs. Taint never downgrades.
987        let (class, rule) = self.trifecta_floor(cmd, &policy, m.class, m.rule);
988        let mut verdict = Verdict::rules(class, kintsugi_core::decide(class, mode), &rule);
989
990        // Tier-2 model: ambiguous band gets summary + risk (+ graduated decision);
991        // catastrophic gets a summary for the hold card. Safe is never scored.
992        match class {
993            kintsugi_core::Class::Ambiguous => {
994                // Phase 6 V1.1 · hardening item H: in the ambiguous TAINT band —
995                // where the provenance floor engaged at the partial level — the
996                // Tier-2 step gains a deterministic, advisory dependency hint:
997                // does this command plausibly consume an identifier from the
998                // session's untrusted trail? Pure string matching (no inference,
999                // no I/O), so it adds no scoring call and cannot bypass the
1000                // recorder's ScoreBudget. Escalation-only (spine #2): the hint
1001                // may turn the attended Hold into a Deny; it can never unlock or
1002                // downgrade anything, and the human paths below (policy
1003                // allowlist, decision memory) still have the final say.
1004                let hint = self.dependency_hint(cmd, &policy);
1005                let out = self.scorer.score_with_hint(cmd, class, &rule, hint);
1006                verdict.summary = Some(out.summary);
1007                verdict.risk = Some(out.risk);
1008                verdict.tier = 2;
1009                if mode == Mode::Unattended {
1010                    // Spine rule #2 (monotonic model influence): the model may only
1011                    // ADD caution. The unattended baseline for an ambiguous command
1012                    // is Deny (queued for a human); the model records risk for that
1013                    // review but NEVER downgrades Deny -> Allow. Auto-proceeding an
1014                    // ambiguous command unattended is only possible via an explicit
1015                    // human allowlist (.kintsugi.toml / decision memory) below — a human
1016                    // decision, not the model's. The hint changes nothing here.
1017                    verdict.reason = format!(
1018                        "model:risk={} ({}) — unattended holds ambiguous for review",
1019                        out.risk, rule
1020                    );
1021                } else if hint == DependencyHint::LikelyDependent
1022                    && verdict.decision == Decision::Hold
1023                {
1024                    // The advisory escalation: Hold -> Deny, marked for audit.
1025                    // `advisory:dependent` appears in a reason ONLY here.
1026                    verdict.decision = Decision::Deny;
1027                    verdict.reason = format!("advisory:dependent ({})", verdict.reason);
1028                }
1029            }
1030            kintsugi_core::Class::Catastrophic => {
1031                let out = self.scorer.score(cmd, class, &rule);
1032                verdict.summary = Some(out.summary);
1033                verdict.tier = 2;
1034            }
1035            kintsugi_core::Class::Safe => {}
1036        }
1037
1038        // Policy can escalate (deny) or tame (allow) — never downgrade catastrophic.
1039        let action = policy.action_for(&cmd.raw);
1040        verdict = kintsugi_core::adjust_for_policy(verdict, action, mode);
1041
1042        // Decision memory has the final say — but, like policy, it can never
1043        // auto-downgrade a CATASTROPHIC command (that hard floor only lifts via an
1044        // in-the-moment human decision, never a stored/replayed one). Memory deny
1045        // always applies (escalation-only).
1046        let repo = repo_key(&cmd.cwd);
1047        let hash = kintsugi_core::command_hash(&cmd.raw);
1048        match self.log.memory_lookup(&repo, &hash) {
1049            Ok(Some(Decision::Allow)) if verdict.class != kintsugi_core::Class::Catastrophic => {
1050                verdict.decision = Decision::Allow;
1051                verdict.reason = format!("memory:allow ({})", verdict.reason);
1052            }
1053            Ok(Some(Decision::Deny)) => {
1054                verdict.decision = Decision::Deny;
1055                verdict.reason = format!("memory:deny ({})", verdict.reason);
1056            }
1057            _ => {}
1058        }
1059        verdict
1060    }
1061
1062    /// Handle one proposal: decide, snapshot if destructive+allowed, record, and —
1063    /// if held — enqueue it for approval. Returns the verdict.
1064    pub fn handle(&self, cmd: ProposedCommand) -> Verdict {
1065        let mut verdict = self.decide(&cmd);
1066        let (snapshot_id, snapshot_failed) = self.maybe_snapshot(&cmd, &verdict);
1067        if verdict.decision == Decision::Allow && verdict.class != kintsugi_core::Class::Safe {
1068            let note = if snapshot_failed {
1069                Some("snapshot failed — NOT reversible by undo")
1070            } else if !kintsugi_core::snapshot::is_fully_reversible(&cmd) {
1071                Some("target can't be fully snapshotted — undo may not restore everything")
1072            } else {
1073                None
1074            };
1075            if let Some(n) = note {
1076                verdict.reason = format!("{} [⚠ {n}]", verdict.reason);
1077            }
1078        }
1079        if let Err(e) = self.log.log_event(&cmd, &verdict, snapshot_id.as_deref()) {
1080            // Spine #4: a command we cannot write to the append-only log must not run
1081            // unrecorded. Fail closed — refuse an Allow rather than execute it dark.
1082            eprintln!("kintsugi-daemon: failed to record event: {e}");
1083            if verdict.decision == Decision::Allow {
1084                verdict.decision = Decision::Deny;
1085                verdict.reason = format!(
1086                    "audit-log write failed; denied fail-closed ({})",
1087                    verdict.reason
1088                );
1089            }
1090        }
1091        if verdict.decision == Decision::Hold && needs_queue_entry(&cmd, verdict.class) {
1092            if let Err(e) = self
1093                .log
1094                .enqueue_pending(&cmd, verdict.class, &verdict.reason)
1095            {
1096                eprintln!("kintsugi-daemon: failed to enqueue pending: {e}");
1097            }
1098        }
1099        // Negotiation is the LAST step so the audit log and the approval queue keep
1100        // the clean, rule-grounded reason; only the verdict returned to the agent
1101        // carries the model-facing instruction. This never changes the decision —
1102        // it only reframes a block — so it cannot unlock the gate (spine).
1103        self.negotiate(cmd.session.as_deref(), verdict)
1104    }
1105
1106    /// Reframe a *blocked* verdict for the agent (model-facing reason + the
1107    /// "materially safer alternative / else ask the user" instruction) and drive the
1108    /// consecutive-denial circuit breaker. Allow/ask are returned unchanged; an
1109    /// Allow resets the session's streak. Decision-preserving by construction.
1110    fn negotiate(&self, session: Option<&str>, mut verdict: Verdict) -> Verdict {
1111        use kintsugi_core::Class;
1112        // The agent receives a hard "no" for a Deny, or for a catastrophic Hold (the
1113        // adapter maps that to deny — an in-agent allow would skip the snapshot). An
1114        // ambiguous Hold becomes a native `ask`, which is not a negotiation deny.
1115        let blocked = verdict.decision == Decision::Deny
1116            || (verdict.decision == Decision::Hold && verdict.class == Class::Catastrophic);
1117        if !blocked {
1118            if verdict.decision == Decision::Allow {
1119                if let Some(s) = session {
1120                    self.denial_streak.borrow_mut().remove(s);
1121                }
1122            }
1123            return verdict;
1124        }
1125
1126        // Count consecutive blocks per session; an untracked session can't be
1127        // counted, so it just never trips (the reason is still grounded).
1128        let tripped = match session {
1129            Some(s) => {
1130                let mut streaks = self.denial_streak.borrow_mut();
1131                let count = streaks.entry(s.to_string()).or_insert(0);
1132                *count += 1;
1133                *count >= kintsugi_core::negotiate::CONSECUTIVE_DENY_LIMIT
1134            }
1135            None => false,
1136        };
1137
1138        verdict.reason = if tripped {
1139            kintsugi_core::negotiate::circuit_breaker_reason(&verdict.reason)
1140        } else {
1141            kintsugi_core::negotiate::model_deny_reason(&verdict.reason)
1142        };
1143        verdict
1144    }
1145
1146    /// Approve or deny a queued command by id: record the human decision (and, on
1147    /// allow, snapshot), then mark the queue entry resolved. The originating
1148    /// caller (MCP poll / shim) executes; this never runs the command itself.
1149    ///
1150    /// A human may approve any class here — including catastrophic — which is the
1151    /// deliberate human override (the *model* never can). Returns whether the id
1152    /// was found in the queue.
1153    pub fn resolve_pending(&self, id: &str, decision: Decision) -> Result<bool> {
1154        // While the kill-switch is engaged, nothing is approvable.
1155        if decision == Decision::Allow && self.kill_switch_engaged() {
1156            anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before approving");
1157        }
1158        let status = if decision == Decision::Allow {
1159            "approved"
1160        } else {
1161            "denied"
1162        };
1163        // Claim the entry exactly once. If the CAS doesn't win, the command was
1164        // already resolved (or never queued) — return false rather than snapshot
1165        // and log a second time, which is what would double-run an approved cmd.
1166        if !self.log.cas_pending_status(id, "pending", status)? {
1167            return Ok(false);
1168        }
1169        let Some(cmd) = self.log.pending_command(id)? else {
1170            return Ok(false);
1171        };
1172        self.resolve(&ipc::Resolution {
1173            command: cmd,
1174            decision,
1175            remember: false,
1176        })?;
1177        Ok(true)
1178    }
1179
1180    /// Snapshot the paths a command will touch, when it is allowed and not Safe.
1181    /// Returns the snapshot id to attach to the event, if one was taken.
1182    fn maybe_snapshot(&self, cmd: &ProposedCommand, verdict: &Verdict) -> (Option<String>, bool) {
1183        if verdict.decision != Decision::Allow || verdict.class == kintsugi_core::Class::Safe {
1184            return (None, false);
1185        }
1186        match kintsugi_core::capture_snapshot(&self.snapshot_dir, cmd) {
1187            Ok(Some(manifest)) => {
1188                if let Err(e) = self.log.record_snapshot(&manifest) {
1189                    eprintln!("kintsugi-daemon: failed to record snapshot: {e}");
1190                    return (None, true);
1191                }
1192                (Some(manifest.id), false)
1193            }
1194            Ok(None) => (None, false),
1195            Err(e) => {
1196                eprintln!("kintsugi-daemon: snapshot failed: {e}");
1197                (None, true)
1198            }
1199        }
1200    }
1201
1202    /// Handle a human's resolution of a held command: record the final decision
1203    /// and, if requested, remember it for this exact command in this repo.
1204    pub fn resolve(&self, resolution: &ipc::Resolution) -> Result<()> {
1205        // Kill-switch hard floor: while engaged, no Allow resolves — not via the
1206        // queue (resolve_pending) and not via this direct path (shim hold card /
1207        // raw Request::Resolve). Mirrors the guard in resolve_pending().
1208        if resolution.decision == Decision::Allow && self.kill_switch_engaged() {
1209            anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before allowing");
1210        }
1211        let cmd = &resolution.command;
1212        // Re-classify so the recorded class is accurate even though a human chose.
1213        let m = kintsugi_core::classify(cmd);
1214        // A catastrophic command is never *remembered* as always-allow — the hard
1215        // floor must re-prompt every time; `[r]` on a catastrophic acts as allow-once.
1216        let remember = resolution.remember
1217            && !(resolution.decision == Decision::Allow
1218                && m.class == kintsugi_core::Class::Catastrophic);
1219        let reason = match resolution.decision {
1220            Decision::Allow if remember => "human:always-allow",
1221            Decision::Allow => "human:allow",
1222            Decision::Deny if remember => "human:always-deny",
1223            Decision::Deny => "human:deny",
1224            Decision::Hold => "human:hold",
1225        };
1226        let verdict = Verdict::rules(m.class, resolution.decision, reason);
1227        // Snapshot before a human-approved destructive command runs.
1228        let (snapshot_id, _) = self.maybe_snapshot(cmd, &verdict);
1229        self.log.log_event(cmd, &verdict, snapshot_id.as_deref())?;
1230
1231        if remember && resolution.decision != Decision::Hold {
1232            let repo = repo_key(&cmd.cwd);
1233            let hash = kintsugi_core::command_hash(&cmd.raw);
1234            self.log.remember(&repo, &hash, resolution.decision)?;
1235        }
1236
1237        // If this command was queued (e.g. a shim hold the human just answered),
1238        // mark the queue entry resolved so it leaves `kintsugi queue`.
1239        if resolution.decision != Decision::Hold {
1240            let status = if resolution.decision == Decision::Allow {
1241                "approved"
1242            } else {
1243                "denied"
1244            };
1245            let _ = self.log.set_pending_status(&cmd.id.to_string(), status);
1246        }
1247        Ok(())
1248    }
1249
1250    /// Record an observed filesystem change from the backstop watcher. Logged as
1251    /// `agent = "fs-watch"`, decision Allow (it already happened) — its purpose is
1252    /// to keep the timeline and undo complete for actions that bypassed
1253    /// interception.
1254    pub fn observe(&self, obs: &ipc::Observation) -> Result<()> {
1255        let raw = format!("{} {}", obs.kind, obs.path);
1256        let cwd = std::path::Path::new(&obs.path)
1257            .parent()
1258            .map(|p| p.to_path_buf())
1259            .unwrap_or_default();
1260        let cmd = ProposedCommand::new(
1261            "fs-watch",
1262            cwd,
1263            vec![obs.kind.clone(), obs.path.clone()],
1264            raw,
1265        );
1266        let verdict = Verdict::rules(
1267            kintsugi_core::Class::Safe,
1268            Decision::Allow,
1269            format!("fs:{}", obs.kind),
1270        );
1271        self.log.log_event(&cmd, &verdict, None)?;
1272        Ok(())
1273    }
1274
1275    /// Record a shell command from a human shell session (passive recording, no
1276    /// AI-agent hook). Logged as `agent = "shell"`, decision Allow — it is never
1277    /// blocked (the recorder is an audit/undo trail, not a gate). We **classify**
1278    /// it with the Tier-1 rules so the event carries the real class (a destructive
1279    /// command a DBA ran is flagged in the timeline and `kintsugi report`), and we
1280    /// **snapshot destructive commands** so `kintsugi undo` can recover a human's
1281    /// mistake. The model never runs on this path.
1282    ///
1283    /// The hard floor stays honest: this is an audit record of the past, not a
1284    /// gate. The "nothing un-warned" guarantee never applied to commands a human
1285    /// ran outside Kintsugi; the "tamper-evident record of everything" one does,
1286    /// which is exactly what this preserves.
1287    pub fn record_shell(&self, cmd: &ProposedCommand) -> Result<()> {
1288        // Provenance: the recorder is for human shell sessions, so force the agent
1289        // label to "shell" regardless of what the caller sent. A local peer that
1290        // can reach the socket therefore cannot forge a record attributed to an
1291        // AI agent ("claude-code") or the watcher ("fs-watch"); the worst it can
1292        // do is inject a self-reported *shell* event, which the Audit view treats
1293        // accordingly. (The socket is already owner-only; this is defense in depth.)
1294        let mut cmd = cmd.clone();
1295        cmd.agent = "shell".to_string();
1296        let m = kintsugi_core::classify(&cmd);
1297        // Allow, not the rule's gate decision: the command already executed, so
1298        // recording a Hold/Deny here would be a lie about what happened. The
1299        // class still rides along (verdict.class) so the timeline flags danger.
1300        let mut verdict = Verdict::rules(m.class, Decision::Allow, format!("recorded:{}", m.rule));
1301        // Score risky commands with the model so the Recorder rows and the
1302        // details drawer can show a plain-English summary alongside the raw
1303        // command. The decision stays Allow — this is just metadata on a row
1304        // that's already an audit record of the past.
1305        //
1306        // The model call is one synchronous inference on the single-threaded
1307        // serve loop, so it's spent against a token-bucket budget: under a flood
1308        // of risky records the budget empties and we record the row *without* the
1309        // summary rather than let the recorder serialize unbounded inference and
1310        // starve real hold/approve traffic. The class still rides in verdict.class
1311        // either way, so the timeline never loses the danger signal — only the
1312        // cosmetic prose. (Safe commands never score, so they never spend.)
1313        let may_score = !matches!(m.class, kintsugi_core::Class::Safe)
1314            && self
1315                .score_budget
1316                .borrow_mut()
1317                .try_spend(std::time::Instant::now());
1318        if may_score {
1319            let out = self.scorer.score(&cmd, m.class, &m.rule);
1320            verdict.summary = Some(out.summary);
1321            verdict.tier = 2;
1322            if m.class == kintsugi_core::Class::Ambiguous {
1323                verdict.risk = Some(out.risk);
1324            }
1325        } else if m.class != kintsugi_core::Class::Safe {
1326            // Budget shed: keep the danger tier on the row even without prose.
1327            verdict.tier = 2;
1328        }
1329        // Recoverer: snapshot the paths a *destructive* human command will touch,
1330        // so `kintsugi undo` can roll back a person's *filesystem* mistake (rm -rf,
1331        // a clobbering overwrite) the same way it rolls back an agent's. The shell
1332        // preexec hook fires before the command runs, so this is a just-in-time
1333        // capture; `maybe_snapshot` no-ops for Safe commands and reflinks where it
1334        // can, so the common case stays cheap. Best-effort: if the snapshot loses
1335        // the race (or the fs can't reflink), the filesystem-watcher backstop still
1336        // records the change. This is a filesystem recoverer — an in-database
1337        // DROP/TRUNCATE is not a file, so it's flagged/recorded but recovery there
1338        // is your DB's PITR/backups. The honest guarantee is "recoverable", not
1339        // transactional.
1340        let (snapshot_id, _) = self.maybe_snapshot(&cmd, &verdict);
1341        self.log.log_event(&cmd, &verdict, snapshot_id.as_deref())?;
1342        Ok(())
1343    }
1344
1345    /// Dispatch an IPC request to its handler.
1346    pub fn handle_request(&self, req: ipc::Request) -> ipc::Response {
1347        match req {
1348            ipc::Request::Propose(cmd) => ipc::Response::Verdict(self.handle(cmd)),
1349            ipc::Request::Resolve(resolution) => match self.resolve(&resolution) {
1350                Ok(()) => ipc::Response::Ack,
1351                Err(e) => ipc::Response::Error {
1352                    message: e.to_string(),
1353                },
1354            },
1355            ipc::Request::Observe(obs) => match self.observe(&obs) {
1356                Ok(()) => ipc::Response::Ack,
1357                Err(e) => ipc::Response::Error {
1358                    message: e.to_string(),
1359                },
1360            },
1361            // Observation only labels — it never blocks and can't fail the caller:
1362            // apply_taint persists best-effort and redacts the source_id (segment G).
1363            ipc::Request::Ingest(observed) => {
1364                self.apply_taint(&observed.into_taint_event());
1365                ipc::Response::Ack
1366            }
1367            // Observation only: a write labels the path for future readers. It
1368            // never blocks, never enqueues, and never touches a command verdict.
1369            ipc::Request::WriteObserved { session, path, cwd } => {
1370                self.apply_write(&session, &path, &cwd);
1371                ipc::Response::Ack
1372            }
1373            // The reader half: a read of a labelled path taints the reader.
1374            ipc::Request::ReadObserved { session, path, cwd } => {
1375                self.apply_read(&session, &path, &cwd);
1376                ipc::Response::Ack
1377            }
1378            ipc::Request::Provenance(cmd) => ipc::Response::Provenance {
1379                tainted: self.is_session_tainted(cmd.session.as_deref()),
1380                trail: self.provenance_trail(&cmd),
1381            },
1382            ipc::Request::Record(cmd) => match self.record_shell(&cmd) {
1383                Ok(()) => ipc::Response::Ack,
1384                Err(e) => ipc::Response::Error {
1385                    message: e.to_string(),
1386                },
1387            },
1388            ipc::Request::ListPending => match self.log.list_pending() {
1389                Ok(items) => ipc::Response::PendingList { items },
1390                Err(e) => ipc::Response::Error {
1391                    message: e.to_string(),
1392                },
1393            },
1394            ipc::Request::PendingStatus { id } => match self.log.pending_status(&id) {
1395                Ok(status) => ipc::Response::Pending {
1396                    status: status.unwrap_or_else(|| "gone".to_string()),
1397                },
1398                Err(e) => ipc::Response::Error {
1399                    message: e.to_string(),
1400                },
1401            },
1402            // Proof-of-human approval (Phase 7): authenticated on a locked
1403            // daemon, audited + throttled when bare. `Deny`/`PrunePending`
1404            // stay bare by design (nuisance, not threat / queue-only).
1405            ipc::Request::Approve { id, nonce, proof } => {
1406                self.approve_op(&id, nonce.as_deref(), proof.as_deref())
1407            }
1408            ipc::Request::Deny { id } => self.resolve_pending_response(&id, Decision::Deny),
1409            ipc::Request::PrunePending => match self.log.prune_pending() {
1410                Ok(n) => ipc::Response::Pending {
1411                    status: n.to_string(),
1412                },
1413                Err(e) => ipc::Response::Error {
1414                    message: e.to_string(),
1415                },
1416            },
1417            ipc::Request::Status => ipc::Response::Status {
1418                scorer: self.scorer_name().to_string(),
1419            },
1420            ipc::Request::AuthBegin { op } => self.auth_begin(&op),
1421            ipc::Request::Shutdown { op, nonce, proof } => {
1422                self.shutdown_op(&op, nonce.as_deref(), proof.as_deref())
1423            }
1424        }
1425    }
1426
1427    fn resolve_pending_response(&self, id: &str, decision: Decision) -> ipc::Response {
1428        match self.resolve_pending(id, decision) {
1429            Ok(true) => ipc::Response::Ack,
1430            Ok(false) => ipc::Response::Error {
1431                message: format!("no pending command with id {id}"),
1432            },
1433            Err(e) => ipc::Response::Error {
1434                message: e.to_string(),
1435            },
1436        }
1437    }
1438
1439    /// Borrow the underlying event log (read-only queries).
1440    pub fn log(&self) -> &EventLog {
1441        &self.log
1442    }
1443}
1444
1445/// Load and merge the effective policy for a command's working directory:
1446/// global defaults (config dir) overridden by the repo's `.kintsugi.toml`.
1447pub fn load_policy(cwd: &std::path::Path) -> kintsugi_core::Policy {
1448    let global = read_policy_file(&global_policy_path()).unwrap_or_default();
1449    let repo = find_repo_policy(cwd)
1450        .and_then(|p| read_policy_file(&p))
1451        .unwrap_or_default();
1452    kintsugi_core::Policy::merge(global, repo)
1453}
1454
1455/// Path to the global policy file. Override with `KINTSUGI_CONFIG` (used in tests).
1456fn global_policy_path() -> PathBuf {
1457    if let Ok(p) = std::env::var("KINTSUGI_CONFIG") {
1458        return PathBuf::from(p);
1459    }
1460    if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
1461        return dirs.config_dir().join("config.toml");
1462    }
1463    std::env::temp_dir().join("kintsugi-config.toml")
1464}
1465
1466/// Find the nearest `.kintsugi.toml` from `cwd` upward.
1467fn find_repo_policy(cwd: &std::path::Path) -> Option<PathBuf> {
1468    let mut dir = Some(cwd);
1469    while let Some(d) = dir {
1470        let candidate = d.join(".kintsugi.toml");
1471        if candidate.is_file() {
1472            return Some(candidate);
1473        }
1474        dir = d.parent();
1475    }
1476    None
1477}
1478
1479fn read_policy_file(path: &std::path::Path) -> Option<kintsugi_core::Policy> {
1480    let text = std::fs::read_to_string(path).ok()?;
1481    match kintsugi_core::Policy::parse(&text) {
1482        Ok(p) => Some(p),
1483        Err(e) => {
1484            eprintln!(
1485                "kintsugi-daemon: ignoring invalid policy {}: {e}",
1486                path.display()
1487            );
1488            None
1489        }
1490    }
1491}
1492
1493/// Identify the "repo" a command runs in: the nearest ancestor containing a
1494/// `.git` directory, else the working directory itself.
1495pub fn repo_key(cwd: &std::path::Path) -> String {
1496    let mut dir = Some(cwd);
1497    while let Some(d) = dir {
1498        if d.join(".git").exists() {
1499            return d.to_string_lossy().to_string();
1500        }
1501        dir = d.parent();
1502    }
1503    cwd.to_string_lossy().to_string()
1504}
1505
1506/// Run the daemon: open the default log, bind the socket, serve forever.
1507pub fn run() -> Result<()> {
1508    let daemon = Daemon::open_default()?;
1509    let server = Server::bind()?;
1510    // Record our PID so `kintsugi stop` can find and stop us (any launch path).
1511    let _ = std::fs::write(pid_file_path(), std::process::id().to_string());
1512    eprintln!(
1513        "kintsugi-daemon {} listening on {}",
1514        VERSION,
1515        Server::endpoint().display()
1516    );
1517    server.serve_until(
1518        |req| daemon.handle_request(req),
1519        || daemon.should_shutdown(),
1520    )?;
1521    // An authenticated shutdown landed: clean up the PID file and exit.
1522    let _ = std::fs::remove_file(pid_file_path());
1523    eprintln!("kintsugi-daemon: authenticated shutdown — exiting.");
1524    Ok(())
1525}
1526
1527/// Path to the daemon's PID file (next to the event log).
1528pub fn pid_file_path() -> PathBuf {
1529    default_db_path().with_file_name("kintsugi.pid")
1530}
1531
1532#[cfg(test)]
1533mod queue_entry_tests {
1534    use super::needs_queue_entry;
1535    use kintsugi_core::{Class, ProposedCommand};
1536
1537    fn cmd(agent: &str) -> ProposedCommand {
1538        ProposedCommand::new(
1539            agent,
1540            std::path::Path::new("/tmp"),
1541            vec!["rm".into(), "x".into()],
1542            "rm x",
1543        )
1544    }
1545
1546    #[test]
1547    fn catastrophic_always_enqueues() {
1548        for a in [
1549            "claude-code",
1550            "qwen",
1551            "gemini",
1552            "mcp",
1553            "opencode",
1554            "anything",
1555        ] {
1556            assert!(
1557                needs_queue_entry(&cmd(a), Class::Catastrophic),
1558                "catastrophic must queue for {a}"
1559            );
1560        }
1561    }
1562
1563    #[test]
1564    fn ambiguous_skips_only_native_ask_agents() {
1565        // Native ask → resolved by the agent's own prompt, so NO queue entry.
1566        for a in ["claude-code", "qwen", "copilot", "cursor", "codex"] {
1567            assert!(
1568                !needs_queue_entry(&cmd(a), Class::Ambiguous),
1569                "{a} has native ask → no queue orphan"
1570            );
1571        }
1572        // No native ask → the human resolves via the queue, so it MUST enqueue.
1573        for a in ["gemini", "antigravity", "opencode", "mcp", "future-agent"] {
1574            assert!(
1575                needs_queue_entry(&cmd(a), Class::Ambiguous),
1576                "{a} has no prompt → must queue"
1577            );
1578        }
1579    }
1580}
1581
1582#[cfg(test)]
1583mod score_budget_tests {
1584    use super::ScoreBudget;
1585    use std::time::{Duration, Instant};
1586
1587    #[test]
1588    fn burst_is_bounded_then_refills_at_the_steady_rate() {
1589        let t0 = Instant::now();
1590        // Capacity 8, refill 4/sec.
1591        let mut b = ScoreBudget::new(8.0, 4.0, t0);
1592
1593        // A flood at t0 spends the whole burst and no more — the 9th is shed, so
1594        // a recorder flood can never serialize unbounded inference on the loop.
1595        for i in 0..8 {
1596            assert!(b.try_spend(t0), "burst token {i} should be granted");
1597        }
1598        assert!(!b.try_spend(t0), "9th in the same instant must be shed");
1599
1600        // After 1s, 4 tokens have refilled (the steady ceiling) — not the full 8.
1601        let t1 = t0 + Duration::from_secs(1);
1602        for i in 0..4 {
1603            assert!(b.try_spend(t1), "refilled token {i} should be granted");
1604        }
1605        assert!(!b.try_spend(t1), "refill is rate-capped, not a full reset");
1606    }
1607
1608    #[test]
1609    fn refill_never_exceeds_capacity() {
1610        let t0 = Instant::now();
1611        let mut b = ScoreBudget::new(8.0, 4.0, t0);
1612        for _ in 0..8 {
1613            assert!(b.try_spend(t0));
1614        }
1615        // Idle far longer than it takes to refill — tokens cap at `capacity`, so a
1616        // long-quiet session banks a burst of 8, never an unbounded backlog.
1617        let later = t0 + Duration::from_secs(3600);
1618        for i in 0..8 {
1619            assert!(b.try_spend(later), "banked token {i} after a long idle");
1620        }
1621        assert!(
1622            !b.try_spend(later),
1623            "cap holds: no more than `capacity` banked"
1624        );
1625    }
1626}