zhao-cli 0.5.3

Deterministic, offline change-review and CI gate for data transformation projects.
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
//! The `zhao lineage` command: a structural query over the current
//! project's compiled state -- what's upstream/downstream of a target
//! model, using dbt's own `+`-prefix/suffix selector syntax. Unlike
//! `zhao check`/`zhao diff`, this reads no Baseline and resolves no
//! `--state`. Its compiled manifest is read from
//! `<project-dir>/target/manifest.json` by default, or from
//! `<project-dir>/<target-path>/manifest.json` when `--dbt-arg`/
//! `--dbt-args` carries a `--target-path` override -- see
//! `crate::dbt_target::resolve_target_dir`.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use zhao_core::config::Config;
use zhao_core::lineage::{ColumnLineageResult, Direction, LineageResult, trace, trace_column};

use crate::adapter::ResolvedAdapter;
use crate::cli::LineageArgs;

/// Exit code for "ran successfully" -- `zhao lineage` is a query tool,
/// not a gate, so a successful (even empty) result always exits zero;
/// only a genuine failure to run at all (bad path, unparsable manifest,
/// unknown target) exits non-zero.
const EXIT_OK: u8 = 0;

/// Exit code shared with `zhao check`/`zhao diff` for "couldn't even
/// run" -- see [`crate::engine::fail`].
const EXIT_ERROR: u8 = 2;

/// Runs `zhao lineage` and returns the process exit code.
pub fn run(args: &LineageArgs) -> ExitCode {
    // Loaded once, up front, regardless of `--compile`: both the
    // `dbt-command` passthrough below and adapter auto-detection's
    // `tool:` fallback come from the same `zhao.yml`.
    let config = match Config::load_for_project(&args.project_dir) {
        Ok(config) => config,
        Err(err) => return fail(&err.to_string()),
    };
    // Auto-detected by project marker first, `zhao.yml`'s `tool:` key
    // only consulted as a fallback -- see
    // `crate::adapter::ResolvedAdapter::resolve`.
    let adapter = match ResolvedAdapter::resolve(&args.project_dir, config.tool()) {
        Ok(adapter) => adapter,
        Err(err) => return fail(&err.to_string()),
    };

    // `--dbt-command`/`--dbt-arg`/`--dbt-args` win outright when given;
    // otherwise falls back to `zhao.yml`'s `dbt-command`/`dbt-args`;
    // otherwise `"dbt"`/no extra args -- same precedence `zhao check`/
    // `zhao diff` already use (see `crate::dbt_target::resolve_dbt_invocation`,
    // shared with `crate::engine::build_report`). A project already
    // using its own wrapper instead of invoking `dbt` directly shouldn't
    // need `zhao lineage --compile` to be the one place that still
    // hardcodes `"dbt"`.
    let dbt_passthrough_args = match args.dbt_passthrough_args() {
        Ok(args) => args,
        Err(err) => return fail(&err),
    };
    let (dbt_command, dbt_passthrough_args) = match crate::dbt_target::resolve_dbt_invocation(
        args.dbt_command.as_deref(),
        dbt_passthrough_args,
        &config,
    ) {
        Ok(resolved) => resolved,
        Err(err) => return fail(&err),
    };

    if args.compile {
        // `dbt_project_dir` and `real_project_dir` are the same path
        // here -- unlike `baseline::resolve`'s git-native Baseline
        // compile (which runs in a throwaway worktree), `--compile`
        // runs directly in the real project directory. See issue #36.
        // `--dbt-args`/`--dbt-arg` (e.g. a `--target-path` override) are
        // forwarded to the compile itself -- see `resolve_target_dir`
        // just below for where the resulting manifest gets read back
        // from.
        if let Err(err) = crate::log::log_dbt_result(
            "compile",
            &args.project_dir,
            &args.project_dir,
            adapter.compile(&args.project_dir, &dbt_command, &dbt_passthrough_args),
        ) {
            return fail(&err.to_string());
        }
    }

    let target_dir =
        crate::dbt_target::resolve_target_dir(&args.project_dir, &dbt_passthrough_args);
    let manifest_path = target_dir.join("manifest.json");
    let project = match adapter.parse(&manifest_path) {
        Ok(project) => project,
        Err(err) => return fail(&format!("{}: {err}", manifest_path.display())),
    };

    // Unconditional, target-independent -- always the whole project's
    // graph, written before any target resolution/validation below (it
    // doesn't depend on the target at all, so there's no reason to gate
    // it behind a successful resolution). Same "unconditional
    // machine-readable output" precedent as `run-metadata.json`. See
    // issue #39.
    if let Err(err) = write_full_lineage_json(&args.project_dir, &project, &adapter) {
        return fail(&err);
    }

    let exit_code = if args.text {
        run_text(args, &project, &adapter)
    } else {
        run_html(args, &project, &adapter)
    };

    // `--purge-logs` wins when explicitly passed; otherwise `zhao.yml`'s
    // `log.retention_days`; otherwise no purging. A `zhao.yml` load
    // failure here is silently treated as "no retention configured"
    // rather than failing the whole command -- `zhao lineage` doesn't
    // otherwise depend on `zhao.yml` at all, so a config problem
    // shouldn't block a query that doesn't need it. See issue #37.
    let log_retention_days = args.purge_logs.or_else(|| {
        zhao_core::config::Config::load_for_project(&args.project_dir)
            .ok()
            .and_then(|config| config.log_retention_days())
    });
    crate::log::purge(&args.project_dir, log_retention_days);

    exit_code
}

