relay-knowledge 1.1.14

Graph-database-based knowledge graph project.
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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

use relay_knowledge::{
    PROJECT_NAME,
    env::{
        ALL_PROXY, ALL_PROXY_LOWER, HTTP_PROXY, HTTP_PROXY_LOWER, HTTPS_PROXY, HTTPS_PROXY_LOWER,
        NO_PROXY, NO_PROXY_LOWER, RELAY_KNOWLEDGE_CACHE_DIR, RELAY_KNOWLEDGE_CONFIG_DIR,
        RELAY_KNOWLEDGE_DATA_DIR, RELAY_KNOWLEDGE_HOME, RELAY_KNOWLEDGE_HTTP_BIND,
        RELAY_KNOWLEDGE_HTTP_MAX_BODY_BYTES, RELAY_KNOWLEDGE_HTTP_REQUEST_TIMEOUT_MS,
        RELAY_KNOWLEDGE_HTTP_SHUTDOWN_TIMEOUT_MS, RELAY_KNOWLEDGE_LOG_DIR,
        RELAY_KNOWLEDGE_MCP_ALLOW_REMOTE_CLIENTS, RELAY_KNOWLEDGE_MCP_ALLOW_UNSPECIFIED_SCOPE,
        RELAY_KNOWLEDGE_MCP_ALLOWED_ORIGINS, RELAY_KNOWLEDGE_MCP_ALLOWED_SCOPES,
        RELAY_KNOWLEDGE_MCP_ENDPOINT, RELAY_KNOWLEDGE_MCP_MAX_CONTEXT_BYTES,
        RELAY_KNOWLEDGE_MCP_MAX_LIMIT, RELAY_KNOWLEDGE_MCP_STREAMABLE_HTTP_ENABLED,
        RELAY_KNOWLEDGE_QOS_MAX_CONNECTIONS, RELAY_KNOWLEDGE_QOS_MAX_IN_FLIGHT_REQUESTS,
        RELAY_KNOWLEDGE_QOS_MAX_QUEUE_DEPTH, RELAY_KNOWLEDGE_RUNTIME_DIR,
        RELAY_KNOWLEDGE_SERVICE_DIR, RELAY_KNOWLEDGE_STATE_DIR, RELAY_KNOWLEDGE_TEMP_DIR,
        SSL_VERIFY, SSL_VERIFY_LOWER,
    },
    interfaces::cli::{CliAction, CliCommand, OutputFormat},
};
use serde_json::Value;

#[test]
fn parses_cli_output_formats() {
    let text = CliCommand::parse(["--format", "text"]).expect("text format should parse");
    let json = CliCommand::parse(["--format=json"]).expect("json format should parse");
    let streaming_json = CliCommand::parse(["--format", "streaming-json"])
        .expect("streaming-json format should parse");

    assert_eq!(text.format, OutputFormat::Text);
    assert_eq!(json.format, OutputFormat::Json);
    assert_eq!(streaming_json.format, OutputFormat::StreamingJson);
    assert_eq!(text.action, CliAction::Status);
}

#[test]
fn rejects_unknown_cli_output_format() {
    let error = CliCommand::parse(["--format", "xml"]).expect_err("format should be rejected");

    assert_eq!(error.exit_code(), 2);
    assert_eq!(
        error.to_string(),
        "invalid --format value 'xml', expected text, json, markdown, or streaming-json"
    );
}

