openlatch-client 0.6.0

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
//! Terminal UI for guided commands: a clack-style rail of stages, a
//! two-option select and a result card, over one process-scoped sink.
//!
//! ```text
//! ┌  Setting up this machine
//! │
//! ◇  Checked this machine · found Cline
//! │
//! ◆  Usage data
//! │  Share anonymous usage data to help improve OpenLatch?
//! │  › ● Yes, share    ○ No thanks        ← → then Enter
//! │
//! └  Done.
//! ```
//!
//! ## One sink, installed by a guard
//!
//! A command opens the rail with [`install`] and holds the returned
//! [`RailGuard`] for as long as the rail should own stderr. While it is held,
//! [`OutputConfig`]'s helpers route through it — `print_step`, `print_substep`
//! and `print_info` become [`detail`] (logged, shown only with `--verbose`),
//! `print_note` becomes [`note`], and `print_error` closes the running stage as
//! failed — so the dozens of helpers that already print through
//! `OutputConfig` join the rail without a signature change. Dropping the guard
//! restores today's output. Same process-scoped pattern as the
//! `report::verdict` latch.
//!
//! With no rail installed every function here is a no-op, and every
//! `OutputConfig` helper prints exactly what it printed before this module
//! existed.
//!
//! ## Errors print once
//!
//! [`OutputConfig::print_error`] records what it printed ([`mark_error_reported`]);
//! `main` prints a returned error only when it was not already reported
//! ([`error_reported`]). A command that shows its own error — inside the rail,
//! or ahead of hints that must follow it — no longer has it printed a second
//! time on the way out.

pub mod card;
pub mod log;
pub mod paint;
pub mod rail;
pub mod select;
pub mod term;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

pub use card::{result_line, result_line_token, Card, Row, Section, Update, Verdict};
pub use paint::Tone;
pub use rail::{Out, Rail};
pub use select::{Select, SelectOutcome};
pub use term::{Caps, Mode};

use crate::cli::output::OutputConfig;
use crate::error::OlError;

static RAIL: Mutex<Option<Rail>> = Mutex::new(None);
/// Fast path for the `OutputConfig` helpers: set exactly while `RAIL` is `Some`.
static ACTIVE: AtomicBool = AtomicBool::new(false);