/// Writes `<project_dir>/target/zhao/full_lineage.json`: a direct
/// serialization of the whole project's lineage graph (every Node,
/// Origin, model-/column-level edge), independent of whatever
/// `--text`/`--html`/target was requested -- see issue #39. Overwritten
/// on every run, no flag to turn it off.
fn write_full_lineage_json(
    project_dir: &Path,
    project: &zhao_core::model::ParsedProject,
    adapter: &ResolvedAdapter,
) -> Result<(), String> {
    let dir = project_dir.join("target").join("zhao");
    std::fs::create_dir_all(&dir)
        .map_err(|err| format!("could not create {}: {err}", dir.display()))?;

    let path = dir.join("full_lineage.json");
    let json = crate::lineage_html::graph_data_json(project, adapter.vocabulary());
    std::fs::write(&path, json).map_err(|err| format!("could not write {}: {err}", path.display()))
}

/// zhao's default filenaming scheme for `zhao lineage`'s HTML export,
/// under `<project-dir>/target/zhao/lineage_graphs/`: `full_lineage.html`
/// with no target, else `partial_lineage_[<package>_]<model>[_<column>]
/// [_upstream_only|_downstream_only].html` -- the package segment only
/// when `--package` was given, the column segment only for a
/// column-level target, and no direction suffix at all for the default
/// "both directions" case.
fn default_html_path(
    project_dir: &Path,
    parsed_target: Option<(&str, Option<&str>, Direction)>,
    package: Option<&str>,
) -> PathBuf {
    let dir = project_dir
        .join("target")
        .join("zhao")
        .join("lineage_graphs");
    let Some((model, column, direction)) = parsed_target else {
        return dir.join("full_lineage.html");
    };

    let mut name = String::from("partial_lineage_");
    if let Some(package) = package {
        name.push_str(package);
        name.push('_');
    }
    name.push_str(model);
    if let Some(column) = column {
        name.push('_');
        name.push_str(column);
    }
    match direction {
        Direction::Upstream => name.push_str("_upstream_only"),
        Direction::Downstream => name.push_str("_downstream_only"),
        Direction::Both => {}
    }
    name.push_str(".html");
    dir.join(name)
}

