openlatch-client 0.6.19

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! One verdict per agent on whether its model calls go through the relay, computed by the daemon
//! and persisted for `init` and `doctor` (`<ol_dir>/state/relay-readiness.json`).
//!
//! The preflight proves the listener, the upstream path and the OS trust store. It never proves
//! that the agent's OWN process routes through the relay: a session, a terminal or an IDE window
//! opened before the wiring keeps the environment it started with. This module adds the two facts
//! that close that gap, without a model call:
//!
//! - **structural proof** — the delivery reads back as ours, the path is proven, the agent's own
//!   runtime trusts the relay, and no running surface predates the wiring;
//! - **traffic** — a real, non-preflight call attributed to this agent went through the relay
//!   since its current wiring, persisted so a daemon restart does not forget it.
//!
//! [`judge`] is pure: every input is a fact gathered by the daemon's wiring pass.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// The state file's name under `<ol_dir>/state/`.
pub const READINESS_FILE: &str = "relay-readiness.json";

/// The per-agent traffic ledger's name under `<ol_dir>/state/`: when this agent's first real call
/// went through the relay, and since which wiring.
pub const TRAFFIC_FILE: &str = "relay-traffic.json";

/// The shape version of both files. A reader meeting another version treats the file as absent.
pub const VERSION: u32 = 1;

/// Where the readiness file lives.
pub fn readiness_path(ol_dir: &Path) -> PathBuf {
    ol_dir.join("state").join(READINESS_FILE)
}

/// Where the traffic ledger lives.
pub fn traffic_path(ol_dir: &Path) -> PathBuf {
    ol_dir.join("state").join(TRAFFIC_FILE)
}

/// One agent's verdict. Exactly one applies; `ready` and `captured` are never a warning.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "verdict", rename_all = "kebab-case")]
pub enum Verdict {
    /// A real, non-preflight model call from this agent went through the relay since its current
    /// wiring.
    Captured { at: DateTime<Utc> },
    /// Structurally proven: the next call is captured.
    Ready,
    /// A running process predates the wiring and cannot pick it up live.
    RestartNeeded {
        /// What to restart, as the user knows it: `Cursor`, `a Claude Code session`.
        app: String,
        /// How, in one sentence.
        how: String,
        /// Whether one of the stale surfaces is one OpenLatch restarts itself on a yes (Cline.app's
        /// hub); every other one is the user's to restart.
        #[serde(default)]
        by_openlatch: bool,
    },
    /// A structural check failed.
    Failed { why: String, fix: String },
}

impl Verdict {
    /// Stable label for `--json` and the report.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Captured { .. } => "captured",
            Self::Ready => "ready",
            Self::RestartNeeded { .. } => "restart-needed",
            Self::Failed { .. } => "failed",
        }
    }

    /// `captured` or `ready`: the agent's next call is captured, nothing to do.
    pub fn is_ok(&self) -> bool {
        matches!(self, Self::Captured { .. } | Self::Ready)
    }
}

/// How a stale surface gets the wiring.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Restart {
    /// OpenLatch restarts it itself, on the user's yes (Cline.app's hub).
    ByOpenLatch,
    /// The user quits and reopens an app OpenLatch never kills (unsaved work).
    QuitAndReopen,
    /// A terminal session: the user starts a new one.
    NewSession,
}

/// One surface of an agent whose processes the readiness pass looks for, as a binding declares
/// it ([`crate::hooks::binding::AgentBinding::relay_surfaces`]). The pass lists every declared
/// root in ONE read of the process table (a PowerShell run on Windows), never one per binding.
#[derive(Debug, Clone)]
pub struct SurfaceDecl {
    /// What the user calls it: `Cursor`, `Claude Code session`.
    pub name: &'static str,
    /// The install directories or application bundles its executables live under.
    pub roots: Vec<PathBuf>,
    /// Which processes under `roots` count, from their argv: an Electron app's main process only
    /// (`hooks::cursor::is_main_process`), a CLI's sessions but not its background helpers.
    pub(crate) counts: fn(&crate::hooks::cline_app::process::ExeProcess) -> bool,
    /// See [`RunningSurface::picks_up_live`].
    pub picks_up_live: bool,
    pub restart: Restart,
}

/// How old a running surface is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Age {
    /// It started then.
    Started(SystemTime),
    /// Known to predate the wiring without a start time: a hub found running without capture.
    Predates,
}

