#![forbid(unsafe_code)]
pub mod ipc;
pub mod watch;
use std::path::PathBuf;
use std::cell::{Cell, RefCell};
use anyhow::{Context, Result};
use directories::ProjectDirs;
use kintsugi_core::admin::{self, VaultState};
use kintsugi_core::{Decision, EventLog, Mode, ProposedCommand, TaintEvent, TaintState, Verdict};
use kintsugi_model::DependencyHint;
pub use ipc::{Client, Observation, Resolution, Server};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const KILL_SWITCH_FILE: &str = "panic.flag";
pub fn kill_switch_path() -> PathBuf {
default_db_path()
.parent()
.map(|p| p.join(KILL_SWITCH_FILE))
.unwrap_or_else(|| std::env::temp_dir().join(KILL_SWITCH_FILE))
}
pub const FAIL_CLOSED_FILE: &str = "fail-closed.flag";
pub fn fail_closed_marker_path() -> PathBuf {
default_db_path().with_file_name(FAIL_CLOSED_FILE)
}
pub fn is_fail_closed_marked() -> bool {
fail_closed_marker_path().exists()
}
pub fn set_fail_closed_marker(on: bool) -> std::io::Result<()> {
let path = fail_closed_marker_path();
if on {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, b"fail-closed\n")?;
} else if path.exists() {
std::fs::remove_file(&path)?;
}
Ok(())
}
pub fn default_db_path() -> PathBuf {
if let Ok(p) = std::env::var("KINTSUGI_DB") {
return PathBuf::from(p);
}
if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
return dirs.data_dir().join("events.db");
}
std::env::temp_dir().join("kintsugi-events.db")
}
pub struct Daemon {
log: EventLog,
mode: Mode,
scorer: Box<dyn kintsugi_model::Scorer>,
snapshot_dir: PathBuf,
kill_path: PathBuf,
vault_path: PathBuf,
vault_expected: bool,
pending: RefCell<Option<(Vec<u8>, String)>>,
shutdown: Cell<bool>,
throttle: RefCell<AuthThrottle>,
taint: RefCell<TaintState>,
denial_streak: RefCell<std::collections::HashMap<String, u32>>,
score_budget: RefCell<ScoreBudget>,
}
#[derive(Default)]
struct AuthThrottle {
failures: u32,
locked_until: Option<std::time::Instant>,
}
impl AuthThrottle {
const FREE_ATTEMPTS: u32 = 5;
fn lockout_remaining(&self) -> Option<std::time::Duration> {
self.locked_until
.and_then(|t| t.checked_duration_since(std::time::Instant::now()))
}
fn record_failure(&mut self) {
self.failures = self.failures.saturating_add(1);
if self.failures >= Self::FREE_ATTEMPTS {
let over = (self.failures - Self::FREE_ATTEMPTS).min(7);
self.locked_until = Some(
std::time::Instant::now()
+ std::time::Duration::from_secs((30u64 << over).min(3600)),
);
}
}
fn reset(&mut self) {
self.failures = 0;
self.locked_until = None;
}
}
struct ScoreBudget {
tokens: f64,
capacity: f64,
refill_per_sec: f64,
last: std::time::Instant,
}
impl ScoreBudget {
fn new(capacity: f64, refill_per_sec: f64, now: std::time::Instant) -> Self {
Self {
tokens: capacity,
capacity,
refill_per_sec,
last: now,
}
}
fn try_spend(&mut self, now: std::time::Instant) -> bool {
let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
self.last = now;
self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
if self.tokens >= 1.0 {
self.tokens -= 1.0;
true
} else {
false
}
}
}
const AGENTS_WITH_NATIVE_ASK: &[&str] = &["claude-code", "qwen", "copilot", "cursor", "codex"];
fn needs_queue_entry(cmd: &ProposedCommand, class: kintsugi_core::Class) -> bool {
if class == kintsugi_core::Class::Catastrophic {
return true;
}
!AGENTS_WITH_NATIVE_ASK.contains(&cmd.agent.as_str())
}
const SHUTDOWN_OP: &str = "shutdown";
fn sanitize_op(op: &str) -> String {
const MAX: usize = 64;
let mut out = String::with_capacity(op.len().min(MAX));
for ch in op.chars().take(MAX) {
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.') {
out.push(ch);
} else {
out.push('?');
}
}
if op.chars().count() > MAX {
out.push('…');
}
out
}
impl Daemon {
pub fn open(db_path: impl Into<PathBuf>) -> Result<Self> {
let db_path = db_path.into();
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("create data dir {}", parent.display()))?;
}
let data_dir = db_path
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.to_path_buf();
#[cfg(unix)]
ipc::set_mode(&data_dir, 0o700);
let snapshot_dir = data_dir.join("snapshots");
let kill_path = data_dir.join(KILL_SWITCH_FILE);
let log = EventLog::open(&db_path)
.with_context(|| format!("open event log at {}", db_path.display()))?;
#[cfg(unix)]
for suffix in ["", "-wal", "-shm"] {
let p = if suffix.is_empty() {
db_path.clone()
} else {
PathBuf::from(format!("{}{suffix}", db_path.display()))
};
if p.exists() {
ipc::set_mode(&p, 0o600);
}
}
let vault_path = admin::default_vault_path();
let taint = match log.load_taint_events() {
Ok(events) => TaintState::from_events(events.iter()),
Err(e) => {
eprintln!("kintsugi-daemon: failed to replay taint events: {e}");
TaintState::new()
}
};
let vault_expected = log.has_provision_marker().unwrap_or(false);
Ok(Self {
log,
mode: Mode::default(),
scorer: kintsugi_model::default_scorer(),
snapshot_dir,
kill_path,
vault_path,
vault_expected,
pending: RefCell::new(None),
shutdown: Cell::new(false),
throttle: RefCell::new(AuthThrottle::default()),
taint: RefCell::new(taint),
denial_streak: RefCell::new(std::collections::HashMap::new()),
score_budget: RefCell::new(ScoreBudget::new(8.0, 4.0, std::time::Instant::now())),
})
}
pub fn apply_taint(&self, event: &TaintEvent) {
let event = event.with_redacted_source_id();
if let Err(e) = self.log.record_taint_event(&event) {
eprintln!("kintsugi-daemon: failed to persist taint event: {e}");
}
self.taint.borrow_mut().apply(&event);
}
pub fn apply_write(&self, session: &str, path: &str, cwd: &std::path::Path) {
if session.is_empty() || path.trim().is_empty() {
return;
}
if !load_policy(cwd).provenance_enabled() {
return;
}
if !self.is_session_tainted(Some(session)) {
return;
}
self.apply_taint(&TaintEvent::WriteFile {
session: session.to_string(),
path: std::path::PathBuf::from(path),
});
}
pub fn apply_read(&self, session: &str, path: &str, cwd: &std::path::Path) {
if session.is_empty() || path.trim().is_empty() {
return;
}
if !load_policy(cwd).provenance_enabled() {
return;
}
if self.is_session_tainted(Some(session)) {
return; }
if !self
.taint
.borrow()
.is_path_tainted(std::path::Path::new(path))
{
return; }
self.apply_taint(&TaintEvent::ReadFile {
session: session.to_string(),
path: std::path::PathBuf::from(path),
});
}
pub fn is_session_tainted(&self, session: Option<&str>) -> bool {
self.taint.borrow().is_session_tainted(session)
}
pub fn session_provenance(&self, session: &str) -> Option<kintsugi_core::TaintSet> {
self.taint.borrow().session_taint(session).cloned()
}
pub fn provenance_trail(&self, cmd: &ProposedCommand) -> Vec<kintsugi_core::ProvStep> {
use kintsugi_core::ProvStep;
let session = cmd.session.as_deref();
let Some(set) = session.and_then(|s| self.session_provenance(s)) else {
return Vec::new();
};
if !set.is_tainted() {
return Vec::new();
}
let mut trail = kintsugi_core::untrusted_trail(&set);
let sensitive = kintsugi_core::is_sensitive_read(cmd);
let egress = kintsugi_core::is_egress_sink(cmd);
if let Some(path) = &sensitive {
trail.push(ProvStep::SensitiveRead { path: path.clone() });
}
if let Some(target) = &egress {
trail.push(ProvStep::EgressSink {
target: target.clone(),
});
}
let outcome = kintsugi_core::evaluate_trifecta(true, sensitive.is_some(), egress.is_some());
if let Some(rule) = outcome.rule() {
trail.push(ProvStep::RuleFired {
rule: rule.to_string(),
});
}
trail
}
fn trifecta_floor(
&self,
cmd: &ProposedCommand,
policy: &kintsugi_core::Policy,
base_class: kintsugi_core::Class,
base_rule: String,
) -> (kintsugi_core::Class, String) {
use kintsugi_core::Trifecta;
if !policy.provenance_enabled() || !self.is_session_tainted(cmd.session.as_deref()) {
return (base_class, base_rule);
}
let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
let egress = kintsugi_core::is_egress_sink(cmd).is_some();
let outcome = kintsugi_core::evaluate_trifecta(true, sensitive, egress);
let floor = match outcome {
Trifecta::Block => kintsugi_core::Class::Catastrophic,
Trifecta::Hold | Trifecta::Annotate => kintsugi_core::Class::Ambiguous,
Trifecta::None => return (base_class, base_rule),
};
let class = base_class.max(floor);
if class.severity() > base_class.severity() {
let rule = outcome.rule().unwrap_or("TRIFECTA");
(class, format!("{rule}:provenance ({base_rule})"))
} else {
(class, base_rule)
}
}
fn dependency_hint(
&self,
cmd: &ProposedCommand,
policy: &kintsugi_core::Policy,
) -> DependencyHint {
use kintsugi_core::Trifecta;
if !policy.provenance_enabled() {
return DependencyHint::Unknown;
}
let Some(trail) = cmd
.session
.as_deref()
.and_then(|s| self.session_provenance(s))
else {
return DependencyHint::Unknown;
};
if !trail.is_tainted() {
return DependencyHint::Unknown;
}
let sensitive = kintsugi_core::is_sensitive_read(cmd).is_some();
let egress = kintsugi_core::is_egress_sink(cmd).is_some();
match kintsugi_core::evaluate_trifecta(true, sensitive, egress) {
Trifecta::Hold | Trifecta::Annotate => kintsugi_model::dependency_hint(cmd, &trail),
Trifecta::Block | Trifecta::None => DependencyHint::Unknown,
}
}
pub fn should_shutdown(&self) -> bool {
self.shutdown.get()
}
fn current_vault(&self) -> VaultState {
match admin::load_vault(&self.vault_path) {
VaultState::Unprovisioned if self.vault_expected => VaultState::Degraded(
"the admin vault was provisioned on this machine but its file is missing"
.to_string(),
),
other => other,
}
}
fn auth_begin(&self, op: &str) -> ipc::Response {
match self.current_vault() {
VaultState::Degraded(_) => ipc::Response::Error {
message: "admin vault is degraded; refusing privileged operations".into(),
},
VaultState::Locked(v) => {
let nonce = match admin::random_auth_nonce() {
Ok(n) => n,
Err(_) => {
return ipc::Response::Error {
message: "could not generate a challenge".into(),
}
}
};
let (salt, params) = v.auth_challenge();
*self.pending.borrow_mut() = Some((nonce.clone(), op.to_string()));
ipc::Response::Challenge {
locked: true,
nonce: hex::encode(&nonce),
salt,
params,
}
}
VaultState::Unprovisioned => ipc::Response::Challenge {
locked: false,
nonce: String::new(),
salt: String::new(),
params: kintsugi_core::admin::KdfParams::production(),
},
}
}
fn shutdown_op(
&self,
op: &str,
nonce_hex: Option<&str>,
proof_hex: Option<&str>,
) -> ipc::Response {
if op != SHUTDOWN_OP {
self.record_admin(op, false, "op not served by shutdown");
return ipc::Response::Error {
message: format!("shutdown requires a `{SHUTDOWN_OP}` challenge"),
};
}
let vault = match self.current_vault() {
VaultState::Degraded(_) => {
self.record_admin(op, false, "vault degraded");
return ipc::Response::Error {
message: "admin vault is degraded; refusing to stop".into(),
};
}
VaultState::Unprovisioned => {
self.record_admin(op, true, "unprovisioned");
self.shutdown.set(true);
return ipc::Response::Ack;
}
VaultState::Locked(v) => v,
};
let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
if proof_offered {
if let Some(rem) = self.throttle.borrow().lockout_remaining() {
self.record_admin(op, false, "locked out");
return ipc::Response::Error {
message: format!(
"too many failed attempts; locked out for {}s",
rem.as_secs() + 1
),
};
}
}
let pending = self.pending.borrow_mut().take();
let ok = match (pending, nonce_hex, proof_hex) {
(Some((issued_nonce, issued_op)), Some(nonce_hex), Some(proof_hex)) => {
match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
(Ok(nonce), Ok(proof)) => {
issued_op == op
&& issued_nonce == nonce
&& vault.verify_proof(&nonce, op.as_bytes(), &proof)
}
_ => false,
}
}
_ => false,
};
if ok {
self.throttle.borrow_mut().reset();
self.record_admin(op, true, "authenticated");
self.shutdown.set(true);
ipc::Response::Ack
} else {
if proof_offered {
self.throttle.borrow_mut().record_failure();
}
if !vault.supports_proof() {
self.record_admin(op, false, "vault missing proof key");
return ipc::Response::Error {
message:
"admin vault has no auth key — re-run `kintsugi admin provision --force` \
(the daemon picks it up immediately, no restart needed)"
.into(),
};
}
self.record_admin(op, false, "authentication failed");
ipc::Response::Error {
message: "authentication failed".into(),
}
}
}
fn approve_op(
&self,
id: &str,
nonce_hex: Option<&str>,
proof_hex: Option<&str>,
) -> ipc::Response {
let op = format!("approve:{id}");
let cwd = self
.log
.pending_command(id)
.ok()
.flatten()
.map(|c| c.cwd)
.unwrap_or_else(|| {
std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
});
let require_proof = load_policy(&cwd).require_approval_proof();
let vault = match self.current_vault() {
VaultState::Degraded(_) => {
self.record_admin(&op, false, "vault degraded");
return ipc::Response::Error {
message: "admin vault is degraded; refusing privileged operations".into(),
};
}
VaultState::Unprovisioned => {
self.record_admin(&op, true, "unprovisioned");
return self.resolve_pending_response(id, Decision::Allow);
}
VaultState::Locked(v) => v,
};
let proof_offered = nonce_hex.is_some() || proof_hex.is_some();
if proof_offered {
if let Some(rem) = self.throttle.borrow().lockout_remaining() {
self.record_admin(&op, false, "locked out");
return ipc::Response::Error {
message: format!(
"too many failed attempts; locked out for {}s",
rem.as_secs() + 1
),
};
}
}
let nonce_hex = nonce_hex.filter(|s| !s.trim().is_empty());
let proof_hex = proof_hex.filter(|s| !s.trim().is_empty());
match (nonce_hex, proof_hex) {
(None, None) if !require_proof => {
self.record_admin(&op, true, "policy-opt-out");
self.resolve_pending_response(id, Decision::Allow)
}
(None, None) => {
self.record_admin(&op, false, "self-approval blocked");
ipc::Response::Error {
message: format!(
"approval requires proof — run `kintsugi approve {id}` (or \
`kintsugi run {id}`) and enter the admin password; see \
docs/policy.md to allow bare approval"
),
}
}
(Some(nonce_hex), Some(proof_hex)) => {
let pending = self.pending.borrow_mut().take();
let ok = match pending {
Some((issued_nonce, issued_op)) => {
match (hex::decode(nonce_hex), hex::decode(proof_hex)) {
(Ok(nonce), Ok(proof)) => {
issued_op == op
&& issued_nonce == nonce
&& vault.verify_proof(&nonce, op.as_bytes(), &proof)
}
_ => false,
}
}
None => false,
};
if ok {
self.throttle.borrow_mut().reset();
self.record_admin(&op, true, "authenticated");
self.resolve_pending_response(id, Decision::Allow)
} else {
self.throttle.borrow_mut().record_failure();
if !vault.supports_proof() {
self.record_admin(&op, false, "vault missing proof key");
return ipc::Response::Error {
message: "admin vault has no auth key — re-run `kintsugi admin \
provision --force` (the daemon picks it up immediately, no \
restart needed)"
.into(),
};
}
self.record_admin(&op, false, "authentication failed");
ipc::Response::Error {
message: "authentication failed".into(),
}
}
}
_ => {
self.throttle.borrow_mut().record_failure();
self.record_admin(&op, false, "authentication failed");
ipc::Response::Error {
message: "authentication failed".into(),
}
}
}
}
fn record_admin(&self, op: &str, ok: bool, reason: &str) {
let op = sanitize_op(op);
let op = op.as_str();
let raw = format!(
"admin {op} — {}",
if ok { "authenticated" } else { "denied" }
);
let cmd = ProposedCommand::new(
"admin",
std::path::Path::new("."),
vec!["admin".to_string(), op.to_string()],
raw,
);
let decision = if ok { Decision::Allow } else { Decision::Deny };
let verdict = Verdict::rules(
kintsugi_core::Class::Safe,
decision,
format!("admin:{op}:{reason}"),
);
let _ = self.log.log_event(&cmd, &verdict, None);
}
pub fn kill_switch_engaged(&self) -> bool {
self.kill_path.exists()
}
pub fn snapshot_dir(&self) -> &std::path::Path {
&self.snapshot_dir
}
pub fn with_scorer(mut self, scorer: Box<dyn kintsugi_model::Scorer>) -> Self {
self.scorer = scorer;
self
}
pub fn scorer_name(&self) -> &str {
self.scorer.name()
}
pub fn open_default() -> Result<Self> {
Self::open(default_db_path())
}
pub fn with_mode(mut self, mode: Mode) -> Self {
self.mode = mode;
self
}
pub fn mode(&self) -> Mode {
self.mode
}
pub fn decide(&self, cmd: &ProposedCommand) -> Verdict {
if self.kill_switch_engaged() {
let m = kintsugi_core::classify(cmd);
return Verdict::rules(m.class, Decision::Deny, "kill-switch: all actions halted");
}
let policy = load_policy(&cmd.cwd);
let mode = policy.mode.unwrap_or(self.mode);
let m = kintsugi_core::classify(cmd);
let (class, rule) = self.trifecta_floor(cmd, &policy, m.class, m.rule);
let mut verdict = Verdict::rules(class, kintsugi_core::decide(class, mode), &rule);
match class {
kintsugi_core::Class::Ambiguous => {
let hint = self.dependency_hint(cmd, &policy);
let out = self.scorer.score_with_hint(cmd, class, &rule, hint);
verdict.summary = Some(out.summary);
verdict.risk = Some(out.risk);
verdict.tier = 2;
if mode == Mode::Unattended {
verdict.reason = format!(
"model:risk={} ({}) — unattended holds ambiguous for review",
out.risk, rule
);
} else if hint == DependencyHint::LikelyDependent
&& verdict.decision == Decision::Hold
{
verdict.decision = Decision::Deny;
verdict.reason = format!("advisory:dependent ({})", verdict.reason);
}
}
kintsugi_core::Class::Catastrophic => {
let out = self.scorer.score(cmd, class, &rule);
verdict.summary = Some(out.summary);
verdict.tier = 2;
}
kintsugi_core::Class::Safe => {}
}
let action = policy.action_for(&cmd.raw);
verdict = kintsugi_core::adjust_for_policy(verdict, action, mode);
let repo = repo_key(&cmd.cwd);
let hash = kintsugi_core::command_hash(&cmd.raw);
match self.log.memory_lookup(&repo, &hash) {
Ok(Some(Decision::Allow)) if verdict.class != kintsugi_core::Class::Catastrophic => {
verdict.decision = Decision::Allow;
verdict.reason = format!("memory:allow ({})", verdict.reason);
}
Ok(Some(Decision::Deny)) => {
verdict.decision = Decision::Deny;
verdict.reason = format!("memory:deny ({})", verdict.reason);
}
_ => {}
}
verdict
}
pub fn handle(&self, cmd: ProposedCommand) -> Verdict {
let mut verdict = self.decide(&cmd);
let (snapshot_id, snapshot_failed) = self.maybe_snapshot(&cmd, &verdict);
if verdict.decision == Decision::Allow && verdict.class != kintsugi_core::Class::Safe {
let note = if snapshot_failed {
Some("snapshot failed — NOT reversible by undo")
} else if !kintsugi_core::snapshot::is_fully_reversible(&cmd) {
Some("target can't be fully snapshotted — undo may not restore everything")
} else {
None
};
if let Some(n) = note {
verdict.reason = format!("{} [⚠ {n}]", verdict.reason);
}
}
if let Err(e) = self.log.log_event(&cmd, &verdict, snapshot_id.as_deref()) {
eprintln!("kintsugi-daemon: failed to record event: {e}");
if verdict.decision == Decision::Allow {
verdict.decision = Decision::Deny;
verdict.reason = format!(
"audit-log write failed; denied fail-closed ({})",
verdict.reason
);
}
}
if verdict.decision == Decision::Hold && needs_queue_entry(&cmd, verdict.class) {
if let Err(e) = self
.log
.enqueue_pending(&cmd, verdict.class, &verdict.reason)
{
eprintln!("kintsugi-daemon: failed to enqueue pending: {e}");
}
}
self.negotiate(cmd.session.as_deref(), verdict)
}
fn negotiate(&self, session: Option<&str>, mut verdict: Verdict) -> Verdict {
use kintsugi_core::Class;
let blocked = verdict.decision == Decision::Deny
|| (verdict.decision == Decision::Hold && verdict.class == Class::Catastrophic);
if !blocked {
if verdict.decision == Decision::Allow {
if let Some(s) = session {
self.denial_streak.borrow_mut().remove(s);
}
}
return verdict;
}
let tripped = match session {
Some(s) => {
let mut streaks = self.denial_streak.borrow_mut();
let count = streaks.entry(s.to_string()).or_insert(0);
*count += 1;
*count >= kintsugi_core::negotiate::CONSECUTIVE_DENY_LIMIT
}
None => false,
};
verdict.reason = if tripped {
kintsugi_core::negotiate::circuit_breaker_reason(&verdict.reason)
} else {
kintsugi_core::negotiate::model_deny_reason(&verdict.reason)
};
verdict
}
pub fn resolve_pending(&self, id: &str, decision: Decision) -> Result<bool> {
if decision == Decision::Allow && self.kill_switch_engaged() {
anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before approving");
}
let status = if decision == Decision::Allow {
"approved"
} else {
"denied"
};
if !self.log.cas_pending_status(id, "pending", status)? {
return Ok(false);
}
let Some(cmd) = self.log.pending_command(id)? else {
return Ok(false);
};
self.resolve(&ipc::Resolution {
command: cmd,
decision,
remember: false,
})?;
Ok(true)
}
fn maybe_snapshot(&self, cmd: &ProposedCommand, verdict: &Verdict) -> (Option<String>, bool) {
if verdict.decision != Decision::Allow || verdict.class == kintsugi_core::Class::Safe {
return (None, false);
}
match kintsugi_core::capture_snapshot(&self.snapshot_dir, cmd) {
Ok(Some(manifest)) => {
if let Err(e) = self.log.record_snapshot(&manifest) {
eprintln!("kintsugi-daemon: failed to record snapshot: {e}");
return (None, true);
}
(Some(manifest.id), false)
}
Ok(None) => (None, false),
Err(e) => {
eprintln!("kintsugi-daemon: snapshot failed: {e}");
(None, true)
}
}
}
pub fn resolve(&self, resolution: &ipc::Resolution) -> Result<()> {
if resolution.decision == Decision::Allow && self.kill_switch_engaged() {
anyhow::bail!("kill-switch engaged; clear it with `kintsugi resume` before allowing");
}
let cmd = &resolution.command;
let m = kintsugi_core::classify(cmd);
let remember = resolution.remember
&& !(resolution.decision == Decision::Allow
&& m.class == kintsugi_core::Class::Catastrophic);
let reason = match resolution.decision {
Decision::Allow if remember => "human:always-allow",
Decision::Allow => "human:allow",
Decision::Deny if remember => "human:always-deny",
Decision::Deny => "human:deny",
Decision::Hold => "human:hold",
};
let verdict = Verdict::rules(m.class, resolution.decision, reason);
let (snapshot_id, _) = self.maybe_snapshot(cmd, &verdict);
self.log.log_event(cmd, &verdict, snapshot_id.as_deref())?;
if remember && resolution.decision != Decision::Hold {
let repo = repo_key(&cmd.cwd);
let hash = kintsugi_core::command_hash(&cmd.raw);
self.log.remember(&repo, &hash, resolution.decision)?;
}
if resolution.decision != Decision::Hold {
let status = if resolution.decision == Decision::Allow {
"approved"
} else {
"denied"
};
let _ = self.log.set_pending_status(&cmd.id.to_string(), status);
}
Ok(())
}
pub fn observe(&self, obs: &ipc::Observation) -> Result<()> {
let raw = format!("{} {}", obs.kind, obs.path);
let cwd = std::path::Path::new(&obs.path)
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default();
let cmd = ProposedCommand::new(
"fs-watch",
cwd,
vec![obs.kind.clone(), obs.path.clone()],
raw,
);
let verdict = Verdict::rules(
kintsugi_core::Class::Safe,
Decision::Allow,
format!("fs:{}", obs.kind),
);
self.log.log_event(&cmd, &verdict, None)?;
Ok(())
}
pub fn record_shell(&self, cmd: &ProposedCommand) -> Result<()> {
let mut cmd = cmd.clone();
cmd.agent = "shell".to_string();
let m = kintsugi_core::classify(&cmd);
let mut verdict = Verdict::rules(m.class, Decision::Allow, format!("recorded:{}", m.rule));
let may_score = !matches!(m.class, kintsugi_core::Class::Safe)
&& self
.score_budget
.borrow_mut()
.try_spend(std::time::Instant::now());
if may_score {
let out = self.scorer.score(&cmd, m.class, &m.rule);
verdict.summary = Some(out.summary);
verdict.tier = 2;
if m.class == kintsugi_core::Class::Ambiguous {
verdict.risk = Some(out.risk);
}
} else if m.class != kintsugi_core::Class::Safe {
verdict.tier = 2;
}
let (snapshot_id, _) = self.maybe_snapshot(&cmd, &verdict);
self.log.log_event(&cmd, &verdict, snapshot_id.as_deref())?;
Ok(())
}
pub fn handle_request(&self, req: ipc::Request) -> ipc::Response {
match req {
ipc::Request::Propose(cmd) => ipc::Response::Verdict(self.handle(cmd)),
ipc::Request::Resolve(resolution) => match self.resolve(&resolution) {
Ok(()) => ipc::Response::Ack,
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::Observe(obs) => match self.observe(&obs) {
Ok(()) => ipc::Response::Ack,
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::Ingest(observed) => {
self.apply_taint(&observed.into_taint_event());
ipc::Response::Ack
}
ipc::Request::WriteObserved { session, path, cwd } => {
self.apply_write(&session, &path, &cwd);
ipc::Response::Ack
}
ipc::Request::ReadObserved { session, path, cwd } => {
self.apply_read(&session, &path, &cwd);
ipc::Response::Ack
}
ipc::Request::Provenance(cmd) => ipc::Response::Provenance {
tainted: self.is_session_tainted(cmd.session.as_deref()),
trail: self.provenance_trail(&cmd),
},
ipc::Request::Record(cmd) => match self.record_shell(&cmd) {
Ok(()) => ipc::Response::Ack,
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::ListPending => match self.log.list_pending() {
Ok(items) => ipc::Response::PendingList { items },
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::PendingStatus { id } => match self.log.pending_status(&id) {
Ok(status) => ipc::Response::Pending {
status: status.unwrap_or_else(|| "gone".to_string()),
},
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::Approve { id, nonce, proof } => {
self.approve_op(&id, nonce.as_deref(), proof.as_deref())
}
ipc::Request::Deny { id } => self.resolve_pending_response(&id, Decision::Deny),
ipc::Request::PrunePending => match self.log.prune_pending() {
Ok(n) => ipc::Response::Pending {
status: n.to_string(),
},
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
},
ipc::Request::Status => ipc::Response::Status {
scorer: self.scorer_name().to_string(),
},
ipc::Request::AuthBegin { op } => self.auth_begin(&op),
ipc::Request::Shutdown { op, nonce, proof } => {
self.shutdown_op(&op, nonce.as_deref(), proof.as_deref())
}
}
}
fn resolve_pending_response(&self, id: &str, decision: Decision) -> ipc::Response {
match self.resolve_pending(id, decision) {
Ok(true) => ipc::Response::Ack,
Ok(false) => ipc::Response::Error {
message: format!("no pending command with id {id}"),
},
Err(e) => ipc::Response::Error {
message: e.to_string(),
},
}
}
pub fn log(&self) -> &EventLog {
&self.log
}
}
pub fn load_policy(cwd: &std::path::Path) -> kintsugi_core::Policy {
let global = read_policy_file(&global_policy_path()).unwrap_or_default();
let repo = find_repo_policy(cwd)
.and_then(|p| read_policy_file(&p))
.unwrap_or_default();
kintsugi_core::Policy::merge(global, repo)
}
fn global_policy_path() -> PathBuf {
if let Ok(p) = std::env::var("KINTSUGI_CONFIG") {
return PathBuf::from(p);
}
if let Some(dirs) = ProjectDirs::from("", "", "kintsugi") {
return dirs.config_dir().join("config.toml");
}
std::env::temp_dir().join("kintsugi-config.toml")
}
fn find_repo_policy(cwd: &std::path::Path) -> Option<PathBuf> {
let mut dir = Some(cwd);
while let Some(d) = dir {
let candidate = d.join(".kintsugi.toml");
if candidate.is_file() {
return Some(candidate);
}
dir = d.parent();
}
None
}
fn read_policy_file(path: &std::path::Path) -> Option<kintsugi_core::Policy> {
let text = std::fs::read_to_string(path).ok()?;
match kintsugi_core::Policy::parse(&text) {
Ok(p) => Some(p),
Err(e) => {
eprintln!(
"kintsugi-daemon: ignoring invalid policy {}: {e}",
path.display()
);
None
}
}
}
pub fn repo_key(cwd: &std::path::Path) -> String {
let mut dir = Some(cwd);
while let Some(d) = dir {
if d.join(".git").exists() {
return d.to_string_lossy().to_string();
}
dir = d.parent();
}
cwd.to_string_lossy().to_string()
}
pub fn run() -> Result<()> {
let daemon = Daemon::open_default()?;
let server = Server::bind()?;
let _ = std::fs::write(pid_file_path(), std::process::id().to_string());
eprintln!(
"kintsugi-daemon {} listening on {}",
VERSION,
Server::endpoint().display()
);
server.serve_until(
|req| daemon.handle_request(req),
|| daemon.should_shutdown(),
)?;
let _ = std::fs::remove_file(pid_file_path());
eprintln!("kintsugi-daemon: authenticated shutdown — exiting.");
Ok(())
}
pub fn pid_file_path() -> PathBuf {
default_db_path().with_file_name("kintsugi.pid")
}
#[cfg(test)]
mod queue_entry_tests {
use super::needs_queue_entry;
use kintsugi_core::{Class, ProposedCommand};
fn cmd(agent: &str) -> ProposedCommand {
ProposedCommand::new(
agent,
std::path::Path::new("/tmp"),
vec!["rm".into(), "x".into()],
"rm x",
)
}
#[test]
fn catastrophic_always_enqueues() {
for a in [
"claude-code",
"qwen",
"gemini",
"mcp",
"opencode",
"anything",
] {
assert!(
needs_queue_entry(&cmd(a), Class::Catastrophic),
"catastrophic must queue for {a}"
);
}
}
#[test]
fn ambiguous_skips_only_native_ask_agents() {
for a in ["claude-code", "qwen", "copilot", "cursor", "codex"] {
assert!(
!needs_queue_entry(&cmd(a), Class::Ambiguous),
"{a} has native ask → no queue orphan"
);
}
for a in ["gemini", "antigravity", "opencode", "mcp", "future-agent"] {
assert!(
needs_queue_entry(&cmd(a), Class::Ambiguous),
"{a} has no prompt → must queue"
);
}
}
}
#[cfg(test)]
mod score_budget_tests {
use super::ScoreBudget;
use std::time::{Duration, Instant};
#[test]
fn burst_is_bounded_then_refills_at_the_steady_rate() {
let t0 = Instant::now();
let mut b = ScoreBudget::new(8.0, 4.0, t0);
for i in 0..8 {
assert!(b.try_spend(t0), "burst token {i} should be granted");
}
assert!(!b.try_spend(t0), "9th in the same instant must be shed");
let t1 = t0 + Duration::from_secs(1);
for i in 0..4 {
assert!(b.try_spend(t1), "refilled token {i} should be granted");
}
assert!(!b.try_spend(t1), "refill is rate-capped, not a full reset");
}
#[test]
fn refill_never_exceeds_capacity() {
let t0 = Instant::now();
let mut b = ScoreBudget::new(8.0, 4.0, t0);
for _ in 0..8 {
assert!(b.try_spend(t0));
}
let later = t0 + Duration::from_secs(3600);
for i in 0..8 {
assert!(b.try_spend(later), "banked token {i} after a long idle");
}
assert!(
!b.try_spend(later),
"cap holds: no more than `capacity` banked"
);
}
}