liminal-cli 0.3.31

The liminal command: serve the network, maintain its stores, or serve its discovery MCP over stdio
Documentation
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
use std::error::Error;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

type TestResult = Result<(), Box<dyn Error>>;

fn command() -> Command {
    let mut command = Command::new(env!("CARGO_BIN_EXE_liminal"));
    for (name, _) in std::env::vars_os() {
        if name.to_string_lossy().starts_with("LIMINAL_") {
            command.env_remove(name);
        }
    }
    command
}

fn check(path: &Path) -> Result<Output, std::io::Error> {
    command().arg("check").arg("--config").arg(path).output()
}

fn toml_string(path: &Path) -> String {
    let escaped = path
        .display()
        .to_string()
        .replace('\\', "\\\\")
        .replace('"', "\\\"");
    format!("\"{escaped}\"")
}

fn fixture(root: &Path) -> Result<PathBuf, Box<dyn Error>> {
    let store = root.join("store");
    std::fs::create_dir(&store)?;
    let config = root.join("liminal.toml");
    std::fs::write(
        &config,
        format!(
            r#"listen_address = "127.0.0.1:7600"
health_listen_address = "127.0.0.1:7601"
drain_timeout_ms = 0
channels = []
routing_rules = []
persistence_path = {store}
[auth]
token = "test-token"
[auth.lys]
issuer = "https://unreachable.invalid"
network_id = "network-a"
keys_path = "absent-issuer.json"
live = true
[auth.lys.machine]
identity_path = "absent-identity.key"
pass_path = "absent-machine.pass"
"#,
            store = toml_string(&store),
        ),
    )?;
    Ok(config)
}

fn snapshot(root: &Path) -> Result<Vec<(PathBuf, Vec<u8>)>, std::io::Error> {
    let mut entries = vec![(root.to_path_buf(), Vec::new())];
    for entry in std::fs::read_dir(root)? {
        let path = entry?.path();
        if path.is_dir() {
            entries.extend(snapshot(&path)?);
        } else {
            entries.push((path.clone(), std::fs::read(path)?));
        }
    }
    entries.sort();
    Ok(entries)
}

fn assert_valid(output: &Output, path: &Path) {
    assert_eq!(
        output.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        format!(
            "{}: configuration valid: mode gated, decisions enforce, agents none\n",
            path.display()
        )
    );
    assert!(output.stderr.is_empty());
}

#[test]
fn check_accepts_valid_config_without_serving_or_writing() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let before = snapshot(root.path())?;
    let output = check(&path)?;
    assert_valid(&output, &path);
    assert_eq!(snapshot(root.path())?, before);
    Ok(())
}

#[test]
fn check_reports_each_startup_refusal_on_its_own_line() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let text = std::fs::read_to_string(&path)?
        .replace("127.0.0.1:7600", "127.0.0.1:0")
        .replace("127.0.0.1:7601", "127.0.0.1:0");
    let text = text
        .lines()
        .filter(|line| !line.starts_with("persistence_path"))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(&path, text)?;
    let output = check(&path)?;
    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    let stderr = String::from_utf8(output.stderr)?;
    let expected = concat!(
        "configuration validation failed: listen_address: port must be non-zero\n",
        "health_listen_address: port must be non-zero\n",
        "health_listen_address: must differ from listen_address for probe isolation\n",
        "persistence_path: full services require an existing directory; set persistence_path or LIMINAL_PERSISTENCE_PATH; no store is opened\n",
    );
    assert_eq!(stderr, expected);
    let startup = command().arg("--config").arg(&path).output()?;
    assert_eq!(startup.status.code(), Some(1));
    assert_eq!(
        String::from_utf8(startup.stderr)?,
        format!("Error: {expected}")
    );
    Ok(())
}

#[test]
fn check_applies_environment_overrides_before_validation() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let output = command()
        .arg("check")
        .arg("--config")
        .arg(&path)
        .env("LIMINAL_LISTEN_ADDRESS", "127.0.0.1:0")
        .output()?;
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(
        String::from_utf8(output.stderr)?,
        "configuration validation failed: listen_address: port must be non-zero\n"
    );
    assert!(output.stdout.is_empty());
    Ok(())
}

