omgbase 0.7.0

omgbase: a versioned, addressable graph layer over authored Markdown — the `omgbase` binary (`omgbase mcp` serves the tool catalog over MCP stdio, with the filesystem watcher and the background embed drain)
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
//! The output contract (`spec/cli` §3): stdout is data, stderr is everything
//! else; the exit codes 0 / 1 / 2; the two error renderings (`usage: …` and
//! `error[<code>]: …` with the pretty payload, or the machine-mode JSON
//! object on stderr); JSON printed exactly as `JSON.stringify` prints it;
//! the truncation footer; the query hit table (§4).

use std::io::{IsTerminal, Write};

use omgbase_surface::SurfaceError;
use serde_json::Value as Json;

use super::render::{Style, columns, visible_width};

pub const EXIT_OK: i32 = 0;
pub const EXIT_ERROR: i32 = 1;
pub const EXIT_USAGE: i32 = 2;

/// Every failure a verb reports.
#[derive(Clone, Debug, PartialEq)]
pub enum CliError {
    /// A CLI-level mistake → `usage: <message>`, exit 2.
    Usage {
        message: String,
        hint: Option<String>,
    },
    /// An engine's typed error (or anything else) → `error[<code>]:
    /// <message>` with its payload, exit 1.
    Engine {
        code: String,
        message: String,
        hint: Option<String>,
        data: Option<Json>,
    },
}

impl CliError {
    pub fn usage(message: impl Into<String>) -> Self {
        Self::Usage {
            message: message.into(),
            hint: None,
        }
    }
    pub fn usage_hint(message: impl Into<String>, hint: impl Into<String>) -> Self {
        Self::Usage {
            message: message.into(),
            hint: Some(hint.into()),
        }
    }
    pub fn engine(code: &str, message: impl Into<String>) -> Self {
        Self::Engine {
            code: code.to_owned(),
            message: message.into(),
            hint: None,
            data: None,
        }
    }
    pub fn engine_hint(code: &str, message: impl Into<String>, hint: impl Into<String>) -> Self {
        Self::Engine {
            code: code.to_owned(),
            message: message.into(),
            hint: Some(hint.into()),
            data: None,
        }
    }
    pub fn engine_data(code: &str, message: impl Into<String>, data: Json) -> Self {
        Self::Engine {
            code: code.to_owned(),
            message: message.into(),
            hint: None,
            data: Some(data),
        }
    }
    pub fn message(&self) -> &str {
        match self {
            Self::Usage { message, .. } | Self::Engine { message, .. } => message,
        }
    }
}

impl From<SurfaceError> for CliError {
    fn from(e: SurfaceError) -> Self {
        Self::Engine {
            code: e.code,
            message: e.message,
            hint: None,
            data: e.data,
        }
    }
}

impl From<omgbase_sync::Error> for CliError {
    fn from(e: omgbase_sync::Error) -> Self {
        Self::from(SurfaceError::from(e))
    }
}

impl From<omgbase_store::Error> for CliError {
    fn from(e: omgbase_store::Error) -> Self {
        Self::from(SurfaceError::from(e))
    }
}

impl From<rusqlite::Error> for CliError {
    fn from(e: rusqlite::Error) -> Self {
        Self::from(SurfaceError::from(e))
    }
}

impl From<std::io::Error> for CliError {
    fn from(e: std::io::Error) -> Self {
        Self::engine("error", e.to_string())
    }
}

pub type Result<T> = std::result::Result<T, CliError>;

// ---- IO -----------------------------------------------------------------------------------

/// stdout is data; stderr is everything else (§3.1). Every line ends in
/// `\n`. A closed pipe downstream is not an error (`omg … | head`).
#[derive(Clone, Copy, Debug, Default)]
pub struct Io;

/// The shell's quiet mode (§7 `@name = <command>`): data is dropped while a
/// command runs for its typed result only; diagnostics still reach stderr.
static STDOUT_MUTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