fn slot() -> std::sync::MutexGuard<'static, Option<Rail>> {
    RAIL.lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Keeps the rail installed; dropping it uninstalls the rail (stopping any
/// spinner) and restores plain `OutputConfig` output.
#[must_use = "the rail is uninstalled as soon as the guard is dropped"]
pub struct RailGuard {
    _private: (),
}

impl Drop for RailGuard {
    fn drop(&mut self) {
        let rail = {
            let mut slot = slot();
            ACTIVE.store(false, Ordering::SeqCst);
            slot.take()
        };
        drop(rail);
    }
}

/// Open a rail of `total` stages for `command` on the real stderr, with its
/// transcript at `<openlatch dir>/logs/<command>-YYYY-MM-DD.log`.
///
/// `None` — and nothing changes — under `--json` or `--quiet`, or when a rail
/// is already installed.
pub fn install(output: &OutputConfig, command: &str, total: usize) -> Option<RailGuard> {
    let caps = Caps::detect(output)?;
    let log = log::Transcript::open(command);
    install_rail(Rail::new(
        caps,
        Out::Term(console::Term::stderr()),
        log,
        total,
    ))
}

/// Install a prepared rail (e.g. [`Rail::buffer`] in a test). `None` when a
/// rail is already installed.
pub fn install_rail(rail: Rail) -> Option<RailGuard> {
    let mut slot = slot();
    if slot.is_some() {
        return None;
    }
    *slot = Some(rail);
    ACTIVE.store(true, Ordering::SeqCst);
    Some(RailGuard { _private: () })
}

/// Whether a rail is installed.
pub fn is_active() -> bool {
    ACTIVE.load(Ordering::SeqCst)
}

/// Run `f` on the installed rail; `None` when there is none.
fn with<R>(f: impl FnOnce(&mut Rail) -> R) -> Option<R> {
    if !is_active() {
        return None;
    }
    slot().as_mut().map(f)
}

/// `┌  <title>` — opens the rail.
pub fn intro(title: &str) {
    with(|r| r.intro(title));
}

/// Open the next stage: `running` while it works, `done` on its result line.
pub fn stage(running: &str, done: &str) {
    with(|r| r.stage(running, done));
}

/// Update what the running stage's spinner says.
pub fn progress(text: &str) {
    with(|r| r.progress(text));
}

/// Close the running stage: `◇  <done> · <result>`.
pub fn done(result: &str) {
    with(|r| r.done(result));
}

/// Close the running stage with only the result in `tone` (see
/// [`Rail::done_toned`]).
pub fn done_toned(result: &str, tone: Tone) {
    with(|r| r.done_toned(result, tone));
}

/// Show how far the running stage has got (see [`Rail::meter`]).
pub fn meter(frac: Option<f64>, tail: &str) {
    with(|r| r.meter(frac, tail));
}

/// Write the running stage's `[n/N] <running>…` heading now, in plain mode,
/// for a long stage that would otherwise leave a log looking stuck (see
/// [`Rail::announce`]).
pub fn announce() {
    with(|r| r.announce());
}

/// Close the running stage as needing the user: `!  <done> · <result>`.
pub fn attention(result: &str) {
    with(|r| r.attention(result));
}

/// An always-visible line under the gutter.
pub fn note(text: &str) {
    with(|r| r.note(text));
}

/// [`stage`], naming what the stage is for the line a failure leaves
/// (`Start OpenLatch failed`).
pub fn stage_named(name: &str, running: &str, done: &str) {
    with(|r| r.stage_named(name, running, done));
}

/// A dim line under the running stage that goes when it closes (see
/// [`Rail::hint`]).
pub fn hint(text: &str) {
    with(|r| r.hint(text));
}

/// A [`hint`] ending in a URL that is never wrapped: `Didn't open? https://…`.
pub fn link(lead: &str, url: &str) {
    with(|r| r.link(lead, url));
}

/// Close the running stage as where the run stops, without an error (see
/// [`Rail::halt`]).
pub fn halt(result: &str) {
    with(|r| r.halt(result));
}

/// Close the running stage as failed without an error of its own (see
/// [`Rail::failed`]).
pub fn failed(result: &str) {
    with(|r| r.failed(result));
}

/// Change the running stage's closing label (see [`Rail::relabel`]).
pub fn relabel(done: &str) {
    with(|r| r.relabel(done));
}

/// The gutter a line under the running stage starts with (`│  `), for output
/// the rail does not draw itself — a third-party prompt. `None` with no rail.
pub fn gutter() -> Option<String> {
    with(|r| r.gutter())
}

/// A line that is logged, and shown only with `--verbose`.
pub fn detail(text: &str) {
    with(|r| r.detail(text));
}

/// Close the running stage as failed with the error block under it, and mark
/// the error reported. `false` when no rail is installed.
pub fn fail(error: &OlError) -> bool {
    let shown = with(|r| r.fail(error)).is_some();
    if shown {
        mark_error_reported(error);
    }
    shown
}

/// `└  <text>` — closes the rail.
pub fn outro(text: &str) {
    with(|r| r.outro(text));
}

/// Draw the result card.
pub fn card(card: &Card) {
    with(|r| r.card(card));
}

/// Draw the result card with amber warning lines heading its footer.
pub fn card_with_warnings(card: &Card, warnings: &[String]) {
    with(|r| r.card_with_warnings(card, warnings));
}

/// Write the `result=` line (plain mode only; always logged).
pub fn result(verdict: Verdict, exit_code: i32, fields: &[(&str, &str)]) {
    with(|r| r.result_line(verdict, exit_code, fields));
}

/// [`result`] with a command's own token (`updated`, `up_to_date`, …).
pub fn result_token(token: &str, exit_code: i32, fields: &[(&str, &str)]) {
    with(|r| r.result_line_token(token, exit_code, fields));
}

/// Ask a two-option question. `None` when no rail is installed.
pub fn select(question: &Select<'_>) -> Option<SelectOutcome> {
    with(|r| r.select(question))
}

/// Run `f` with the spinner out of the way, for output the rail does not own.
/// Runs `f` directly when no rail is installed.
pub fn suspend<R>(f: impl FnOnce() -> R) -> R {
    if !is_active() {
        return f();
    }
    let slot = slot();
    match slot.as_ref() {
        Some(rail) => rail.suspend(f),
        None => f(),
    }
}

/// The installed rail's capabilities.
pub fn caps() -> Option<Caps> {
    with(|r| *r.caps())
}

/// Where the installed rail's transcript is written.
pub fn log_path() -> Option<std::path::PathBuf> {
    with(|r| r.log_path().map(std::path::Path::to_path_buf)).flatten()
}

/// Move a transcript this run created out of the state directory, into the OS
/// temp directory, removing the directories opening it created (see
/// [`log::Transcript::take_back`]). For a failure that must leave the host as
/// it was found; the card then points at the moved file.
pub fn take_back_log() {
    with(|r| r.take_back_log(&std::env::temp_dir()));
}

/// Tests that install the process-wide rail run one at a time.
#[cfg(test)]
pub(crate) static INSTALL_LOCK: Mutex<()> = Mutex::new(());

static REPORTED: Mutex<Option<(&'static str, String)>> = Mutex::new(None);

/// Record that `error` has been shown to the operator.
pub fn mark_error_reported(error: &OlError) {
    *REPORTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner) =
        Some((error.code, error.message.clone()));
}

/// Whether this exact error (code and message) was already shown. `main` asks
/// before printing the error a command returned.
pub fn error_reported(error: &OlError) -> bool {
    REPORTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .as_ref()
        .is_some_and(|(code, message)| *code == error.code && *message == error.message)
}

/// Draw backtick-marked spans (`` `openlatch doctor` ``) in the accent colour,
/// URLs underlined too, dropping the backticks. With colour off the backticks
/// are simply removed.
pub fn style(text: &str, color_on: bool) -> String {
    style_over(text, color_on, |t, _| t.to_string())
}

/// [`style`], drawing the text between the marked spans with `base` (the card
/// footer's dim words around its commands).
pub fn style_over(text: &str, color_on: bool, base: fn(&str, bool) -> String) -> String {
    let mut out = String::with_capacity(text.len());
    for (i, part) in text.split('`').enumerate() {
        if i % 2 == 1 && !part.is_empty() {
            if part.starts_with("http://") || part.starts_with("https://") {
                out.push_str(&paint::link(part, color_on));
            } else {
                out.push_str(&paint::accent(part, color_on));
            }
        } else {
            out.push_str(&base(part, color_on));
        }
    }
    out
}

/// Swap the Unicode punctuation callers write (`·`, `…`, `—`, `→`) and the
/// meter's bar (`━`, `─`) for the ASCII set when the rail draws ASCII, so a
/// legacy console or a log file never shows a stray non-ASCII byte.
pub fn fit_glyphs(text: &str, caps: &Caps) -> String {
    if caps.unicode {
        return text.to_string();
    }
    text.replace('·', "-")
        .replace('…', "...")
        .replace('—', "-")
        .replace('›', ">")
        .replace('→', "->")
        .replace('━', "#")
        .replace('─', "-")
}

/// Visible width of marked-up text (backticks are markup, not columns).
fn visible_width(text: &str) -> usize {
    console::measure_text_width(&text.replace('`', ""))
}

/// Word-wrap marked-up `text` to `width` visible columns. A word longer than
/// the width is split; a backtick span broken across lines is closed and
/// reopened so each line styles on its own.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut lines = Vec::new();
    let mut line = String::new();
    for word in text.split_whitespace() {
        for piece in split_long(word, width) {
            let need = if line.is_empty() {
                visible_width(&piece)
            } else {
                visible_width(&line) + 1 + visible_width(&piece)
            };
            if need > width && !line.is_empty() {
                lines.push(std::mem::take(&mut line));
            }
            if !line.is_empty() {
                line.push(' ');
            }
            line.push_str(&piece);
        }
    }
    if !line.is_empty() || lines.is_empty() {
        lines.push(line);
    }
    // Rebalance backtick spans that a line break cut in two.
    let mut open = false;
    for line in &mut lines {
        if open {
            line.insert(0, '`');
        }
        if line.matches('`').count() % 2 == 1 {
            line.push('`');
            open = true;
        } else {
            open = false;
        }
    }
    lines
}