/// The default output mode: generates the self-contained interactive
/// export, at `--html`'s explicit path when given, else the computed
/// default under `target/zhao/lineage_graphs/` (see
/// [`default_html_path`]).
fn run_html(
    args: &LineageArgs,
    project: &zhao_core::model::ParsedProject,
    adapter: &ResolvedAdapter,
) -> ExitCode {
    let parsed_target = args.parse_target();

    // `LineageError`'s own `Display` already gives a clear, actionable
    // message for every variant, same as the text path -- validated up
    // front (via the same resolution `trace`/`trace_column` use) so an
    // unknown/ambiguous/unknown-column target fails the same way it
    // would for text output, rather than silently producing an export
    // with nothing pre-selected.
    let package = args.package.as_deref();
    let (initial_target, initial_column) = match parsed_target {
        None => (None, None),
        Some((target_name, Some(column_name), direction)) => {
            match trace_column(project, target_name, package, column_name, direction) {
                Ok(_) => match zhao_core::lineage::resolve_target(project, target_name, package) {
                    Ok(id) => (Some(id), Some(column_name.to_string())),
                    Err(err) => return fail(&err.to_string()),
                },
                Err(err) => return fail(&err.to_string()),
            }
        }
        Some((target_name, None, direction)) => {
            match trace(project, target_name, package, direction) {
                Ok(_) => match zhao_core::lineage::resolve_target(project, target_name, package) {
                    Ok(id) => (Some(id), None),
                    Err(err) => return fail(&err.to_string()),
                },
                Err(err) => return fail(&err.to_string()),
            }
        }
    };

    let html_path = args
        .html
        .clone()
        .unwrap_or_else(|| default_html_path(&args.project_dir, parsed_target, package));

    if let Some(parent) = html_path.parent() {
        if let Err(err) = std::fs::create_dir_all(parent) {
            return fail(&format!("could not create {}: {err}", parent.display()));
        }
    }

    let html = crate::lineage_html::generate(
        project,
        adapter.vocabulary(),
        initial_target,
        initial_column,
    );
    if let Err(err) = std::fs::write(&html_path, html) {
        return fail(&format!("could not write {}: {err}", html_path.display()));
    }

    let absolute_path = html_path
        .canonicalize()
        .unwrap_or_else(|_| html_path.to_path_buf());
    let printed = format!(
        "Wrote {} -- open it at {}\n",
        html_path.display(),
        file_url(&absolute_path)
    );
    print!("{printed}");
    crate::log::mirror(&args.project_dir, &printed);
    ExitCode::from(EXIT_OK)
}

/// Builds a `file://` URI a browser can actually open when pasted in,
/// from an absolute path -- correct on both Unix and Windows, unlike a
/// plain `format!("file://{}", path.display())` (what this used to do).
///
/// Two Windows-specific problems that alone: a Windows path never
/// starts with `/` (it starts with a drive letter, `C:\...`), so simply
/// prepending `file://` leaves out the third slash a `file://` URI's
/// authority-less form needs (`file:///C:/...`, not `file://C:/...`);
/// and separately, backslashes are path separators, not valid URI path
/// characters, so they need converting to forward slashes regardless.
/// A third, easy-to-miss problem: `Path::canonicalize()` on Windows
/// returns a `\\?\`-prefixed extended-length path (e.g.
/// `\\?\C:\Users\...`) even for an ordinary path with no special
/// length or reserved-name issue at all -- stripped here before the
/// rest of the conversion, since a browser has no idea what to do with
/// that prefix either.
fn file_url(absolute_path: &Path) -> String {
    let mut path = absolute_path.display().to_string().replace('\\', "/");
    if let Some(stripped) = path.strip_prefix("//?/") {
        path = stripped.to_string();
    }
    if path.starts_with('/') {
        format!("file://{path}")
    } else {
        // A Windows drive-letter path (`C:/Users/...`) has no leading
        // slash of its own to reuse -- file://'s authority-less form
        // needs exactly one more than a Unix absolute path already
        // supplies.
        format!("file:///{path}")
    }
}

/// The `--text` path: prints the plain-text report, same as before HTML
/// became the default.
fn run_text(
    args: &LineageArgs,
    project: &zhao_core::model::ParsedProject,
    adapter: &ResolvedAdapter,
) -> ExitCode {
    let Some((target_name, target_column, direction)) = args.parse_target() else {
        return fail(
            "a target is required for --text output -- omit --text to generate a whole-project HTML graph instead",
        );
    };

    let package = args.package.as_deref();

    // `LineageError`'s own `Display` (via thiserror) already gives a
    // clear, actionable message for every variant -- `UnknownTarget`,
    // `AmbiguousTarget`, `UnknownColumn` alike -- so there's no need to
    // re-derive it per variant here.
    let text = match target_column {
        Some(column) => match trace_column(project, target_name, package, column, direction) {
            Ok(result) => render_column_text(&result, direction, adapter.vocabulary()),
            Err(err) => return fail(&err.to_string()),
        },
        None => match trace(project, target_name, package, direction) {
            Ok(result) => render_text(&result, target_name, direction, adapter.vocabulary()),
            Err(err) => return fail(&err.to_string()),
        },
    };

    print!("{text}");
    crate::log::mirror(&args.project_dir, &text);
    ExitCode::from(EXIT_OK)
}