impl Io {
    /// Drop (or restore) everything written through [`Io::out`].
    pub fn mute_stdout(muted: bool) {
        STDOUT_MUTED.store(muted, std::sync::atomic::Ordering::SeqCst);
    }

    pub fn out(&self, s: &str) {
        if STDOUT_MUTED.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        let mut h = std::io::stdout().lock();
        let _ = h.write_all(s.as_bytes());
        if !s.ends_with('\n') {
            let _ = h.write_all(b"\n");
        }
        let _ = h.flush();
    }
    pub fn err(&self, s: &str) {
        let mut h = std::io::stderr().lock();
        let _ = h.write_all(s.as_bytes());
        if !s.ends_with('\n') {
            let _ = h.write_all(b"\n");
        }
        let _ = h.flush();
    }
    pub fn stdout_tty(&self) -> bool {
        std::io::stdout().is_terminal()
    }
    pub fn stdin_tty(&self) -> bool {
        std::io::stdin().is_terminal()
    }
}

// ---- JSON as JavaScript prints it ---------------------------------------------------------

/// `JSON.stringify(s)`: the string escaping is `serde_json`'s (the same set
/// of escapes — `"`, `\`, the C0 controls with their short forms).
pub fn js_string(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned())
}

/// A number as `String(n)` prints it: integral doubles without a fraction,
/// exponents past 1e21 / under 1e-6 in JavaScript's spelling.
fn js_number(n: &serde_json::Number) -> String {
    if let Some(i) = n.as_i64() {
        return i.to_string();
    }
    if let Some(u) = n.as_u64() {
        return u.to_string();
    }
    let f = n.as_f64().unwrap_or(0.0);
    if !f.is_finite() {
        return "null".to_owned();
    }
    if f == 0.0 {
        return "0".to_owned();
    }
    let abs = f.abs();
    if !(1e-6..1e21).contains(&abs) {
        // `1.5e21` → `1.5e+21`; `1e-7` stays.
        let s = format!("{f:e}");
        return match s.split_once('e') {
            Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
            _ => s,
        };
    }
    if f.fract() == 0.0 {
        return format!("{f:.0}");
    }
    // Rust's shortest round-trip repr equals JavaScript's in this range.
    f.to_string()
}

fn write_compact(v: &Json, out: &mut String) {
    match v {
        Json::Null => out.push_str("null"),
        Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Json::Number(n) => out.push_str(&js_number(n)),
        Json::String(s) => out.push_str(&js_string(s)),
        Json::Array(a) => {
            out.push('[');
            for (i, x) in a.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_compact(x, out);
            }
            out.push(']');
        }
        Json::Object(m) => {
            out.push('{');
            for (i, (k, x)) in m.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&js_string(k));
                out.push(':');
                write_compact(x, out);
            }
            out.push('}');
        }
    }
}

fn write_pretty(v: &Json, out: &mut String, depth: usize) {
    let pad = |d: usize| "  ".repeat(d);
    match v {
        Json::Array(a) if !a.is_empty() => {
            out.push_str("[\n");
            for (i, x) in a.iter().enumerate() {
                if i > 0 {
                    out.push_str(",\n");
                }
                out.push_str(&pad(depth + 1));
                write_pretty(x, out, depth + 1);
            }
            out.push('\n');
            out.push_str(&pad(depth));
            out.push(']');
        }
        Json::Object(m) if !m.is_empty() => {
            out.push_str("{\n");
            for (i, (k, x)) in m.iter().enumerate() {
                if i > 0 {
                    out.push_str(",\n");
                }
                out.push_str(&pad(depth + 1));
                out.push_str(&js_string(k));
                out.push_str(": ");
                write_pretty(x, out, depth + 1);
            }
            out.push('\n');
            out.push_str(&pad(depth));
            out.push('}');
        }
        other => write_compact(other, out),
    }
}

/// `JSON.stringify(v)`.
pub fn js_json(v: &Json) -> String {
    let mut s = String::new();
    write_compact(v, &mut s);
    s
}

/// `JSON.stringify(v, null, 2)`.
pub fn js_json_pretty(v: &Json) -> String {
    let mut s = String::new();
    write_pretty(v, &mut s, 0);
    s
}