/// One running process of an agent's surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningSurface {
    /// What the user calls it: `Cursor`, `Claude Code session`, `Cline.app hub`.
    pub name: &'static str,
    /// When it started.
    pub age: Age,
    /// Whether a process of this surface that predates the wiring reads it anyway (it re-reads its
    /// configuration per session or per request). Recorded per surface from a live test.
    pub picks_up_live: bool,
    /// How it gets the wiring when it cannot pick it up live.
    pub restart: Restart,
}

/// Everything [`judge`] needs about one wired agent.
#[derive(Debug, Clone)]
pub struct Facts {
    /// The preflight verdict: the listener, the upstream path and, for an intercepted agent, the
    /// store and the tunnel.
    pub path: crate::model_relay::preflight::Verdict,
    /// The delivery read back from disk and the agent's own runtime trusting the relay. `Err`
    /// carries `(why, fix)`.
    pub delivery: Result<(), (String, String)>,
    /// When the current wiring was first seen in place.
    pub wired_since: SystemTime,
    /// The agent's first real call through the relay, when one has been seen at all.
    pub captured_at: Option<SystemTime>,
    /// Every running process of the agent's surfaces. `Err` = the process table could not be
    /// read, which is unknown and never a restart ask.
    pub running: Result<Vec<RunningSurface>, String>,
}

/// The verdict for one wired agent. `None` while the preflight has not answered yet: the agent
/// gets no entry, and `init` keeps waiting.
pub fn judge(f: &Facts) -> Option<Verdict> {
    use crate::model_relay::preflight::Verdict as Path;

    match &f.path {
        Path::Pending => return None,
        // The agent refused the relay's certificate: captured from its next launch, and
        // reported to the platform meanwhile — not a structural failure.
        Path::Failed(why) if crate::daemon::wiring_tamper::is_refusal(why) => {
            return Some(Verdict::RestartNeeded {
                app: "the agent".into(),
                how: "Quit and reopen it: it reads trusted certificates once per launch.".into(),
                by_openlatch: false,
            })
        }
        Path::Failed(why) => {
            return Some(Verdict::Failed {
                why: why.clone(),
                fix: "Run `openlatch doctor` for the cause and its fix.".into(),
            })
        }
        Path::Ok => {}
    }
    if let Err((why, fix)) = &f.delivery {
        return Some(Verdict::Failed {
            why: why.clone(),
            fix: fix.clone(),
        });
    }
    if let Some(v) = restart_needed(f.running.as_deref().unwrap_or(&[]), f.wired_since) {
        return Some(v);
    }
    Some(match f.captured_at.filter(|t| *t >= f.wired_since) {
        Some(at) => Verdict::Captured { at: at.into() },
        None => Verdict::Ready,
    })
}

/// The ask for every running surface that predates the wiring and cannot pick it up live. One
/// verdict, naming each surface once, OpenLatch's own restart first.
fn restart_needed(running: &[RunningSurface], wired_since: SystemTime) -> Option<Verdict> {
    let mut stale: Vec<&RunningSurface> = running
        .iter()
        .filter(|s| {
            !s.picks_up_live
                && match s.age {
                    Age::Started(t) => t < wired_since,
                    Age::Predates => true,
                }
        })
        .collect();
    if stale.is_empty() {
        return None;
    }
    stale.sort_by_key(|s| (s.restart as u8, s.name));
    stale.dedup_by_key(|s| s.name);
    let app = stale.iter().map(|s| s.name).collect::<Vec<_>>().join(", ");
    let how = stale.iter().map(|s| how(s)).collect::<Vec<_>>().join(" ");
    Some(Verdict::RestartNeeded {
        app,
        how,
        by_openlatch: stale.iter().any(|s| s.restart == Restart::ByOpenLatch),
    })
}

/// One sentence per stale surface.
fn how(s: &RunningSurface) -> String {
    match s.restart {
        Restart::ByOpenLatch => format!(
            "OpenLatch restarts the {} for you; an open conversation reconnects to it.",
            s.name
        ),
        Restart::QuitAndReopen => format!(
            "Quit and reopen {}: it was open before OpenLatch and reads its settings at launch.",
            s.name
        ),
        Restart::NewSession => format!(
            "Start a new {}: one opened before OpenLatch keeps going direct.",
            s.name
        ),
    }
}

/// One agent's entry in the readiness file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentReadiness {
    #[serde(flatten)]
    pub verdict: Verdict,
    /// When the current wiring was first seen in place.
    pub wired_since: DateTime<Utc>,
}

/// The readiness file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReadinessFile {
    pub version: u32,
    pub computed_at: DateTime<Utc>,
    /// Keyed by agent type. A wired agent whose preflight has not answered has no entry.
    pub agents: BTreeMap<String, AgentReadiness>,
}