/// Prints `message` to stderr as `error: {message}` and returns
/// [`EXIT_ERROR`] -- mirrors [`crate::engine::fail`], duplicated rather
/// than shared since `zhao lineage` doesn't otherwise depend on
/// `crate::engine`'s Baseline-diff-specific pipeline.
fn fail(message: &str) -> ExitCode {
    eprintln!("error: {message}");
    ExitCode::from(EXIT_ERROR)
}

/// Renders a [`LineageResult`] as human-readable text: an "Upstream:"
/// section (Nodes and Origins, via `vocabulary`'s own terms), a
/// "Downstream:" section, whichever `direction` didn't exclude -- or a
/// plain "nothing found" line if the included side(s) are genuinely
/// empty, never a bare blank output that could be mistaken for a
/// failure.
fn render_text(
    result: &LineageResult,
    target_name: &str,
    direction: Direction,
    vocabulary: &dyn zhao_core::adapters::AdapterVocabulary,
) -> String {
    let node_term = vocabulary.node_term();
    let origin_term = vocabulary.origin_term();
    let mut out = String::new();

    if matches!(direction, Direction::Upstream | Direction::Both) {
        out.push_str("Upstream:\n");
        if result.upstream_nodes.is_empty() && result.upstream_origins.is_empty() {
            out.push_str("  (none)\n");
        } else {
            for id in &result.upstream_origins {
                out.push_str(&format!("  {origin_term} {id}\n"));
            }
            for id in &result.upstream_nodes {
                out.push_str(&format!("  {node_term} {id}\n"));
            }
        }
    }

    if matches!(direction, Direction::Downstream | Direction::Both) {
        out.push_str("Downstream:\n");
        if result.downstream_nodes.is_empty() {
            out.push_str("  (none)\n");
        } else {
            for id in &result.downstream_nodes {
                out.push_str(&format!("  {node_term} {id}\n"));
            }
        }
    }

    if out.is_empty() {
        // Only reachable if `direction` somehow excluded both sides,
        // which `LineageArgs::parse_target` never produces -- kept as a
        // defensive fallback so this function can never silently print
        // nothing for a real target.
        out.push_str(&format!("{node_term} {target_name}: nothing found\n"));
    }

    out
}