// ---- errors (§3.5) ------------------------------------------------------------------------

/// Render `err` to stderr and return the exit code. `machine` selects the
/// JSON object (`hint` kept, §9 Fixed); else the human form with the
/// payload pretty-printed under the message (an empty payload prints
/// nothing, §9 Fixed).
pub fn render_error(err: &CliError, io: Io, style: &Style, machine: bool) -> i32 {
    match err {
        CliError::Usage { message, hint } => {
            if machine {
                let mut m = serde_json::Map::new();
                m.insert("error".into(), Json::String("usage".into()));
                m.insert("message".into(), Json::String(message.clone()));
                if let Some(h) = hint {
                    m.insert("hint".into(), Json::String(h.clone()));
                }
                m.insert("retriable".into(), Json::Bool(false));
                io.err(&js_json(&Json::Object(m)));
            } else {
                io.err(&format!("{}: {message}", style.err("usage")));
                if let Some(h) = hint {
                    io.err(&style.dim(&format!("  hint: {h}")));
                }
            }
            EXIT_USAGE
        }
        CliError::Engine {
            code,
            message,
            hint,
            data,
        } => {
            if machine {
                let mut m = serde_json::Map::new();
                m.insert("error".into(), Json::String(code.clone()));
                m.insert("message".into(), Json::String(message.clone()));
                if let Some(h) = hint {
                    m.insert("hint".into(), Json::String(h.clone()));
                }
                if let Some(d) = data.as_ref().filter(|d| !payload_is_empty(d)) {
                    m.insert("data".into(), d.clone());
                }
                m.insert("retriable".into(), Json::Bool(false));
                io.err(&js_json(&Json::Object(m)));
                return EXIT_ERROR;
            }
            io.err(&format!(
                "{}: {message}",
                style.err(&format!("error[{code}]"))
            ));
            if let Some(h) = hint {
                io.err(&style.dim(&format!("  hint: {h}")));
            }
            if let Some(d) = data {
                if !payload_is_empty(d) {
                    let text = js_json_pretty(d)
                        .split('\n')
                        .map(|l| format!("  {l}"))
                        .collect::<Vec<_>>()
                        .join("\n");
                    io.err(&style.dim(&text));
                }
            }
            EXIT_ERROR
        }
    }
}

/// §9 Fixed: an empty payload (`{}`, `[]`, `null`) prints nothing under the
/// message and is omitted from the JSON error.
fn payload_is_empty(d: &Json) -> bool {
    d.is_null()
        || d.as_object().is_some_and(|m| m.is_empty())
        || d.as_array().is_some_and(|a| a.is_empty())
}

/// §3.4: the footer, on stderr, exit 0.
pub fn truncation_footer(io: Io, style: &Style, cursor: &str) {
    io.err(&style.dim(&format!("… truncated; continue with --cursor {cursor}")));
}

// ---- the query hit table (§4) -------------------------------------------------------------

pub const HIT_CELL_MAX: usize = 60;

/// Clip to `max` visible characters, the last one `…`.
pub fn truncate_cell(s: &str, max: usize) -> String {
    if visible_width(s) <= max {
        return s.to_owned();
    }
    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
    out.push('…');
    out
}

/// One projected value as a cell: strings verbatim to their first newline
/// (`…` marks a cut), numbers and booleans as JavaScript prints them,
/// null/absent empty, lists and records as compact JSON; clipped.
pub fn hit_cell(v: Option<&Json>) -> String {
    match v {
        None | Some(Json::Null) => String::new(),
        Some(Json::String(s)) => match s.find('\n') {
            None => truncate_cell(s, HIT_CELL_MAX),
            Some(nl) => truncate_cell(&format!("{}…", &s[..nl]), HIT_CELL_MAX),
        },
        Some(Json::Bool(b)) => b.to_string(),
        Some(Json::Number(n)) => js_number(n),
        Some(other) => truncate_cell(&js_json(other), HIT_CELL_MAX),
    }
}