/// Read the readiness file. `None` when absent, unreadable or another version.
pub fn read(ol_dir: &Path) -> Option<ReadinessFile> {
    let body = std::fs::read_to_string(readiness_path(ol_dir)).ok()?;
    serde_json::from_str::<ReadinessFile>(&body)
        .ok()
        .filter(|f| f.version == VERSION)
}

/// Write the readiness file, only when its verdicts changed: `computed_at` alone never rewrites
/// it. Returns whether it wrote.
pub fn write_if_changed(ol_dir: &Path, agents: BTreeMap<String, AgentReadiness>) -> bool {
    if read(ol_dir).is_some_and(|f| f.agents == agents) {
        return false;
    }
    let file = ReadinessFile {
        version: VERSION,
        computed_at: Utc::now(),
        agents,
    };
    match crate::core::fs_secure::write_json_state(&readiness_path(ol_dir), &file) {
        Ok(()) => true,
        Err(e) => {
            tracing::warn!(error = %e, "could not write the relay readiness file");
            false
        }
    }
}

/// One agent's traffic record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Traffic {
    /// The first real call through the relay since `wired_since`.
    pub captured_at: Option<DateTime<Utc>>,
    /// When the current wiring was first seen in place. Kept across a daemon restart while the
    /// agent stays wired, so a restart neither forgets a capture nor makes an older session stale.
    pub wired_since: DateTime<Utc>,
}

/// The traffic ledger file.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrafficFile {
    pub version: u32,
    pub agents: BTreeMap<String, Traffic>,
}

/// Read the traffic ledger. Empty when absent, unreadable or another version.
pub fn read_traffic(ol_dir: &Path) -> BTreeMap<String, Traffic> {
    std::fs::read_to_string(traffic_path(ol_dir))
        .ok()
        .and_then(|b| serde_json::from_str::<TrafficFile>(&b).ok())
        .filter(|f| f.version == VERSION)
        .map(|f| f.agents)
        .unwrap_or_default()
}

