Skip to main content

kintsugi_daemon/
ipc.rs

1//! Local IPC transport between interception and the daemon.
2//!
3//! Wire format: one newline-delimited JSON value per message. The interception
4//! side connects and sends a [`Request`]; the daemon replies with a [`Response`].
5//! A `Propose` carries a [`ProposedCommand`] and is answered with a [`Verdict`];
6//! a `Resolve` records a human's decision on a held command and is answered with
7//! `Ack`. Transport is a Unix domain socket (filesystem) or a Windows named pipe
8//! (namespaced), abstracted by the `interprocess` crate.
9
10use std::io::{BufRead, BufReader, Read, Write};
11use std::path::PathBuf;
12
13use anyhow::{Context, Result};
14use interprocess::local_socket::prelude::*;
15#[cfg(unix)]
16use interprocess::local_socket::GenericFilePath;
17#[cfg(not(unix))]
18use interprocess::local_socket::GenericNamespaced;
19use interprocess::local_socket::{ListenerOptions, Name, Stream};
20use kintsugi_core::{Decision, ProposedCommand, Verdict};
21use serde::{Deserialize, Serialize};
22
23/// A request from interception to the daemon.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25#[serde(tag = "kind", rename_all = "lowercase")]
26pub enum Request {
27    /// "Here is a command I'm about to run — what's the verdict?"
28    Propose(ProposedCommand),
29    /// "A human resolved a held command; record it (and maybe remember it)."
30    Resolve(Resolution),
31    /// "I observed a filesystem change that bypassed interception — just record
32    /// it." The backstop sends these so the daemon's single writer keeps the hash
33    /// chain intact.
34    Observe(Observation),
35    /// "I observed an agent ingest untrusted content (a web fetch, a search, an MCP
36    /// result, an out-of-workspace read, a download)." Provenance taint input
37    /// (P6.2): the daemon labels the session; it never blocks on this — observation
38    /// only labels, the trifecta rule decides later.
39    Ingest(kintsugi_core::ObservedIngest),
40    /// "Show me the provenance trail for this command" (P6.4). A read-only query for
41    /// the CLI/TUI: the daemon returns the session's untrusted reads plus this
42    /// command's sensitive-read → egress-sink → rule chain. Identifiers only.
43    Provenance(ProposedCommand),
44    /// "A human (no AI agent) already ran this shell command — record it for the
45    /// audit trail." Passive session recording: the daemon classifies it (so a
46    /// destructive command is flagged in the timeline) but never blocks or
47    /// snapshots, because by the time we hear about it the command has run.
48    Record(ProposedCommand),
49    /// "List the commands currently held for approval."
50    ListPending,
51    /// "What is the status of this queued command?" (`pending`/`approved`/`denied`).
52    // Struct variants (not newtype-of-String): serde's internally-tagged enums
53    // cannot represent a tagged newtype wrapping a primitive.
54    PendingStatus { id: String },
55    /// "A human approved this queued command id."
56    Approve { id: String },
57    /// "A human denied this queued command id."
58    Deny { id: String },
59    /// "Drop every still-pending entry from the queue without recording an audit
60    /// row per one — the bulk recovery for orphaned holds."
61    PrunePending,
62    /// "What is the daemon's runtime status?" — currently the active scorer, so
63    /// callers can tell whether the local model loaded or it's on the heuristic
64    /// fallback.
65    Status,
66    /// "I want to perform a privileged operation `op` (e.g. shutdown) — give me a
67    /// challenge." The daemon replies with a [`Response::Challenge`]. Auth is
68    /// enforced by the *daemon*, against the vault IT loaded at startup, so the
69    /// caller's environment can't point the check at a different/empty vault.
70    AuthBegin { op: String },
71    /// "Here is the challenge proof for `op`; do it." Currently only shutdown.
72    Shutdown {
73        op: String,
74        /// The challenge nonce + proof (hex). `None` on the unauthenticated path
75        /// (no vault provisioned) — modeled as absence, NOT an empty string, so
76        /// no placeholder ever flows into the proof-verification crypto sink.
77        nonce: Option<String>,
78        proof: Option<String>,
79    },
80}
81
82/// A filesystem change observed by the backstop watcher.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct Observation {
85    /// `created` | `modified` | `removed`. Serialized as `change` so it never
86    /// collides with the enum's internal `kind` tag.
87    #[serde(rename = "change")]
88    pub kind: String,
89    /// The path that changed.
90    pub path: String,
91}
92
93/// A human's resolution of a held command.
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct Resolution {
96    /// The original command being resolved.
97    pub command: ProposedCommand,
98    /// The human's decision — `Allow` or `Deny` (never `Hold`).
99    pub decision: Decision,
100    /// Whether to remember this decision for this exact command in this repo.
101    pub remember: bool,
102}
103
104/// The daemon's reply.
105#[derive(Debug, Clone, Serialize, Deserialize)]
106#[serde(tag = "kind", rename_all = "lowercase")]
107pub enum Response {
108    /// Verdict for a `Propose`.
109    Verdict(Verdict),
110    /// Acknowledgement of a `Resolve`/`Approve`/`Deny`/`Observe`.
111    Ack,
112    /// The approval queue (reply to `ListPending`). A struct variant because
113    /// serde's internally-tagged enums cannot wrap a bare sequence.
114    PendingList {
115        items: Vec<kintsugi_core::PendingItem>,
116    },
117    /// The status of a queued command (reply to `PendingStatus`): `pending` |
118    /// `approved` | `denied` | `gone` (not in the queue).
119    Pending { status: String },
120    /// The daemon's runtime status (reply to `Status`). `scorer` is the active
121    /// backend id, e.g. `heuristic` or `llama:Qwen3-4B-Instruct-2507-Q4_K_M`.
122    Status { scorer: String },
123    /// The provenance trail for a command (reply to `Provenance`). `tainted` is the
124    /// session's current taint state; `trail` is the ordered, identifier-only chain.
125    Provenance {
126        tainted: bool,
127        trail: Vec<kintsugi_core::ProvStep>,
128    },
129    /// Reply to `AuthBegin`: a fresh challenge. `locked` is false when the daemon
130    /// has no vault (then no proof is needed); otherwise the caller derives the
131    /// proof from `nonce` + `salt` + `params` and the admin password.
132    Challenge {
133        locked: bool,
134        nonce: String,
135        salt: String,
136        params: kintsugi_core::admin::KdfParams,
137    },
138    /// Something went wrong handling the request.
139    Error { message: String },
140}
141
142/// Resolve the socket path. Override with `KINTSUGI_SOCKET` (handy in tests).
143///
144/// On Unix this is a filesystem path under `$XDG_RUNTIME_DIR` (falling back to
145/// the temp dir). On Windows a namespaced pipe name is used instead.
146pub fn socket_path() -> PathBuf {
147    if let Ok(p) = std::env::var("KINTSUGI_SOCKET") {
148        return PathBuf::from(p);
149    }
150    #[cfg(unix)]
151    {
152        // $XDG_RUNTIME_DIR is already a per-user 0700 dir — the right home.
153        if let Ok(rt) = std::env::var("XDG_RUNTIME_DIR") {
154            if !rt.is_empty() {
155                return PathBuf::from(rt).join("kintsugi.sock");
156            }
157        }
158        // Otherwise use the per-user data dir (created 0700 at bind), never the
159        // world-writable temp dir, so another local user can't pre-create or
160        // connect to the socket.
161        if let Some(dirs) = directories::ProjectDirs::from("", "", "kintsugi") {
162            return dirs.data_dir().join("kintsugi.sock");
163        }
164        std::env::temp_dir().join("kintsugi.sock")
165    }
166    #[cfg(not(unix))]
167    {
168        PathBuf::from(r"\\.\pipe\kintsugi")
169    }
170}
171
172/// Best-effort chmod on Unix (no-op elsewhere). Used to keep the socket and its
173/// parent dir private to the owning user.
174#[cfg(unix)]
175pub(crate) fn set_mode(path: &std::path::Path, mode: u32) {
176    use std::os::unix::fs::PermissionsExt;
177    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
178}
179
180/// Build the `interprocess` name for the current platform.
181fn make_name() -> Result<Name<'static>> {
182    let path = socket_path();
183    #[cfg(unix)]
184    {
185        path.clone()
186            .to_fs_name::<GenericFilePath>()
187            .with_context(|| format!("invalid socket path {}", path.display()))
188    }
189    #[cfg(not(unix))]
190    {
191        let _ = &path;
192        "kintsugi"
193            .to_ns_name::<GenericNamespaced>()
194            .context("invalid namespaced pipe name")
195    }
196}
197
198/// Write one JSON message followed by a newline.
199fn write_message<W: Write, T: Serialize>(w: &mut W, value: &T) -> Result<()> {
200    let mut line = serde_json::to_string(value).context("serialize IPC message")?;
201    line.push('\n');
202    w.write_all(line.as_bytes()).context("write IPC message")?;
203    w.flush().context("flush IPC message")?;
204    Ok(())
205}
206
207/// Maximum size of a single IPC message. Bounds memory so a misbehaving or
208/// hostile local peer can't OOM/stall the single-threaded daemon with a giant or
209/// newline-free stream.
210pub const MAX_FRAME: u64 = 16 * 1024 * 1024;
211
212/// Read one newline-delimited JSON message from a length-bounded reader.
213fn read_message<R: BufRead, T: serde::de::DeserializeOwned>(r: &mut R) -> Result<T> {
214    let mut line = String::new();
215    let n = r.read_line(&mut line).context("read IPC message")?;
216    if n == 0 {
217        anyhow::bail!("connection closed before a message was received");
218    }
219    if !line.ends_with('\n') && n as u64 >= MAX_FRAME {
220        anyhow::bail!("IPC message exceeds {MAX_FRAME} bytes");
221    }
222    serde_json::from_str(line.trim_end()).context("deserialize IPC message")
223}
224
225/// Wrap a stream in a length-bounded buffered reader (see [`MAX_FRAME`]).
226fn bounded(stream: &mut Stream) -> BufReader<std::io::Take<&mut Stream>> {
227    BufReader::new(stream.take(MAX_FRAME))
228}
229
230/// Expect an `Ack`, mapping anything else to an error.
231fn expect_ack(resp: Response) -> Result<()> {
232    match resp {
233        Response::Ack => Ok(()),
234        Response::Error { message } => anyhow::bail!("daemon error: {message}"),
235        _ => anyhow::bail!("unexpected response (wanted Ack)"),
236    }
237}
238
239/// Send a request and read the response on a fresh connection.
240fn round_trip(req: &Request) -> Result<Response> {
241    let name = make_name()?;
242    let mut stream =
243        Stream::connect(name).context("connect to kintsugi daemon (is it running?)")?;
244    write_message(&mut stream, req)?;
245    let mut reader = bounded(&mut stream);
246    read_message(&mut reader)
247}
248
249/// Client side: connect, send a request, and block for the response.
250pub struct Client;
251
252impl Client {
253    /// Propose a command and await its verdict.
254    pub fn send(cmd: &ProposedCommand) -> Result<Verdict> {
255        match round_trip(&Request::Propose(cmd.clone()))? {
256            Response::Verdict(v) => Ok(v),
257            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
258            _ => anyhow::bail!("unexpected response to Propose"),
259        }
260    }
261
262    /// Record a human's resolution of a held command.
263    pub fn resolve(resolution: &Resolution) -> Result<()> {
264        expect_ack(round_trip(&Request::Resolve(resolution.clone()))?)
265    }
266
267    /// Record an observed filesystem change (backstop).
268    pub fn observe(observation: &Observation) -> Result<()> {
269        expect_ack(round_trip(&Request::Observe(observation.clone()))?)
270    }
271
272    /// Report an observed untrusted-content ingestion (provenance taint input).
273    pub fn ingest(observed: &kintsugi_core::ObservedIngest) -> Result<()> {
274        expect_ack(round_trip(&Request::Ingest(observed.clone()))?)
275    }
276
277    /// Fetch the provenance trail for a command: `(tainted, trail)`.
278    pub fn provenance(cmd: &ProposedCommand) -> Result<(bool, Vec<kintsugi_core::ProvStep>)> {
279        match round_trip(&Request::Provenance(cmd.clone()))? {
280            Response::Provenance { tainted, trail } => Ok((tainted, trail)),
281            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
282            _ => anyhow::bail!("unexpected response to Provenance"),
283        }
284    }
285
286    /// Record a shell command a human already ran (passive session recording).
287    pub fn record(cmd: &ProposedCommand) -> Result<()> {
288        expect_ack(round_trip(&Request::Record(cmd.clone()))?)
289    }
290
291    /// List the commands currently held for approval.
292    pub fn list_pending() -> Result<Vec<kintsugi_core::PendingItem>> {
293        match round_trip(&Request::ListPending)? {
294            Response::PendingList { items } => Ok(items),
295            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
296            _ => anyhow::bail!("unexpected response to ListPending"),
297        }
298    }
299
300    /// The status of a queued command: `pending` | `approved` | `denied` | `gone`.
301    pub fn pending_status(id: &str) -> Result<String> {
302        match round_trip(&Request::PendingStatus { id: id.to_string() })? {
303            Response::Pending { status } => Ok(status),
304            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
305            _ => anyhow::bail!("unexpected response to PendingStatus"),
306        }
307    }
308
309    /// Approve a queued command (records the human decision; may snapshot).
310    pub fn approve(id: &str) -> Result<()> {
311        expect_ack(round_trip(&Request::Approve { id: id.to_string() })?)
312    }
313
314    /// Deny a queued command.
315    pub fn deny(id: &str) -> Result<()> {
316        expect_ack(round_trip(&Request::Deny { id: id.to_string() })?)
317    }
318
319    /// Prune every still-pending entry from the queue without recording a
320    /// human:deny per one — recovery for orphaned holds. Returns the count
321    /// pruned (reported by the daemon via a `Pending { status: "N" }` reply).
322    pub fn prune_pending() -> Result<u64> {
323        match round_trip(&Request::PrunePending)? {
324            Response::Pending { status } => status
325                .parse()
326                .map_err(|e| anyhow::anyhow!("bad count: {e}")),
327            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
328            _ => anyhow::bail!("unexpected response to PrunePending"),
329        }
330    }
331
332    /// The daemon's active scorer backend id (e.g. `heuristic` or
333    /// `llama:<model>`). Lets callers report whether the local model is loaded.
334    pub fn status_scorer() -> Result<String> {
335        match round_trip(&Request::Status)? {
336            Response::Status { scorer } => Ok(scorer),
337            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
338            _ => anyhow::bail!("unexpected response to Status"),
339        }
340    }
341
342    /// Begin authenticating a privileged op; returns (locked, nonce, salt, params).
343    pub fn auth_begin(op: &str) -> Result<(bool, String, String, kintsugi_core::admin::KdfParams)> {
344        match round_trip(&Request::AuthBegin { op: op.to_string() })? {
345            Response::Challenge {
346                locked,
347                nonce,
348                salt,
349                params,
350            } => Ok((locked, nonce, salt, params)),
351            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
352            _ => anyhow::bail!("unexpected response to AuthBegin"),
353        }
354    }
355
356    /// Complete a shutdown. Pass `Some(nonce_hex)` + `Some(proof_hex)` for the
357    /// authenticated path (a provisioned vault); pass `None`/`None` when no vault
358    /// is set and no proof is required. Absence is modeled as `None`, never an
359    /// empty string, so a placeholder can't be mistaken for a real nonce.
360    pub fn shutdown(op: &str, nonce: Option<&str>, proof: Option<&str>) -> Result<()> {
361        expect_ack(round_trip(&Request::Shutdown {
362            op: op.to_string(),
363            nonce: nonce.map(str::to_string),
364            proof: proof.map(str::to_string),
365        })?)
366    }
367
368    /// Whether a daemon appears to be listening.
369    pub fn is_daemon_running() -> bool {
370        match make_name() {
371            Ok(name) => Stream::connect(name).is_ok(),
372            Err(_) => false,
373        }
374    }
375}
376
377/// Server side: a bound listener that dispatches each request to a handler.
378pub struct Server {
379    listener: interprocess::local_socket::Listener,
380}
381
382impl Server {
383    /// Bind the listener, clearing any stale Unix socket file first.
384    pub fn bind() -> Result<Self> {
385        // Refuse to start a second daemon: two writers would race on the event
386        // log's prev_hash and split the timeline. Clearing the stale socket below
387        // would otherwise let a second instance silently steal the endpoint.
388        if Client::is_daemon_running() {
389            anyhow::bail!(
390                "a kintsugi daemon is already running on {}",
391                socket_path().display()
392            );
393        }
394        #[cfg(unix)]
395        {
396            let path = socket_path();
397            // Ensure a private parent dir (0700) so peers can't pre-create the
398            // socket, then clear any stale socket file.
399            if let Some(parent) = path.parent() {
400                let _ = std::fs::create_dir_all(parent);
401                set_mode(parent, 0o700);
402            }
403            if path.exists() {
404                let _ = std::fs::remove_file(&path);
405            }
406        }
407        let name = make_name()?;
408        let listener = ListenerOptions::new()
409            .name(name)
410            .create_sync()
411            .context("bind kintsugi daemon socket")?;
412        // Restrict the socket to the owning user (no group/other access), so on a
413        // shared host another user can't connect and Approve/Deny/Resolve.
414        #[cfg(unix)]
415        set_mode(&socket_path(), 0o600);
416        Ok(Self { listener })
417    }
418
419    /// The path/name the server is listening on.
420    pub fn endpoint() -> PathBuf {
421        socket_path()
422    }
423
424    /// Serve connections sequentially, calling `handler` for each request.
425    pub fn serve<F>(self, mut handler: F) -> Result<()>
426    where
427        F: FnMut(Request) -> Response,
428    {
429        for incoming in self.listener.incoming() {
430            let stream = match incoming {
431                Ok(s) => s,
432                Err(e) => {
433                    eprintln!("kintsugi-daemon: accept error: {e}");
434                    continue;
435                }
436            };
437            if let Err(e) = Self::handle_one(stream, &mut handler) {
438                eprintln!("kintsugi-daemon: connection error: {e}");
439            }
440        }
441        Ok(())
442    }
443
444    /// Serve connections until `stop()` returns true (checked after each one).
445    /// Lets a handler request its own shutdown (e.g. an authenticated `Shutdown`).
446    pub fn serve_until<F, S>(self, mut handler: F, stop: S) -> Result<()>
447    where
448        F: FnMut(Request) -> Response,
449        S: Fn() -> bool,
450    {
451        for incoming in self.listener.incoming() {
452            let stream = match incoming {
453                Ok(s) => s,
454                Err(e) => {
455                    eprintln!("kintsugi-daemon: accept error: {e}");
456                    continue;
457                }
458            };
459            if let Err(e) = Self::handle_one(stream, &mut handler) {
460                eprintln!("kintsugi-daemon: connection error: {e}");
461            }
462            if stop() {
463                break;
464            }
465        }
466        Ok(())
467    }
468
469    /// Serve exactly `count` connections then stop. Used by tests.
470    pub fn serve_n<F>(self, count: usize, mut handler: F) -> Result<()>
471    where
472        F: FnMut(Request) -> Response,
473    {
474        if count == 0 {
475            return Ok(());
476        }
477        let mut served = 0;
478        for incoming in self.listener.incoming() {
479            let stream = incoming.context("accept connection")?;
480            Self::handle_one(stream, &mut handler)?;
481            served += 1;
482            if served >= count {
483                break;
484            }
485        }
486        Ok(())
487    }
488
489    fn handle_one<F>(mut stream: Stream, handler: &mut F) -> Result<()>
490    where
491        F: FnMut(Request) -> Response,
492    {
493        // Read the request line directly (rather than via `read_message`) so we can
494        // tell a *benign* zero-byte disconnect — a peer that connected and closed
495        // without sending, e.g. `is_daemon_running`'s liveness probe — apart from a
496        // real protocol error. A probe is not worth logging; treat it as a no-op.
497        let mut line = String::new();
498        let n = {
499            let mut reader = bounded(&mut stream);
500            reader.read_line(&mut line).context("read IPC message")?
501        };
502        if n == 0 {
503            return Ok(()); // connected then closed with no message — nothing to do
504        }
505        if !line.ends_with('\n') && n as u64 >= MAX_FRAME {
506            anyhow::bail!("IPC message exceeds {MAX_FRAME} bytes");
507        }
508        let req: Request =
509            serde_json::from_str(line.trim_end()).context("deserialize IPC message")?;
510        let resp = handler(req);
511        write_message(&mut stream, &resp)?;
512        Ok(())
513    }
514}