/// The column-level mirror of [`render_text`]: an "Upstream:"/
/// "Downstream:" section per included side, each listing resolved
/// columns (`<term> <node-id>.<column>`, and Origins via
/// `origin_term()`) plus, separately, any Node reached whose specific
/// column mapping couldn't be resolved -- rendered as `<term> <node-id>
/// (unresolved)` so it's visibly present, never silently dropped or
/// indistinguishable from a fully-traced entry.
fn render_column_text(
    result: &ColumnLineageResult,
    direction: Direction,
    vocabulary: &dyn zhao_core::adapters::AdapterVocabulary,
) -> String {
    let node_term = vocabulary.node_term();
    let origin_term = vocabulary.origin_term();
    let mut out = String::new();

    if matches!(direction, Direction::Upstream | Direction::Both) {
        out.push_str("Upstream:\n");
        if result.upstream_columns.is_empty()
            && result.upstream_origins.is_empty()
            && result.unresolved_upstream_at.is_empty()
        {
            out.push_str("  (none)\n");
        } else {
            for origin_ref in &result.upstream_origins {
                out.push_str(&format!(
                    "  {origin_term} {}.{}\n",
                    origin_ref.origin, origin_ref.column
                ));
            }
            for column_ref in &result.upstream_columns {
                out.push_str(&format!(
                    "  {node_term} {}.{}\n",
                    column_ref.node, column_ref.column
                ));
            }
            for id in &result.unresolved_upstream_at {
                out.push_str(&format!("  {node_term} {id} (unresolved)\n"));
            }
        }
    }

    if matches!(direction, Direction::Downstream | Direction::Both) {
        out.push_str("Downstream:\n");
        if result.downstream_columns.is_empty() && result.unresolved_downstream_at.is_empty() {
            out.push_str("  (none)\n");
        } else {
            for column_ref in &result.downstream_columns {
                out.push_str(&format!(
                    "  {node_term} {}.{}\n",
                    column_ref.node, column_ref.column
                ));
            }
            for id in &result.unresolved_downstream_at {
                out.push_str(&format!("  {node_term} {id} (unresolved)\n"));
            }
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use zhao_core::adapters::dbt::DbtVocabulary;
    use zhao_core::model::{NodeId, OriginId};

    // -----------------------------------------------------------------
    // `file_url` -- a correct file:// URI on both Unix and Windows.
    // -----------------------------------------------------------------

    #[test]
    fn a_unix_absolute_path_gets_exactly_one_more_leading_slash() {
        assert_eq!(
            file_url(Path::new(
                "/Users/allen/project/target/zhao/full_lineage.html"
            )),
            "file:///Users/allen/project/target/zhao/full_lineage.html"
        );
    }

    #[test]
    fn a_windows_drive_letter_path_gets_forward_slashes_and_a_triple_slash_prefix() {
        assert_eq!(
            file_url(Path::new(
                r"C:\Users\allen\project\target\zhao\full_lineage.html"
            )),
            "file:///C:/Users/allen/project/target/zhao/full_lineage.html"
        );
    }

    /// `Path::canonicalize()` on Windows returns a `\\?\`-prefixed
    /// extended-length path even for an ordinary path -- this must be
    /// stripped, not just have its backslashes swapped, or the URI
    /// would end up as the nonsensical `file:////?/C:/...`.
    #[test]
    fn a_windows_extended_length_path_prefix_is_stripped() {
        assert_eq!(
            file_url(Path::new(
                r"\\?\C:\Users\allen\project\target\zhao\full_lineage.html"
            )),
            "file:///C:/Users/allen/project/target/zhao/full_lineage.html"
        );
    }

    // -----------------------------------------------------------------
    // `default_html_path` -- the filenaming table from issue #38.
    // -----------------------------------------------------------------

    #[test]
    fn no_target_defaults_to_full_lineage() {
        let path = default_html_path(Path::new("."), None, None);
        assert_eq!(
            path,
            PathBuf::from("./target/zhao/lineage_graphs/full_lineage.html")
        );
    }

    #[test]
    fn a_bare_model_target_defaults_to_partial_lineage_model() {
        let path = default_html_path(
            Path::new("."),
            Some(("dim_customers", None, Direction::Both)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from("./target/zhao/lineage_graphs/partial_lineage_dim_customers.html")
        );
    }

    #[test]
    fn an_upstream_only_target_gets_the_upstream_only_suffix() {
        let path = default_html_path(
            Path::new("."),
            Some(("dim_customers", None, Direction::Upstream)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from(
                "./target/zhao/lineage_graphs/partial_lineage_dim_customers_upstream_only.html"
            )
        );
    }

    #[test]
    fn a_downstream_only_target_gets_the_downstream_only_suffix() {
        let path = default_html_path(
            Path::new("."),
            Some(("dim_customers", None, Direction::Downstream)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from(
                "./target/zhao/lineage_graphs/partial_lineage_dim_customers_downstream_only.html"
            )
        );
    }

    #[test]
    fn a_column_target_appends_the_column_name() {
        let path = default_html_path(
            Path::new("."),
            Some(("dim_customers", Some("customer_id"), Direction::Both)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from(
                "./target/zhao/lineage_graphs/partial_lineage_dim_customers_customer_id.html"
            )
        );
    }

    #[test]
    fn a_column_target_with_upstream_only_appends_column_then_direction() {
        let path = default_html_path(
            Path::new("."),
            Some(("dim_customers", Some("customer_id"), Direction::Upstream)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from(
                "./target/zhao/lineage_graphs/partial_lineage_dim_customers_customer_id_upstream_only.html"
            )
        );
    }

    #[test]
    fn a_package_flag_prepends_the_package_name() {
        let path = default_html_path(
            Path::new("."),
            Some(("customers", None, Direction::Both)),
            Some("pkg_b"),
        );
        assert_eq!(
            path,
            PathBuf::from("./target/zhao/lineage_graphs/partial_lineage_pkg_b_customers.html")
        );
    }

    #[test]
    fn no_package_flag_never_adds_a_package_segment() {
        let path = default_html_path(
            Path::new("."),
            Some(("customers", None, Direction::Both)),
            None,
        );
        assert_eq!(
            path,
            PathBuf::from("./target/zhao/lineage_graphs/partial_lineage_customers.html")
        );
    }

    #[test]
    fn no_target_ignores_package_since_theres_nothing_to_scope() {
        let path = default_html_path(Path::new("."), None, Some("pkg_b"));
        assert_eq!(
            path,
            PathBuf::from("./target/zhao/lineage_graphs/full_lineage.html")
        );
    }

    #[test]
    fn render_text_lists_both_sections_for_both_directions() {
        let result = LineageResult {
            upstream_nodes: vec![NodeId::new("model.p.a")],
            upstream_origins: vec![OriginId::new("source.p.raw")],
            downstream_nodes: vec![NodeId::new("model.p.c")],
        };
        let text = render_text(&result, "b", Direction::Both, &DbtVocabulary);

        assert!(text.contains("Upstream:\n"), "{text}");
        assert!(text.contains("  source source.p.raw\n"), "{text}");
        assert!(text.contains("  model model.p.a\n"), "{text}");
        assert!(text.contains("Downstream:\n"), "{text}");
        assert!(text.contains("  model model.p.c\n"), "{text}");
    }

    #[test]
    fn render_text_omits_the_downstream_section_for_upstream_only() {
        let result = LineageResult {
            upstream_nodes: vec![NodeId::new("model.p.a")],
            upstream_origins: Vec::new(),
            downstream_nodes: Vec::new(),
        };
        let text = render_text(&result, "b", Direction::Upstream, &DbtVocabulary);

        assert!(text.contains("Upstream:\n"), "{text}");
        assert!(!text.contains("Downstream:\n"), "{text}");
    }

    #[test]
    fn render_text_omits_the_upstream_section_for_downstream_only() {
        let result = LineageResult {
            upstream_nodes: Vec::new(),
            upstream_origins: Vec::new(),
            downstream_nodes: vec![NodeId::new("model.p.c")],
        };
        let text = render_text(&result, "b", Direction::Downstream, &DbtVocabulary);

        assert!(!text.contains("Upstream:\n"), "{text}");
        assert!(text.contains("Downstream:\n"), "{text}");
    }

    #[test]
    fn render_text_reports_none_for_an_empty_included_side_not_a_blank_output() {
        let result = LineageResult::default();
        let text = render_text(&result, "isolated", Direction::Both, &DbtVocabulary);

        assert!(text.contains("Upstream:\n  (none)\n"), "{text}");
        assert!(text.contains("Downstream:\n  (none)\n"), "{text}");
    }

    #[test]
    fn render_column_text_lists_resolved_columns_and_origins() {
        let result = ColumnLineageResult {
            upstream_columns: vec![zhao_core::lineage::ColumnRef {
                node: NodeId::new("model.p.a"),
                column: zhao_core::model::ColumnName::new("x"),
            }],
            upstream_origins: vec![zhao_core::lineage::OriginColumnRef {
                origin: OriginId::new("source.p.raw"),
                column: zhao_core::model::ColumnName::new("x"),
            }],
            unresolved_upstream_at: Vec::new(),
            downstream_columns: vec![zhao_core::lineage::ColumnRef {
                node: NodeId::new("model.p.c"),
                column: zhao_core::model::ColumnName::new("x"),
            }],
            unresolved_downstream_at: Vec::new(),
        };
        let text = render_column_text(&result, Direction::Both, &DbtVocabulary);

        assert!(text.contains("  source source.p.raw.x\n"), "{text}");
        assert!(text.contains("  model model.p.a.x\n"), "{text}");
        assert!(text.contains("  model model.p.c.x\n"), "{text}");
    }

    /// Acceptance criterion: an unresolved column is visibly reported,
    /// distinguishable from a fully-resolved entry -- never silently
    /// dropped or indistinguishable from "nothing here."
    #[test]
    fn render_column_text_reports_unresolved_nodes_distinctly() {
        let result = ColumnLineageResult {
            upstream_columns: Vec::new(),
            upstream_origins: Vec::new(),
            unresolved_upstream_at: vec![NodeId::new("model.p.b")],
            downstream_columns: Vec::new(),
            unresolved_downstream_at: Vec::new(),
        };
        let text = render_column_text(&result, Direction::Upstream, &DbtVocabulary);

        assert!(text.contains("  model model.p.b (unresolved)\n"), "{text}");
        assert!(
            !text.contains("(none)"),
            "an unresolved entry means this side isn't genuinely empty: {text}"
        );
    }

    #[test]
    fn render_column_text_reports_none_when_genuinely_empty() {
        let result = ColumnLineageResult::default();
        let text = render_column_text(&result, Direction::Both, &DbtVocabulary);

        assert!(text.contains("Upstream:\n  (none)\n"), "{text}");
        assert!(text.contains("Downstream:\n  (none)\n"), "{text}");
    }
}