/// Write the traffic ledger.
pub fn write_traffic(ol_dir: &Path, agents: &BTreeMap<String, Traffic>) -> std::io::Result<()> {
    crate::core::fs_secure::write_json_state(
        &traffic_path(ol_dir),
        &TrafficFile {
            version: VERSION,
            agents: agents.clone(),
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model_relay::preflight::Verdict as Path;
    use std::time::Duration;

    fn t(secs: u64) -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000 + secs)
    }

    fn facts() -> Facts {
        Facts {
            path: Path::Ok,
            delivery: Ok(()),
            wired_since: t(100),
            captured_at: None,
            running: Ok(vec![]),
        }
    }

    fn surface(name: &'static str, started: u64, live: bool, restart: Restart) -> RunningSurface {
        RunningSurface {
            name,
            age: Age::Started(t(started)),
            picks_up_live: live,
            restart,
        }
    }

    #[test]
    fn a_pending_preflight_has_no_verdict() {
        let f = Facts {
            path: Path::Pending,
            ..facts()
        };
        assert_eq!(judge(&f), None);
    }

    #[test]
    fn a_failed_path_is_failed() {
        let f = Facts {
            path: Path::Failed("upstream unreachable".into()),
            ..facts()
        };
        assert!(
            matches!(judge(&f), Some(Verdict::Failed { why, .. }) if why == "upstream unreachable")
        );
    }

    #[test]
    fn a_failed_delivery_is_failed_with_its_fix() {
        let f = Facts {
            delivery: Err(("not ours".into(), "run doctor --fix".into())),
            ..facts()
        };
        assert_eq!(
            judge(&f),
            Some(Verdict::Failed {
                why: "not ours".into(),
                fix: "run doctor --fix".into()
            })
        );
    }

    #[test]
    fn proven_and_nothing_running_is_ready() {
        assert_eq!(judge(&facts()), Some(Verdict::Ready));
    }

    #[test]
    fn a_surface_started_after_the_wiring_is_ready() {
        let f = Facts {
            running: Ok(vec![surface("Cursor", 200, false, Restart::QuitAndReopen)]),
            ..facts()
        };
        assert_eq!(judge(&f), Some(Verdict::Ready));
    }

    #[test]
    fn an_older_surface_that_picks_it_up_live_is_ready() {
        let f = Facts {
            running: Ok(vec![surface("Codex", 50, true, Restart::NewSession)]),
            ..facts()
        };
        assert_eq!(judge(&f), Some(Verdict::Ready));
    }

    #[test]
    fn an_older_surface_that_cannot_is_restart_needed() {
        let f = Facts {
            running: Ok(vec![surface("Cursor", 50, false, Restart::QuitAndReopen)]),
            ..facts()
        };
        match judge(&f) {
            Some(Verdict::RestartNeeded {
                app, by_openlatch, ..
            }) => {
                assert_eq!(app, "Cursor");
                assert!(!by_openlatch);
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn restart_needed_wins_over_an_earlier_capture() {
        let f = Facts {
            captured_at: Some(t(150)),
            running: Ok(vec![surface(
                "Claude Code session",
                50,
                false,
                Restart::NewSession,
            )]),
            ..facts()
        };
        assert_eq!(judge(&f).map(|v| v.label()), Some("restart-needed"));
    }

    #[test]
    fn a_stale_hub_is_offered_as_openlatch_s_restart() {
        let hub = surface("Cline.app hub", 50, false, Restart::ByOpenLatch);
        let f = Facts {
            running: Ok(vec![hub.clone()]),
            ..facts()
        };
        assert!(matches!(
            judge(&f),
            Some(Verdict::RestartNeeded {
                by_openlatch: true,
                ..
            })
        ));
        let f = Facts {
            running: Ok(vec![
                hub,
                surface("VS Code", 50, false, Restart::QuitAndReopen),
            ]),
            ..facts()
        };
        match judge(&f) {
            Some(Verdict::RestartNeeded {
                app, by_openlatch, ..
            }) => {
                assert_eq!(app, "Cline.app hub, VS Code");
                assert!(by_openlatch, "the hub is still OpenLatch's to restart");
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn a_surface_known_to_predate_the_wiring_is_restart_needed() {
        let f = Facts {
            running: Ok(vec![RunningSurface {
                name: "Cline.app hub",
                age: Age::Predates,
                picks_up_live: false,
                restart: Restart::ByOpenLatch,
            }]),
            ..facts()
        };
        assert!(matches!(
            judge(&f),
            Some(Verdict::RestartNeeded {
                by_openlatch: true,
                ..
            })
        ));
    }

    #[test]
    fn an_unreadable_process_table_never_asks() {
        let f = Facts {
            running: Err("no table".into()),
            ..facts()
        };
        assert_eq!(judge(&f), Some(Verdict::Ready));
    }

    #[test]
    fn traffic_since_the_wiring_is_captured_and_older_traffic_is_not() {
        let f = Facts {
            captured_at: Some(t(150)),
            ..facts()
        };
        assert_eq!(judge(&f).map(|v| v.label()), Some("captured"));
        let f = Facts {
            captured_at: Some(t(50)),
            ..facts()
        };
        assert_eq!(judge(&f), Some(Verdict::Ready));
    }

    #[test]
    fn the_file_round_trips_and_is_written_only_on_a_change() {
        let dir = tempfile::tempdir().unwrap();
        let mut agents = BTreeMap::new();
        agents.insert(
            "cursor".to_string(),
            AgentReadiness {
                verdict: Verdict::RestartNeeded {
                    app: "Cursor".into(),
                    how: "Quit and reopen Cursor.".into(),
                    by_openlatch: false,
                },
                wired_since: t(100).into(),
            },
        );
        assert!(write_if_changed(dir.path(), agents.clone()));
        assert!(!write_if_changed(dir.path(), agents.clone()));
        let read_back = read(dir.path()).expect("written");
        assert_eq!(read_back.agents, agents);
        let raw = std::fs::read_to_string(readiness_path(dir.path())).unwrap();
        assert!(raw.contains("\"verdict\": \"restart-needed\""), "{raw}");
    }

    #[test]
    fn another_version_reads_as_absent() {
        let dir = tempfile::tempdir().unwrap();
        crate::core::fs_secure::write_json_state(
            &readiness_path(dir.path()),
            &serde_json::json!({"version": 99, "computed_at": "2026-10-13T00:00:00Z", "agents": {}}),
        )
        .unwrap();
        assert!(read(dir.path()).is_none());
    }

    #[test]
    fn the_traffic_ledger_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        assert!(read_traffic(dir.path()).is_empty());
        let mut m = BTreeMap::new();
        m.insert(
            "claude-code".to_string(),
            Traffic {
                captured_at: Some(t(150).into()),
                wired_since: t(100).into(),
            },
        );
        write_traffic(dir.path(), &m).unwrap();
        assert_eq!(read_traffic(dir.path()), m);
    }
}