roteiro 1.1.0

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! End-to-end test for `roteiro links` (ADR-0009): a spoke repo declares authored
//! cross-repo `[[links]]` into a hub repo's graph; the command resolves each
//! against the workspace, reports the ones that resolve, and flags drift (targets
//! that no longer exist), exiting non-zero so it works as a CI gate.

use std::path::Path;
use std::process::Command;

const BIN: &str = env!("CARGO_BIN_EXE_roteiro");

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args([
            "-c",
            "user.name=Test",
            "-c",
            "user.email=test@example.com",
            "-c",
            "commit.gpgsign=false",
            "-c",
            "init.defaultBranch=main",
        ])
        .args(args)
        .current_dir(dir)
        .status()
        .expect("run git");
    assert!(status.success(), "git {args:?} failed in {}", dir.display());
}

fn roteiro(dir: &Path, args: &[&str]) -> std::process::Output {
    Command::new(BIN)
        .args(args)
        .current_dir(dir)
        .output()
        .expect("run roteiro")
}

fn head_sha(dir: &Path) -> String {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(dir)
        .output()
        .expect("rev-parse");
    assert!(
        out.status.success(),
        "git rev-parse HEAD failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8(out.stdout).unwrap().trim().to_owned()
}

/// Run `links --infer --hub app --workspace <base> --json` plus `extra` and return
/// the parsed report.
fn infer_json(base: &Path, extra: &[&str]) -> serde_json::Value {
    let base_s = base.to_str().unwrap();
    let mut args = vec!["links", "--infer", "--hub", "app", "--workspace", base_s];
    args.extend_from_slice(extra);
    args.push("--json");
    let out = roteiro(base, &args);
    assert!(out.status.success(), "infer {extra:?} failed: {out:?}");
    serde_json::from_slice(&out.stdout).expect("JSON")
}

/// The `hub_key`s a report's first spoke matched.
fn matched_hub_keys(report: &serde_json::Value) -> Vec<String> {
    report["spokes"][0]["matches"]
        .as_array()
        .unwrap()
        .iter()
        .map(|m| m["hub_key"].as_str().unwrap().to_owned())
        .collect()
}

#[test]
fn infer_resolves_against_a_pinned_hub_version() {
    let base = std::env::temp_dir().join(format!("roteiro-hubrev-cli-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub v1 defines `serve.tools`; v2 renames it to `serve.features`. Sync each so
    // the HEAD graph reflects v2.
    std::fs::write(app.join("config.toml"), "[serve]\ntools = true\n").expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "v1"]);
    let v1 = head_sha(&app);
    // Tag v1 so we can pin by a *revspec* (a tag), not just a sha — the resolver
    // must accept both.
    git(&app, &["tag", "rel-1"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v1 sync");
    std::fs::write(app.join("config.toml"), "[serve]\nfeatures = true\n").expect("write");
    git(&app, &["commit", "-aqm", "v2 rename"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v2 sync");

    // Spoke references the *old* key (`SERVE_TOOLS`).
    std::fs::write(deploy.join("prod.env"), "SERVE_TOOLS=true\n").expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&deploy, &["sync"]).status.success(), "deploy sync");

    // Against HEAD: the hub no longer defines the key, so it's an orphan (drift).
    let head = infer_json(&base, &[]);
    let orphans: Vec<&str> = head["spokes"][0]["orphans"]
        .as_array()
        .unwrap()
        .iter()
        .map(|o| o["key"].as_str().unwrap())
        .collect();
    assert!(
        orphans.contains(&"SERVE_TOOLS"),
        "drift against HEAD: {head}"
    );
    assert_eq!(head["hub_rev"], serde_json::Value::Null);

    // Against the pinned v1 — named by the *tag* `rel-1`, not a sha — it resolves.
    let by_tag = infer_json(&base, &["--hub-rev", "rel-1"]);
    assert_eq!(by_tag["hub_rev"], "rel-1", "reports the pinned rev (a tag)");
    assert!(
        matched_hub_keys(&by_tag).contains(&"serve.tools".to_owned()),
        "resolves at the pinned version: {by_tag}"
    );
    assert!(
        by_tag["spokes"][0]["orphans"]
            .as_array()
            .unwrap()
            .is_empty(),
        "no drift once resolved against the deployed version: {by_tag}"
    );

    // The same pin named by the raw sha resolves identically — any revspec works.
    let by_sha = infer_json(&base, &["--hub-rev", &v1]);
    assert_eq!(by_sha["hub_rev"], v1);
    assert!(
        matched_hub_keys(&by_sha).contains(&"serve.tools".to_owned()),
        "sha pin resolves too: {by_sha}"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn hub_rev_uses_a_published_graph_artifact_when_present() {
    let base = std::env::temp_dir().join(format!("roteiro-artifact-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    std::fs::write(app.join("config.toml"), "[serve]\ntools = true\n").expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "v1"]);
    let v1 = head_sha(&app);
    assert!(roteiro(&app, &["sync"]).status.success(), "app sync");

    // Export the hub graph, then inject a sentinel config key that is NOT in the
    // actual tree, and publish it at the conventional artifact path for v1's tree.
    // If resolution later surfaces the sentinel, it used the artifact — not extraction.
    let export = roteiro(&app, &["export", "--out", "-"]);
    assert!(export.status.success(), "export failed: {export:?}");
    let mut art: serde_json::Value = serde_json::from_slice(&export.stdout).expect("artifact JSON");
    art["facts"]["nodes"]
        .as_array_mut()
        .unwrap()
        .push(serde_json::json!({
            "key": "cfgkey:art.toml#artifact.only", "kind": "config_key", "name": "artifact.only",
            "path": "art.toml", "lang": null, "blob_hash": null, "span": null,
            "provenance": "derived", "meta": { "key": "artifact.only", "value": "yes" }
        }));
    let tree = String::from_utf8(
        Command::new("git")
            .args(["rev-parse", "HEAD^{tree}"])
            .current_dir(&app)
            .output()
            .expect("tree")
            .stdout,
    )
    .unwrap()
    .trim()
    .to_owned();
    let art_dir = app.join(".git/roteiro/artifacts");
    std::fs::create_dir_all(&art_dir).expect("mkdir artifacts");
    std::fs::write(art_dir.join(format!("{tree}.json")), art.to_string()).expect("write artifact");

    // Spoke references a key only the *artifact* defines, plus a real one.
    std::fs::write(
        deploy.join("prod.env"),
        "ARTIFACT_ONLY=yes\nSERVE_TOOLS=true\n",
    )
    .expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&deploy, &["sync"]).status.success(), "deploy sync");

    let base_s = base.to_str().unwrap();
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--hub",
            "app",
            "--hub-rev",
            &v1,
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(out.status.success(), "hub-rev infer failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("JSON");
    let matched = matched_hub_keys(&v);
    assert!(
        matched.contains(&"artifact.only".to_owned()),
        "resolution used the published artifact (sentinel key present): {v}"
    );
    assert!(matched.contains(&"serve.tools".to_owned()), "{v}");

    // A corrupt artifact is "not usable": resolution must fall back to extraction
    // (no sentinel, but the real tree key still resolves), never abort.
    std::fs::write(art_dir.join(format!("{tree}.json")), "{ not valid json").expect("corrupt");
    let v = infer_json(&base, &["--hub-rev", &v1]);
    let matched = matched_hub_keys(&v);
    assert!(
        !matched.contains(&"artifact.only".to_owned()),
        "corrupt artifact must be ignored: {v}"
    );
    assert!(
        matched.contains(&"serve.tools".to_owned()),
        "fell back to extraction: {v}"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn pinned_uses_pins_config_template_for_image_tags() {
    let base = std::env::temp_dir().join(format!("roteiro-pinstmpl-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub v1 (serve.tools), tagged `release-1.2` — a scheme the default `1.2`/`v1.2`
    // guess would miss. Then v2 renames the key at HEAD.
    std::fs::write(app.join("config.toml"), "[serve]\ntools = true\n").expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "v1"]);
    git(&app, &["tag", "release-1.2"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v1 sync");
    std::fs::write(app.join("config.toml"), "[serve]\nfeatures = true\n").expect("write");
    git(&app, &["commit", "-aqm", "v2"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v2 sync");

    // Spoke: a Dockerfile pins image `app:1.2`, and `[pins]` says its git ref is
    // `release-{tag}`. It also references the old key.
    std::fs::write(deploy.join("Dockerfile"), "FROM registry.io/app:1.2\n").expect("write");
    std::fs::write(deploy.join("prod.env"), "SERVE_TOOLS=true\n").expect("write");
    std::fs::write(
        deploy.join("roteiro.toml"),
        "[pins]\napp = \"release-{tag}\"\n",
    )
    .expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&deploy, &["sync"]).status.success(), "deploy sync");

    let base_s = base.to_str().unwrap();
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--pinned",
            "--hub",
            "app",
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(out.status.success(), "pinned infer failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("JSON");
    let spoke = &v["spokes"][0];
    // The `[pins]` template resolved the image tag to the `release-1.2` git tag.
    assert_eq!(
        spoke["hub_rev"], "release-1.2",
        "resolved via [pins] template: {v}"
    );
    assert!(
        spoke["pin_via"].as_str().unwrap_or("").starts_with("image"),
        "pinned via the image: {v}"
    );
    assert!(
        matched_hub_keys(&v).contains(&"serve.tools".to_owned()),
        "old key resolves at the deployed version: {v}"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn pinned_auto_resolves_each_spoke_against_the_version_it_vendors() {
    let base = std::env::temp_dir().join(format!("roteiro-pinned-cli-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub v1 defines `serve.tools`; v2 renames it. Sync each; capture the v1 sha.
    std::fs::write(app.join("config.toml"), "[serve]\ntools = true\n").expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "v1"]);
    let v1 = head_sha(&app);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v1 sync");
    std::fs::write(app.join("config.toml"), "[serve]\nfeatures = true\n").expect("write");
    git(&app, &["commit", "-aqm", "v2"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app v2 sync");

    // Spoke references the old key AND vendors the hub as a submodule pinned to v1.
    std::fs::write(deploy.join("prod.env"), "SERVE_TOOLS=true\n").expect("write");
    std::fs::write(
        deploy.join(".gitmodules"),
        "[submodule \"app\"]\n\tpath = app\n\turl = https://github.com/acme/app.git\n",
    )
    .expect("write .gitmodules");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "prod.env", ".gitmodules"]);
    // The gitlink pins the hub at its v1 commit.
    git(
        &deploy,
        &[
            "update-index",
            "--add",
            "--cacheinfo",
            &format!("160000,{v1},app"),
        ],
    );
    git(&deploy, &["commit", "-q", "-m", "deploy pinned to app@v1"]);
    assert!(roteiro(&deploy, &["sync"]).status.success(), "deploy sync");

    let base_s = base.to_str().unwrap();
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--pinned",
            "--hub",
            "app",
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(out.status.success(), "pinned infer failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("JSON");
    let spoke = &v["spokes"][0];
    assert_eq!(spoke["repo"], "deploy");
    // Auto-detected the v1 pin via the submodule, so the old key resolves.
    assert_eq!(
        spoke["hub_rev"], v1,
        "resolved against the vendored version: {v}"
    );
    assert!(
        spoke["pin_via"]
            .as_str()
            .unwrap_or("")
            .contains("submodule app"),
        "reports the pin source: {v}"
    );
    let matched: Vec<&str> = spoke["matches"]
        .as_array()
        .unwrap()
        .iter()
        .map(|m| m["hub_key"].as_str().unwrap())
        .collect();
    assert!(
        matched.contains(&"serve.tools"),
        "resolves at the pinned version: {v}"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn links_resolve_across_repos_and_flag_drift() {
    let base = std::env::temp_dir().join(format!("roteiro-links-cli-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub: a real graph with a `file:README.md` node.
    std::fs::write(app.join("README.md"), "# App\n").expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app sync failed");

    // Spoke: authored links — one that resolves, one drift (removed key), one to a
    // project that isn't in the workspace.
    std::fs::write(
        deploy.join("roteiro.toml"),
        "[[links]]\n\
         to = \"app::file:README.md\"\n\
         from = \"file:values.yaml\"\n\
         kind = \"configures\"\n\
         \n\
         [[links]]\n\
         to = \"app::file:gone.md\"\n\
         \n\
         [[links]]\n\
         to = \"ghost::file:x\"\n",
    )
    .expect("write toml");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);

    let base_s = base.to_str().unwrap();

    // Human output: the resolving link is `ok`, the two bad ones `DRIFT`; the
    // command exits non-zero because there is drift.
    let out = roteiro(&base, &["links", "--workspace", base_s]);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(!out.status.success(), "drift must fail the command: {text}");
    assert!(
        text.contains("app::file:README.md") && text.contains("ok"),
        "{text}"
    );
    assert!(
        text.contains("app::file:gone.md") && text.contains("DRIFT"),
        "{text}"
    );

    // JSON: three links, exactly one resolved.
    let out = roteiro(&base, &["links", "--workspace", base_s, "--json"]);
    let arr: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    let arr = arr.as_array().expect("array");
    assert_eq!(arr.len(), 3, "three declared links: {arr:?}");
    let ok = arr.iter().filter(|r| r["status"] == "ok").count();
    let drift = arr.iter().filter(|r| r["status"] == "drift").count();
    assert_eq!((ok, drift), (1, 2), "one resolves, two drift: {arr:?}");
    // The resolved one names its target node.
    let resolved = arr.iter().find(|r| r["status"] == "ok").unwrap();
    assert_eq!(resolved["to"], "app::file:README.md");
    assert!(resolved["detail"].as_str().unwrap().contains("README.md"));

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn infer_matches_config_keys_across_repos_and_flags_orphans() {
    let base = std::env::temp_dir().join(format!("roteiro-infer-cli-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub: a TOML config with a few keys.
    std::fs::write(
        app.join("config.toml"),
        "[serve]\naddr = \"127.0.0.1:8017\"\ntools = true\n[models]\ngenerative = \"qwen3-0.6b\"\n",
    )
    .expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "init"]);
    // `--infer` reads config keys from the graph, so both repos must be synced.
    assert!(roteiro(&app, &["sync"]).status.success(), "app sync failed");

    // Spoke: an .env that overrides two keys (different naming convention) and
    // sets one the app doesn't define (the orphan / drift candidate).
    std::fs::write(
        deploy.join("prod.env"),
        "SERVE_ADDR=0.0.0.0:8443\nSERVE_TOOLS=false\nMAX_CONNECTIONS=512\n",
    )
    .expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(
        roteiro(&deploy, &["sync"]).status.success(),
        "deploy sync failed"
    );

    let base_s = base.to_str().unwrap();
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--hub",
            "app",
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(
        out.status.success(),
        "infer is informational (exit 0): {out:?}"
    );
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    assert_eq!(v["hub"], "app");
    let spoke = &v["spokes"][0];
    assert_eq!(spoke["repo"], "deploy");
    // SERVE_ADDR / SERVE_TOOLS match app's serve.addr / serve.tools by name.
    let matched: Vec<&str> = spoke["matches"]
        .as_array()
        .unwrap()
        .iter()
        .map(|m| m["hub_key"].as_str().unwrap())
        .collect();
    assert!(matched.contains(&"serve.addr"), "{matched:?}");
    assert!(matched.contains(&"serve.tools"), "{matched:?}");
    // MAX_CONNECTIONS has no app counterpart → orphan.
    let orphans: Vec<&str> = spoke["orphans"]
        .as_array()
        .unwrap()
        .iter()
        .map(|o| o["key"].as_str().unwrap())
        .collect();
    assert_eq!(
        orphans,
        vec!["MAX_CONNECTIONS"],
        "the app-undefined key is the orphan"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn infer_write_persists_cross_repo_edges_that_survive_sync() {
    let base = std::env::temp_dir().join(format!("roteiro-infer-write-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub with two config keys; spoke overrides both under a different convention.
    std::fs::write(
        app.join("config.toml"),
        "[serve]\naddr = \"127.0.0.1:8017\"\ntools = true\n",
    )
    .expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app sync failed");

    std::fs::write(
        deploy.join("prod.env"),
        "SERVE_ADDR=0.0.0.0:8443\nSERVE_TOOLS=false\n",
    )
    .expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(
        roteiro(&deploy, &["sync"]).status.success(),
        "deploy sync failed"
    );

    let base_s = base.to_str().unwrap();

    // Persist the inferred links into the spoke's graph.
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--hub",
            "app",
            "--write",
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(out.status.success(), "infer --write failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    assert_eq!(v["written"], 2, "two matches persisted as edges: {v}");

    // The external-ref target nodes are now queryable in the spoke's graph.
    let q = roteiro(&deploy, &["query", "--kind", "external_ref", "--json"]);
    assert!(q.status.success(), "query failed: {q:?}");
    let text = String::from_utf8_lossy(&q.stdout);
    assert!(
        text.contains("app::cfgkey:config.toml#serve.addr"),
        "external-ref to the hub key must be present: {text}"
    );

    // A re-sync of the spoke must not drop the persisted layer (it is re-applied).
    assert!(
        roteiro(&deploy, &["sync"]).status.success(),
        "deploy re-sync failed"
    );
    let q = roteiro(&deploy, &["query", "--kind", "external_ref", "--json"]);
    let text = String::from_utf8_lossy(&q.stdout);
    assert!(
        text.contains("app::cfgkey:config.toml#serve.addr"),
        "external-ref must survive a re-sync: {text}"
    );

    // Now the hub loses every key the spoke matched: the spoke drops to *zero*
    // matches. A re-`--write` must clear the stale inferred links (the layer is
    // re-applied authoritatively even when empty), not leak them.
    std::fs::write(app.join("config.toml"), "[database]\nhost = \"db\"\n").expect("rewrite");
    git(&app, &["commit", "-aqm", "unrelated config"]);
    assert!(
        roteiro(&app, &["sync"]).status.success(),
        "app re-sync failed"
    );
    let out = roteiro(
        &base,
        &[
            "links",
            "--infer",
            "--hub",
            "app",
            "--write",
            "--workspace",
            base_s,
            "--json",
        ],
    );
    assert!(out.status.success(), "re-infer --write failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    assert_eq!(v["written"], 0, "no matches remain: {v}");
    // The stale cross-repo *edge* must be cleared: the empty layer is applied
    // authoritatively (not skipped), so the spoke's config key no longer has an
    // inferred `references` edge into the hub. (Orphan external-ref nodes with no
    // edges are cleaned by the next real re-sync, as with any import layer.)
    let q = roteiro(&deploy, &["query", "cfgkey:prod.env#SERVE_ADDR", "--json"]);
    assert!(q.status.success(), "query failed: {q:?}");
    let ex: serde_json::Value = serde_json::from_slice(&q.stdout).expect("valid JSON");
    let outgoing = ex["outgoing"].as_array().cloned().unwrap_or_default();
    assert!(
        !outgoing
            .iter()
            .any(|e| e["node"].as_str().is_some_and(|n| n.starts_with("extref:"))),
        "stale inferred cross-repo edge must be cleared when matches drop to zero: {ex}"
    );

    std::fs::remove_dir_all(&base).ok();
}

#[test]
fn incompatible_link_flag_combinations_are_rejected() {
    // clap constraints fail fast rather than silently running a surprising path.
    for args in [
        ["links", "--infer", "--matrix"].as_slice(),
        ["links", "--write"].as_slice(), // --write without --infer
        ["links", "--html"].as_slice(),  // --html without --matrix
        ["links", "--out", "x.html"].as_slice(), // --out without --html
    ] {
        let out = roteiro(Path::new("."), args);
        assert!(
            !out.status.success(),
            "expected {args:?} to be rejected by clap"
        );
    }
}

#[test]
fn matrix_renders_override_grid_and_drift_across_formats() {
    let base = std::env::temp_dir().join(format!("roteiro-matrix-cli-{}", std::process::id()));
    std::fs::remove_dir_all(&base).ok();
    let app = base.join("app");
    let deploy = base.join("deploy");
    std::fs::create_dir_all(&app).expect("mkdir app");
    std::fs::create_dir_all(&deploy).expect("mkdir deploy");

    // Hub defines serve.addr + serve.tools.
    std::fs::write(
        app.join("config.toml"),
        "[serve]\naddr = \"127.0.0.1:8017\"\ntools = true\n",
    )
    .expect("write");
    git(&app, &["init", "-q"]);
    git(&app, &["add", "."]);
    git(&app, &["commit", "-q", "-m", "init"]);
    assert!(roteiro(&app, &["sync"]).status.success(), "app sync failed");

    // Spoke overrides addr to a *different* value, restates tools identically, and
    // sets one orphan key (drift).
    std::fs::write(
        deploy.join("prod.env"),
        "SERVE_ADDR=0.0.0.0:8443\nSERVE_TOOLS=true\nMAX_CONNECTIONS=512\n",
    )
    .expect("write");
    git(&deploy, &["init", "-q"]);
    git(&deploy, &["add", "."]);
    git(&deploy, &["commit", "-q", "-m", "init"]);
    assert!(
        roteiro(&deploy, &["sync"]).status.success(),
        "deploy sync failed"
    );

    let base_s = base.to_str().unwrap();
    let common = ["links", "--matrix", "--hub", "app", "--workspace", base_s];

    // JSON: serve.addr is a real override (differs), serve.tools is redundant, and
    // MAX_CONNECTIONS is drift.
    let mut json_args = common.to_vec();
    json_args.push("--json");
    let out = roteiro(&base, &json_args);
    assert!(out.status.success(), "matrix --json failed: {out:?}");
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    assert_eq!(v["hub"], "app");
    let rows = v["rows"].as_array().expect("rows");
    let addr = rows
        .iter()
        .find(|r| r["hub_key"] == "serve.addr")
        .expect("serve.addr row");
    assert_eq!(
        addr["cells"]["deploy"]["differs"], true,
        "addr is an override"
    );
    let tools = rows
        .iter()
        .find(|r| r["hub_key"] == "serve.tools")
        .expect("serve.tools row");
    assert_eq!(
        tools["cells"]["deploy"]["differs"], false,
        "tools restated identically"
    );
    let drift: Vec<&str> = v["drift"]
        .as_array()
        .unwrap()
        .iter()
        .map(|d| d["key"].as_str().unwrap())
        .collect();
    assert_eq!(drift, vec!["MAX_CONNECTIONS"]);

    // Text: marks the override with ≠ and lists drift.
    let out = roteiro(&base, &common);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("≠ deploy: 0.0.0.0:8443"), "{text}");
    assert!(
        text.contains("drift") && text.contains("MAX_CONNECTIONS"),
        "{text}"
    );

    // HTML: a self-contained page written to the requested file.
    let html_path = base.join("overview.html");
    let mut html_args = common.to_vec();
    html_args.extend(["--html", "--out", html_path.to_str().unwrap()]);
    let out = roteiro(&base, &html_args);
    assert!(out.status.success(), "matrix --html failed: {out:?}");
    let html = std::fs::read_to_string(&html_path).expect("html written");
    assert!(html.starts_with("<!doctype html>"));
    assert!(html.contains("<style>"), "self-contained CSS");
    assert!(html.contains("serve.addr") && html.contains("0.0.0.0:8443"));
    assert!(html.contains("MAX_CONNECTIONS"), "drift shown");

    std::fs::remove_dir_all(&base).ok();
}