#[test]
fn binary_outputs_text_by_default() {
    let output = relay_command().output().expect("binary should run");

    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout), "relay-knowledge\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn binary_outputs_single_json_object() {
    let output = relay_command()
        .args(["--format", "json"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("stdout should be JSON");

    assert_eq!(value["project_name"], "relay-knowledge");
    assert_eq!(value["metadata"]["graph_version"], 0);
    assert_eq!(value["metadata"]["stale"], false);
    assert_eq!(value["runtime"]["storage_topology"], "single_sqlite");
    assert_eq!(value["runtime"]["http_bind"], "127.0.0.1:8791");
    assert_eq!(value["runtime"]["http_proxy_configured"], false);
    assert_eq!(value["runtime"]["http_no_proxy_rules"], 0);
    assert_eq!(value["runtime"]["http_ssl_verify"], true);
    assert_eq!(value["runtime"]["qos_max_connections"], 1024);
    assert!(value["metadata"]["trace_id"].as_str().is_some());
    assert!(value["metadata"]["request_id"].as_str().is_some());
}

#[test]
fn binary_outputs_streaming_json_as_ndjson_events() {
    let output = relay_command()
        .args(["--format=streaming-json"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let stdout = String::from_utf8(output.stdout).expect("stdout should be UTF-8");
    let lines = stdout.lines().collect::<Vec<_>>();

    assert_eq!(lines.len(), 4);

    let events = lines
        .iter()
        .map(|line| serde_json::from_str::<Value>(line).expect("line should be JSON"))
        .collect::<Vec<_>>();

    assert_eq!(events[0]["event"], "started");
    assert_eq!(events[1]["event"], "progress");
    assert_eq!(events[2]["event"], "item");
    assert_eq!(events[2]["project_name"], "relay-knowledge");
    assert_eq!(events[2]["runtime"]["storage_topology"], "single_sqlite");
    assert_eq!(events[2]["runtime"]["http_bind"], "127.0.0.1:8791");
    assert!(events[2]["payload"].is_null());
    assert_eq!(events[3]["event"], "completed");

    for event in events {
        assert_eq!(event["operation"], "project.status");
        assert_eq!(event["metadata"]["graph_version"], 0);
    }
}

#[test]
fn binary_outputs_version_without_runtime_configuration() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["version"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        format!("relay-knowledge {}\n", env!("CARGO_PKG_VERSION"))
    );
    assert!(output.stderr.is_empty());
}

#[test]
fn binary_outputs_version_json_from_flag_alias() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["--version", "--format", "json"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("version JSON");

    assert_eq!(value["project_name"], "relay-knowledge");
    assert_eq!(value["version"], env!("CARGO_PKG_VERSION"));
}

#[test]
fn binary_outputs_root_help_without_runtime_configuration() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["--help"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(stdout.contains("Usage: relay-knowledge <command>"));
    assert!(stdout.contains("help"));
    assert!(stdout.contains("machine-readable parameter metadata"));
}

#[test]
fn binary_outputs_command_help_text() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["repo", "query", "core", "--help"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(stdout.contains("Usage: relay-knowledge repo query"));
    assert!(stdout.contains("--kind"));
    assert!(stdout.contains("definition"));
}

#[test]
fn binary_outputs_namespace_help_text() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["repo", "--help"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(stdout.contains("Usage: relay-knowledge repo <subcommand>"));
    assert!(stdout.contains("repo query"));
    assert!(stdout.contains("repo index"));
}

#[test]
fn binary_outputs_machine_readable_help() {
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["help", "repo", "query", "--format", "json"])
        .output()
        .expect("binary should run");
    let software = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, "")
        .args(["help", "repo", "software", "--format", "json"])
        .output()
        .expect("binary should run");

    assert!(output.status.success());
    assert!(software.status.success());
    assert!(output.stderr.is_empty());
    assert!(software.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("help JSON");
    let software_value: Value =
        serde_json::from_slice(&software.stdout).expect("software help JSON");

    assert_eq!(value["schema_version"], 2);
    assert_eq!(value["path"], serde_json::json!(["repo", "query"]));
    assert_eq!(value["operation"], "code.repo.query");
    assert_eq!(value["effect"], "read-only");
    assert_eq!(value["syntax"]["kind"], "command");
    assert!(
        value["options"]
            .as_array()
            .expect("options")
            .iter()
            .any(|option| option["flag"] == "--kind"
                && option["allowed_values"]
                    .as_array()
                    .expect("values")
                    .iter()
                    .any(|value| value == "definition"))
    );
    assert!(
        software_value["options"]
            .as_array()
            .expect("software options")
            .iter()
            .any(|option| option["flag"] == "--kind"
                && option["allowed_values"]
                    == serde_json::json!([
                        "dependencies",
                        "sdks",
                        "files",
                        "topics",
                        "relationships",
                        "build",
                        "iac",
                        "design",
                        "all"
                    ]))
    );
}

#[test]
fn binary_help_metadata_uses_canonical_cli_name() {
    let root = relay_command()
        .args(["help", "--format", "json"])
        .output()
        .expect("binary should run");
    let repo = relay_command()
        .args(["help", "repo", "--format", "json"])
        .output()
        .expect("binary should run");
    let repo_query = relay_command()
        .args(["help", "repo", "query", "--format", "json"])
        .output()
        .expect("binary should run");

    assert!(root.status.success());
    assert!(repo.status.success());
    assert!(repo_query.status.success());

    let root_json: Value = serde_json::from_slice(&root.stdout).expect("root help JSON");
    let repo_json: Value = serde_json::from_slice(&repo.stdout).expect("repo help JSON");
    let repo_query_json: Value =
        serde_json::from_slice(&repo_query.stdout).expect("repo query help JSON");

    assert_eq!(root_json["binary"], PROJECT_NAME);
    assert_eq!(repo_json["binary"], PROJECT_NAME);
    assert_eq!(repo_query_json["binary"], PROJECT_NAME);
    assert_eq!(repo_json["kind"], "namespace");

    for command in root_json["commands"].as_array().expect("root commands") {
        assert_command_metadata_uses_project_name(command);
    }
    for command in repo_json["commands"].as_array().expect("repo commands") {
        assert_command_metadata_uses_project_name(command);
    }
    assert_command_metadata_uses_project_name(&repo_query_json);
}

#[test]
fn binary_rejects_streaming_json_version_format() {
    let output = relay_command()
        .args(["version", "--format", "streaming-json"])
        .output()
        .expect("binary should run");

    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    assert_eq!(
        String::from_utf8_lossy(&output.stderr).trim(),
        "version does not support --format streaming-json"
    );
}

#[test]
fn binary_ingests_queries_and_inspects_isolated_graph() {
    let home = isolated_home("binary-ingests-queries");
    let ingest = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args([
            "ingest",
            "--source",
            "docs",
            "--content",
            "Rust async services isolate blocking SQLite work",
            "--entity",
            "Rust",
            "--format",
            "json",
        ])
        .output()
        .expect("ingest command should run");

    assert!(ingest.status.success());
    assert!(ingest.stderr.is_empty());
    let ingest_json: Value = serde_json::from_slice(&ingest.stdout).expect("ingest JSON");
    assert_eq!(ingest_json["metadata"]["graph_version"], 1);
    assert_eq!(ingest_json["receipt"]["evidence_count"], 1);
    assert_eq!(ingest_json["indexes"].as_array().expect("indexes").len(), 3);

    let query = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args([
            "query",
            "SQLite",
            "--source",
            "docs",
            "--freshness",
            "wait-until-fresh",
            "--format",
            "json",
        ])
        .output()
        .expect("query command should run");

    assert!(query.status.success());
    assert!(query.stderr.is_empty());
    let query_json: Value = serde_json::from_slice(&query.stdout).expect("query JSON");
    assert_eq!(query_json["metadata"]["graph_version"], 1);
    assert_eq!(query_json["metadata"]["stale"], false);
    assert_eq!(query_json["results"].as_array().expect("results").len(), 1);

    let inspect = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args(["graph", "inspect", "--format", "json"])
        .output()
        .expect("inspect command should run");

    assert!(inspect.status.success());
    let inspect_json: Value = serde_json::from_slice(&inspect.stdout).expect("inspect JSON");
    assert_eq!(inspect_json["graph"]["entity_count"], 1);
    assert_eq!(inspect_json["graph"]["evidence_count"], 1);
}

#[test]
fn binary_queries_dash_prefixed_text_after_delimiter() {
    let output = relay_command()
        .args(["--format", "json", "query", "--", "--help"])
        .output()
        .expect("query command should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("query JSON");

    assert_eq!(value["metadata"]["graph_version"], 0);
    assert_eq!(value["results"].as_array().expect("results").len(), 0);
}

#[test]
fn binary_queries_dash_prefixed_text_with_trailing_global_format() {
    let output = relay_command()
        .args(["query", "--", "--help", "--format", "json"])
        .output()
        .expect("query command should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("query JSON");

    assert_eq!(value["metadata"]["graph_version"], 0);
    assert_eq!(value["results"].as_array().expect("results").len(), 0);
}

#[test]
fn binary_ingests_dash_prefixed_content_value() {
    let home = isolated_home("binary-ingests-dash-prefixed-content");
    let output = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args([
            "ingest",
            "--source",
            "docs",
            "--content",
            "--version",
            "--format",
            "json",
        ])
        .output()
        .expect("ingest command should run");

    assert!(output.status.success());
    assert!(output.stderr.is_empty());

    let value: Value = serde_json::from_slice(&output.stdout).expect("ingest JSON");

    assert_eq!(value["metadata"]["graph_version"], 1);
    assert_eq!(value["receipt"]["evidence_count"], 1);
}

#[test]
fn binary_reports_health_and_service_status() {
    let home = isolated_home("binary-health-service");

    let health = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args(["health", "--format", "json"])
        .output()
        .expect("health command should run");

    assert!(health.status.success());
    let health_json: Value = serde_json::from_slice(&health.stdout).expect("health JSON");
    assert_eq!(health_json["healthy"], true);
    assert_eq!(health_json["graph"]["graph_version"], 0);

    let service = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args(["service", "doctor", "--format", "json"])
        .output()
        .expect("service command should run");

    assert!(service.status.success());
    let service_json: Value = serde_json::from_slice(&service.stdout).expect("service JSON");
    assert_eq!(service_json["service_name"], "relay-knowledge");
    assert_eq!(service_json["mode"], "disabled");
}

#[test]
fn binary_reports_setup_doctor_and_profiles() {
    let home = isolated_home("binary-setup");

    let doctor = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args(["setup", "doctor", "--format", "json"])
        .output()
        .expect("setup doctor should run");

    assert!(doctor.status.success());
    assert!(doctor.stderr.is_empty());
    let doctor_json: Value = serde_json::from_slice(&doctor.stdout).expect("doctor JSON");
    assert_eq!(doctor_json["configuration_ready"], true);
    assert_eq!(doctor_json["live_health_checked"], false);
    assert!(
        doctor_json["checks"]
            .as_array()
            .expect("checks")
            .iter()
            .any(|check| check["name"] == "network_budget")
    );
    assert!(
        doctor_json["live_health_commands"]
            .as_array()
            .expect("live health commands")
            .iter()
            .any(|command| command == "relay-knowledge health --format json")
    );

    let profile = relay_command()
        .env(RELAY_KNOWLEDGE_HOME, &home)
        .args(["setup", "profile", "agent-readonly", "--format", "json"])
        .output()
        .expect("setup profile should run");

    assert!(profile.status.success());
    assert!(profile.stderr.is_empty());
    let profile_json: Value = serde_json::from_slice(&profile.stdout).expect("profile JSON");
    assert_eq!(profile_json["profile"], "agent-readonly");
    assert!(
        profile_json["environment"]
            .as_array()
            .expect("environment")
            .iter()
            .any(|variable| variable["name"] == "RELAY_KNOWLEDGE_MCP_ALLOWED_SCOPES")
    );
}

#[test]
fn binary_rejects_flag_style_actions_and_extra_command_words() {
    let flag_action = relay_command()
        .args(["--ingest", "--source", "docs", "--content", "x"])
        .output()
        .expect("binary should run");
    let extra = relay_command()
        .args(["status", "health"])
        .output()
        .expect("binary should run");

    assert_eq!(flag_action.status.code(), Some(2));
    let flag_stderr = String::from_utf8_lossy(&flag_action.stderr);
    assert!(flag_stderr.contains("unknown option '--ingest'; commands are positional"));
    assert!(flag_stderr.contains("relay-knowledge ingest"));
    assert_eq!(extra.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&extra.stderr)
            .contains("unexpected argument 'health' for 'status'")
    );
}

#[test]
fn binary_diagnostics_use_canonical_cli_name() {
    let typo = relay_command()
        .args(["repo", "qurey", "core", "--query", "rust"])
        .output()
        .expect("binary should run");
    let json = relay_command()
        .args(["--format", "json", "query", "--query", "SQLite"])
        .output()
        .expect("binary should run");

    assert_eq!(typo.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&typo.stderr);
    assert!(stderr.contains("did you mean 'repo query'"));
    assert!(stderr.contains(&format!("Try: {PROJECT_NAME} repo query")));
    assert!(stderr.contains(&format!("Usage: {PROJECT_NAME} repo <subcommand>")));

    assert_eq!(json.status.code(), Some(2));
    let value: Value = serde_json::from_slice(&json.stderr).expect("diagnostic JSON");
    assert_eq!(value["suggestion"], format!("{PROJECT_NAME} query SQLite"));
    assert_eq!(
        value["usage"],
        format!(
            "{PROJECT_NAME} query <text> [--source <scope>] [--limit <n>] [--freshness <policy>]"
        )
    );
}

#[test]
fn binary_outputs_json_parse_diagnostic_on_json_format_errors() {
    let output = relay_command()
        .args(["--format", "json", "query", "--query", "SQLite"])
        .output()
        .expect("binary should run");

    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());

    let value: Value = serde_json::from_slice(&output.stderr).expect("stderr diagnostic JSON");

    assert_eq!(value["matched_path"], serde_json::json!(["query"]));
    assert_eq!(value["unexpected_token"], "--query");
    assert_eq!(value["suggestion"], format!("{PROJECT_NAME} query SQLite"));
}

fn assert_command_metadata_uses_project_name(command: &Value) {
    let path = command["path"]
        .as_array()
        .expect("path should be an array")
        .iter()
        .map(|segment| {
            segment
                .as_str()
                .expect("path segment should be a string")
                .to_owned()
        })
        .collect::<Vec<_>>();
    let usage = command["usage"].as_str().expect("usage should exist");

    assert_usage_invokes_path(usage, &path);

    for example in command["examples"]
        .as_array()
        .expect("examples should be an array")
    {
        assert_invocation_uses_project_name(example.as_str().expect("example should be a string"));
    }
}

fn assert_usage_invokes_path(usage: &str, path: &[String]) {
    assert_invocation_uses_project_name(usage);

    let tokens = usage.split_whitespace().collect::<Vec<_>>();
    assert_eq!(tokens.first().copied(), Some(PROJECT_NAME));

    for (index, segment) in path.iter().enumerate() {
        let usage_segment = tokens
            .get(index + 1)
            .unwrap_or_else(|| panic!("usage is missing path segment '{segment}': {usage}"));
        assert!(
            usage_segment
                .split('|')
                .any(|candidate| candidate == segment.as_str()),
            "usage segment '{usage_segment}' should include path segment '{segment}' in {usage}"
        );
    }
}

fn assert_invocation_uses_project_name(invocation: &str) {
    assert!(
        invocation
            .split_whitespace()
            .any(|token| token == PROJECT_NAME),
        "invocation should include canonical CLI name '{PROJECT_NAME}': {invocation}"
    );
}

fn relay_command() -> Command {
    let mut command = Command::new(env!("CARGO_BIN_EXE_relay-knowledge"));

    for variable in [
        RELAY_KNOWLEDGE_HOME,
        RELAY_KNOWLEDGE_CONFIG_DIR,
        RELAY_KNOWLEDGE_DATA_DIR,
        RELAY_KNOWLEDGE_STATE_DIR,
        RELAY_KNOWLEDGE_CACHE_DIR,
        RELAY_KNOWLEDGE_LOG_DIR,
        RELAY_KNOWLEDGE_TEMP_DIR,
        RELAY_KNOWLEDGE_RUNTIME_DIR,
        RELAY_KNOWLEDGE_SERVICE_DIR,
        RELAY_KNOWLEDGE_HTTP_BIND,
        RELAY_KNOWLEDGE_HTTP_REQUEST_TIMEOUT_MS,
        RELAY_KNOWLEDGE_HTTP_SHUTDOWN_TIMEOUT_MS,
        RELAY_KNOWLEDGE_HTTP_MAX_BODY_BYTES,
        RELAY_KNOWLEDGE_MCP_STREAMABLE_HTTP_ENABLED,
        RELAY_KNOWLEDGE_MCP_ENDPOINT,
        RELAY_KNOWLEDGE_MCP_ALLOWED_ORIGINS,
        RELAY_KNOWLEDGE_MCP_ALLOWED_SCOPES,
        RELAY_KNOWLEDGE_MCP_ALLOW_UNSPECIFIED_SCOPE,
        RELAY_KNOWLEDGE_MCP_MAX_LIMIT,
        RELAY_KNOWLEDGE_MCP_MAX_CONTEXT_BYTES,
        RELAY_KNOWLEDGE_MCP_ALLOW_REMOTE_CLIENTS,
        RELAY_KNOWLEDGE_QOS_MAX_CONNECTIONS,
        RELAY_KNOWLEDGE_QOS_MAX_IN_FLIGHT_REQUESTS,
        RELAY_KNOWLEDGE_QOS_MAX_QUEUE_DEPTH,
        HTTPS_PROXY,
        HTTPS_PROXY_LOWER,
        HTTP_PROXY,
        HTTP_PROXY_LOWER,
        ALL_PROXY,
        ALL_PROXY_LOWER,
        NO_PROXY,
        NO_PROXY_LOWER,
        SSL_VERIFY,
        SSL_VERIFY_LOWER,
    ] {
        command.env_remove(variable);
    }
    command.env(RELAY_KNOWLEDGE_HOME, isolated_home("relay-command"));

    command
}

fn isolated_home(test_name: &str) -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock should be after epoch")
        .as_nanos();
    let path = std::env::temp_dir().join(format!("relay-knowledge-{test_name}-{nanos}"));

    path.display().to_string()
}