/// The projected keys: `projected` (the query's `select` names, in order),
/// then every other key of `hits` but `id`/`path`, first-seen order.
pub fn hit_columns(hits: &[Json], projected: &[String]) -> Vec<String> {
    let mut cols: Vec<String> = Vec::new();
    for k in projected {
        if k != "id" && k != "path" && !cols.iter().any(|c| c == k) {
            cols.push(k.clone());
        }
    }
    for h in hits {
        if let Some(m) = h.as_object() {
            for k in m.keys() {
                if k != "id" && k != "path" && !cols.iter().any(|c| c == k) {
                    cols.push(k.clone());
                }
            }
        }
    }
    cols
}

/// Human-tier hit list: `<id>  <path>` lines, or an aligned table when projected.
pub fn render_hits(io: Io, style: &Style, hits: &[Json], projected: &[String]) {
    let str_of = |h: &Json, k: &str| -> String {
        h.get(k)
            .and_then(Json::as_str)
            .map(str::to_owned)
            .unwrap_or_default()
    };
    let projected = hit_columns(hits, projected);
    if projected.is_empty() {
        for h in hits {
            let line = format!(
                "{}  {}",
                style.id(&str_of(h, "id")),
                style.accent(&str_of(h, "path"))
            );
            io.out(line.trim_end());
        }
        return;
    }
    let mut cols: Vec<String> = vec!["id".to_owned()];
    if !projected.iter().any(|c| c == "$path") {
        cols.push("path".to_owned());
    }
    cols.extend(projected);
    let mut rows: Vec<Vec<String>> = vec![cols.iter().map(|c| style.dim(c)).collect()];
    for h in hits {
        rows.push(
            cols.iter()
                .map(|c| match c.as_str() {
                    "id" => style.id(&str_of(h, "id")),
                    "path" => style.accent(&str_of(h, "path")),
                    "$path" if h.get("$path").is_some_and(Json::is_string) => {
                        style.accent(&str_of(h, "$path"))
                    }
                    other => hit_cell(h.get(other)),
                })
                .collect(),
        );
    }
    for line in columns(&rows, &[]) {
        io.out(&line);
    }
}

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

    #[test]
    fn json_like_javascript() {
        let v = json!({ "a": 1.0, "b": 0.016129032258064516, "c": [], "d": {}, "e": "x\ny", "f": 1677, "g": true, "h": null });
        assert_eq!(
            js_json(&v),
            r#"{"a":1,"b":0.016129032258064516,"c":[],"d":{},"e":"x\ny","f":1677,"g":true,"h":null}"#
        );
        assert_eq!(js_json(&json!(1.5e21)), "1.5e+21");
        assert_eq!(js_json(&json!(1e-7)), "1e-7");
        assert_eq!(js_json(&json!(-2.5)), "-2.5");
        assert_eq!(
            js_json_pretty(&json!({ "candidates": ["fixture"], "e": {} })),
            "{\n  \"candidates\": [\n    \"fixture\"\n  ],\n  \"e\": {}\n}"
        );
    }

    #[test]
    fn cells() {
        assert_eq!(hit_cell(Some(&json!("a\nb"))), "a…");
        assert_eq!(hit_cell(Some(&json!(false))), "false");
        assert_eq!(hit_cell(Some(&json!([1, 2]))), "[1,2]");
        assert_eq!(hit_cell(None), "");
        let long = "x".repeat(70);
        let c = hit_cell(Some(&json!(long)));
        assert_eq!(c.chars().count(), 60);
        assert!(c.ends_with('…'));
        assert_eq!(
            hit_columns(
                &[
                    json!({ "id": "a", "path": "p", "x": 1 }),
                    json!({ "id": "b", "y": 2 })
                ],
                &[]
            ),
            vec!["x", "y"]
        );
        assert_eq!(
            hit_columns(
                &[json!({ "id": "a", "path": "p", "x": 1 })],
                &["x".into(), "nope".into()]
            ),
            vec!["x", "nope"]
        );
    }
}