#[test]
fn check_resolves_schemas_relative_to_the_configuration() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let text = std::fs::read_to_string(&path)?
        .replace("channels = []\n", "")
        .replace(
            "[auth]",
            "[[channels]]\nname = 'orders'\ndurable = true\nschema_ref = 'orders.json'\n[auth]",
        );
    std::fs::write(&path, text)?;
    std::fs::write(root.path().join("orders.json"), r#"{"type":"object"}"#)?;
    let elsewhere = tempfile::tempdir()?;
    let output = command()
        .arg("check")
        .arg("--config")
        .arg(&path)
        .current_dir(elsewhere.path())
        .output()?;
    assert_valid(&output, &path);
    std::fs::write(root.path().join("orders.json"), "not JSON")?;
    let output = check(&path)?;
    assert_eq!(output.status.code(), Some(2));
    assert!(String::from_utf8(output.stderr)?.contains("is not valid JSON"));
    Ok(())
}

#[test]
fn check_reports_missing_and_unreadable_files_with_the_os_error() -> TestResult {
    let root = tempfile::tempdir()?;
    for path in [root.path().join("missing.toml"), root.path().to_path_buf()] {
        let error = std::fs::read_to_string(&path)
            .err()
            .ok_or("file was readable")?;
        let output = check(&path)?;
        assert_eq!(output.status.code(), Some(2));
        assert!(output.stdout.is_empty());
        assert_eq!(
            String::from_utf8(output.stderr)?,
            format!(
                "configuration load failed: failed to read configuration file '{}': {error}\n",
                path.display()
            )
        );
    }
    Ok(())
}

#[test]
fn check_reports_malformed_toml_and_unknown_fields() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let valid = std::fs::read_to_string(&path)?;
    for text in [
        "[broken".to_owned(),
        format!("unknown_field = true\n{valid}"),
    ] {
        std::fs::write(&path, text)?;
        let error = liminal_server::config::load_from_file(&path)
            .err()
            .ok_or("malformed configuration loaded")?;
        let output = check(&path)?;
        assert_eq!(output.status.code(), Some(2));
        assert!(output.stdout.is_empty());
        let stderr = String::from_utf8(output.stderr)?;
        assert_eq!(stderr, format!("{error}\n"));
    }
    Ok(())
}

#[test]
fn check_requires_a_configuration_path() -> TestResult {
    let output = command().arg("check").output()?;
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr)?;
    assert!(stderr.contains("--config <CONFIG> is required"), "{stderr}");
    assert!(
        stderr.contains("liminal check --config <CONFIG>"),
        "{stderr}"
    );
    let output = check(Path::new(""))?;
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(
        String::from_utf8(output.stderr)?,
        "configuration load failed: configuration path is empty\n"
    );
    Ok(())
}

#[test]
fn check_is_documented_in_both_help_pages() -> TestResult {
    for arguments in [vec!["--help"], vec!["check", "--help"]] {
        let output = command().args(arguments).output()?;
        assert_eq!(output.status.code(), Some(0));
        let stdout = String::from_utf8(output.stdout)?;
        assert!(
            stdout.contains("Validate the server configuration without serving"),
            "{stdout}"
        );
        assert!(stdout.contains("--config <CONFIG>"), "{stdout}");
    }
    Ok(())
}

#[test]
fn check_validates_extra_listen_addresses_without_serving_or_writing() -> TestResult {
    let root = tempfile::tempdir()?;
    let path = fixture(root.path())?;
    let original = std::fs::read_to_string(&path)?;
    std::fs::write(
        &path,
        format!("extra_listen_addresses = ['100.64.0.1:7600']\n{original}"),
    )?;
    let before = snapshot(root.path())?;
    assert_valid(&check(&path)?, &path);
    assert_eq!(snapshot(root.path())?, before);
    std::fs::write(
        &path,
        format!("extra_listen_addresses = ['0.0.0.0:7600']\n{original}"),
    )?;
    let before = snapshot(root.path())?;
    let output = check(&path)?;
    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    let error = String::from_utf8(output.stderr)?;
    assert!(
        error.contains("extra_listen_addresses[0] (0.0.0.0:7600)"),
        "{error}"
    );
    assert!(
        error.contains("unspecified addresses are refused"),
        "{error}"
    );
    assert_eq!(snapshot(root.path())?, before);
    Ok(())
}