/// Split a word wider than `width` into chunks of at most `width` columns.
fn split_long(word: &str, width: usize) -> Vec<String> {
    if visible_width(word) <= width {
        return vec![word.to_string()];
    }
    let mut out = Vec::new();
    let mut chunk = String::new();
    for ch in word.chars() {
        if ch != '`' && visible_width(&chunk) >= width {
            out.push(std::mem::take(&mut chunk));
        }
        chunk.push(ch);
    }
    if !chunk.is_empty() {
        out.push(chunk);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_style_marks_commands() {
        assert_eq!(
            style("run `openlatch init` now", false),
            "run openlatch init now"
        );
        assert_eq!(
            style("run `openlatch init`", true),
            "run \x1b[36mopenlatch init\x1b[0m"
        );
        assert_eq!(
            style("see `https://app.openlatch.ai`", true),
            "see \x1b[4;36mhttps://app.openlatch.ai\x1b[0m"
        );
        assert_eq!(
            style_over("Check `openlatch status`", true, paint::dim),
            "\x1b[90mCheck \x1b[0m\x1b[36mopenlatch status\x1b[0m"
        );
        assert_eq!(style("no marks", true), "no marks");
    }

    #[test]
    fn test_fit_glyphs() {
        let ascii = Caps::new(Mode::Append, false, false, 80);
        assert_eq!(
            fit_glyphs("━━━─── 50% · 0.5.7 → 0.5.8…", &ascii),
            "###--- 50% - 0.5.7 -> 0.5.8..."
        );
        let unicode = Caps::new(Mode::Live, false, false, 80);
        assert_eq!(fit_glyphs("━━━───", &unicode), "━━━───");
    }

    #[test]
    fn test_wrap() {
        assert_eq!(wrap("", 10), vec![""]);
        assert_eq!(wrap("one two three", 7), vec!["one two", "three"]);
        assert_eq!(wrap("abcdefghij", 4), vec!["abcd", "efgh", "ij"]);
        // Backticks do not count, and a span cut by a break is rebalanced.
        assert_eq!(
            wrap("run `openlatch system telemetry enable` later", 20),
            vec!["run `openlatch system`", "`telemetry enable`", "later"]
        );
        for line in wrap(&"lorem ipsum ".repeat(30), 50) {
            assert!(visible_width(&line) <= 50, "{line}");
        }
    }

    #[test]
    fn test_error_fingerprint() {
        let e = OlError::new("OL-9901", "fingerprint test");
        assert!(!error_reported(&e));
        mark_error_reported(&e);
        assert!(error_reported(&e));
        assert!(!error_reported(&OlError::new("OL-9901", "another message")));
        assert!(!error_reported(&OlError::new(
            "OL-9902",
            "fingerprint test"
        )));
    }

    #[test]
    fn test_guard_installs_and_uninstalls() {
        let _l = INSTALL_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (rail, screen) = Rail::buffer(Caps::new(Mode::Plain, false, false, 80), 2);
        {
            let _guard = install_rail(rail).expect("installs");
            assert!(is_active());
            let (second, _) = Rail::buffer(Caps::new(Mode::Plain, false, false, 80), 1);
            assert!(install_rail(second).is_none(), "one rail at a time");
            intro("Setting up");
            stage("Checking", "Checked");
            done("ok");
            assert!(fail(&OlError::new("OL-9903", "boom")));
            assert!(error_reported(&OlError::new("OL-9903", "boom")));
        }
        assert!(!is_active());
        assert!(caps().is_none());
        // Uninstalled: the free functions are no-ops again.
        note("not drawn");
        assert!(!fail(&OlError::new("OL-9904", "not drawn")));
        let lines = screen.lock().unwrap().clone();
        assert_eq!(
            lines,
            vec!["Setting up", "[1/2] Checked - ok", "x boom (OL-9903)"]
        );
    }
}