/// `cargo install liminal-cli` builds only `liminal`: every other binary
/// target needs `test-support`, which no default feature turns on (Apollo item 3).
#[test]
fn an_install_builds_only_the_liminal_binary() -> TestResult {
    let manifest: toml::Table = include_str!("../Cargo.toml").parse()?;
    let bins = manifest
        .get("bin")
        .and_then(toml::Value::as_array)
        .ok_or("Cargo.toml declares no [[bin]] targets")?;
    let mut installed = Vec::new();
    for bin in bins {
        let name = bin
            .get("name")
            .and_then(toml::Value::as_str)
            .ok_or("a [[bin]] has no name")?;
        let gated = bin
            .get("required-features")
            .and_then(toml::Value::as_array)
            .is_some_and(|features| features.iter().any(|f| f.as_str() == Some("test-support")));
        if !gated {
            installed.push(name);
        }
    }
    assert_eq!(installed, ["liminal"]);
    let defaults = manifest
        .get("features")
        .and_then(|features| features.get("default"))
        .and_then(toml::Value::as_array);
    assert!(
        defaults.is_none_or(|features| features.iter().all(|f| f.as_str() != Some("test-support"))),
        "test-support is a default feature"
    );
    Ok(())
}

/// The docs site's ticket seat example loads as written through the ticket
/// loader; the hosted agent's is loaded by the seat loader's own tests.
#[test]
fn the_published_seat_example_loads() -> TestResult {
    let examples: serde_json::Value =
        serde_json::from_str(include_str!("../../../docs/site/_data/examples.json"))?;
    let code = examples["seat-config"]["code"]
        .as_str()
        .ok_or("examples.json has no seat-config")?;
    let dir = tempfile::tempdir()?;
    let ticket = dir.path().join("seat.toml");
    std::fs::write(&ticket, code)?;
    liminal_cli::config::Config::load(&ticket)?;
    Ok(())
}

/// ACCESS-011 R3: the valid line names the mode and, for open, its reach,
/// and, for a Lys exchange, its decisions; ACCESS-013 R3: and where its agent
/// registry is written (`top`, `auth.lys` or `none`).
#[test]
fn access011_check_names_the_mode_its_reach_and_its_decisions() -> TestResult {
    let root = tempfile::tempdir()?;
    let store = root.path().join("store");
    std::fs::create_dir(&store)?;
    let base = format!(
        "health_listen_address = \"127.0.0.1:7601\"\ndrain_timeout_ms = 0\nchannels = []\n\
         routing_rules = []\npersistence_path = {}\n",
        toml_string(&store)
    );
    let shapes = [
        (
            "open-loopback.toml",
            format!("listen_address = \"127.0.0.1:7600\"\n{base}"),
            "mode open, reach loopback, agents none",
        ),
        (
            "open-network.toml",
            format!("listen_address = \"0.0.0.0:7600\"\n{base}[open]\nreach = \"network\"\n"),
            "mode open, reach network, agents none",
        ),
        (
            "lys-advise.toml",
            format!(
                "listen_address = \"127.0.0.1:7600\"\n{base}[auth]\ntoken = \"test-token\"\n\
                 [auth.lys]\nissuer = \"https://unreachable.invalid\"\nnetwork_id = \"network-a\"\n\
                 keys_path = \"absent-issuer.json\"\ndecisions = \"advise\"\n"
            ),
            "mode gated, decisions advise, agents none",
        ),
        (
            "open-agents.toml",
            format!(
                "listen_address = \"127.0.0.1:7600\"\n{base}[agents]\n[limits]\nmax_channels = 64\n"
            ),
            "mode open, reach loopback, agents top",
        ),
        (
            "lys-agents.toml",
            format!(
                "listen_address = \"127.0.0.1:7600\"\n{base}[limits]\nmax_channels = 64\n[auth]\n\
                 token = \"test-token\"\n[auth.lys]\nissuer = \"https://unreachable.invalid\"\n\
                 network_id = \"network-a\"\nkeys_path = \"absent-issuer.json\"\n[auth.lys.agents]\n"
            ),
            "mode gated, decisions enforce, agents auth.lys",
        ),
    ];
    for (name, text, words) in shapes {
        let path = root.path().join(name);
        std::fs::write(&path, text)?;
        let output = check(&path)?;
        assert_eq!(
            output.status.code(),
            Some(0),
            "{name}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            format!("{}: configuration valid: {words}\n", path.display()),
            "{name}"
        );
    }
    Ok(())
}