harn-cli 0.7.47

CLI for the Harn programming language — run, test, REPL, format, and lint
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use harn_lexer::Lexer;
use harn_modules::resolve_import_path;
use harn_parser::{Parser, SNode};

use crate::package::CheckConfig;

use super::bundle::build_bundle_manifest;
use super::check_cmd::check_file_inner;
use super::config::collect_harn_targets;
use super::config::{build_module_graph, collect_cross_file_imports};
use super::host_capabilities::parse_host_capability_value;
use super::preflight::{collect_preflight_diagnostics, is_preflight_allowed};

fn parse_program(source: &str) -> Vec<SNode> {
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().expect("tokenize");
    let mut parser = Parser::new(tokens);
    parser.parse().expect("parse")
}

fn unique_temp_dir(prefix: &str) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    std::env::temp_dir().join(format!("{prefix}-{nanos}"))
}

#[test]
fn preflight_reports_template_syntax_error() {
    let dir = unique_temp_dir("harn-check-tpl");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    // Unterminated `{{ for }}` block.
    std::fs::write(dir.join("broken.prompt"), "{{ for x in xs }}oops\n").unwrap();
    let source = r#"
pipeline main() {
  let text = render("broken.prompt")
  println(text)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics.iter().any(|d| d
            .message
            .contains("template 'broken.prompt' has a syntax error")),
        "expected template-syntax diagnostic, got {} messages",
        diagnostics.len()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_missing_literal_render_target() {
    let dir = unique_temp_dir("harn-check");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let text = render("missing.txt")
  println(text)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert_eq!(diagnostics.len(), 1);
    assert!(diagnostics[0].message.contains("render target"));
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: `render_prompt(...)` literal-string targets
/// must be validated alongside `render(...)`, the diagnostic must name
/// the actual builtin (`render_prompt`), and the resolved candidate path
/// must be visible so the author can see exactly where the lookup tried
/// to land.
#[test]
fn preflight_reports_missing_literal_render_prompt_target() {
    let dir = unique_temp_dir("harn-check-render-prompt");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("chat.harn");
    let source = r#"
pub fn chat() -> string {
  let trimmed = "hello"
  return render_prompt("lane-classifier.harn.prompt", {task: trimmed})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert_eq!(diagnostics.len(), 1);
    let diag = &diagnostics[0];
    assert!(
        diag.message.contains("render_prompt target"),
        "expected diagnostic to name render_prompt, got: {}",
        diag.message
    );
    assert!(
        diag.message.contains("lane-classifier.harn.prompt"),
        "expected diagnostic to include the literal path, got: {}",
        diag.message
    );
    assert!(
        diag.message.contains(
            &dir.join("lane-classifier.harn.prompt")
                .display()
                .to_string()
        ),
        "expected diagnostic to include the resolved candidate path, got: {}",
        diag.message
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: dynamic first arguments are not statically
/// checkable, so `render_prompt(some_var, ...)` must be silently
/// skipped — no false positives on legitimate dynamic dispatch.
#[test]
fn preflight_skips_non_literal_render_prompt_target() {
    let dir = unique_temp_dir("harn-check-render-dynamic");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let path = "missing.harn.prompt"
  let prompt = render_prompt(path, {})
  let key = "1"
  let interp = render_prompt("missing_${key}.prompt", {})
  println(prompt + interp)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("render_prompt target")),
        "dynamic first args must not produce render-target diagnostics, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: raw string literals (`r"foo"`) are still
/// statically known and must be validated like ordinary string literals.
#[test]
fn preflight_reports_missing_render_prompt_target_for_raw_string() {
    let dir = unique_temp_dir("harn-check-render-raw");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt(r"missing.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("render_prompt target")),
        "raw string literal must trigger preflight check, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: the diagnostic span must point at the
/// literal-string argument, not the whole `render_prompt(...)`
/// expression — this is what enables an editor's quick-fix to jump
/// straight to the path that needs editing.
#[test]
fn preflight_render_prompt_diagnostic_spans_literal_argument() {
    let dir = unique_temp_dir("harn-check-render-span");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt("missing.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let render_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("render_prompt target"))
        .expect("expected render_prompt target diagnostic");
    let span_text = &source[render_diag.span.start..render_diag.span.end];
    assert_eq!(
        span_text, "\"missing.prompt\"",
        "expected diagnostic span to cover only the literal-string argument"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: `@/<rel>` forms must resolve through the
/// same `harn_modules::asset_paths` logic the runtime uses, so a missing
/// project-root prompt fails the static check.
#[test]
fn preflight_reports_missing_project_root_asset_path() {
    let dir = unique_temp_dir("harn-check-asset-projroot");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("harn.toml"), "[package]\nname = \"x\"\n").unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt("@/prompts/missing.harn.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let render_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("render_prompt target"))
        .expect("expected render_prompt target diagnostic for missing @/ asset");
    assert!(
        render_diag.message.contains(
            &dir.join("prompts/missing.harn.prompt")
                .display()
                .to_string()
        ),
        "expected diagnostic to surface the resolved project-root path, got: {}",
        render_diag.message
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: `@<alias>/<rel>` with an unknown alias
/// must surface the asset-resolver's structural error so the user sees
/// the missing `[asset_roots]` entry, not a generic file-existence
/// message.
#[test]
fn preflight_reports_unknown_asset_alias() {
    let dir = unique_temp_dir("harn-check-asset-alias");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("harn.toml"), "[package]\nname = \"x\"\n").unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt("@unknown/foo.harn.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let alias_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("[asset_roots]"))
        .expect("expected unknown-alias diagnostic citing [asset_roots]");
    assert!(
        alias_diag.message.contains("unknown"),
        "expected diagnostic to name the missing alias, got: {}",
        alias_diag.message
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: a defined `@<alias>/<rel>` resolves
/// through the same logic the runtime uses, so a missing file under the
/// alias is still flagged.
#[test]
fn preflight_reports_missing_aliased_asset_path() {
    let dir = unique_temp_dir("harn-check-asset-alias-missing");
    std::fs::create_dir_all(dir.join("src/prompts")).unwrap();
    std::fs::write(
        dir.join("harn.toml"),
        "[package]\nname = \"x\"\n[asset_roots]\npartials = \"src/prompts\"\n",
    )
    .unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt("@partials/missing.harn.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let render_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("render_prompt target"))
        .expect("expected render_prompt target diagnostic for missing aliased asset");
    assert!(
        render_diag.message.contains(
            &dir.join("src/prompts/missing.harn.prompt")
                .display()
                .to_string()
        ),
        "expected diagnostic to surface the alias-resolved path, got: {}",
        render_diag.message
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771 (the burin-code repro): when the missing
/// prompt file exists elsewhere under the same project root, the
/// diagnostic must include a "did you mean ...?" suggestion pointing at
/// the misfiled location — that's the one-keystroke fix the issue is
/// asking for.
#[test]
fn preflight_suggests_misfiled_render_prompt_target() {
    let dir = unique_temp_dir("harn-check-render-suggest");
    std::fs::create_dir_all(dir.join("lib/runtime")).unwrap();
    std::fs::create_dir_all(dir.join("lib/mode")).unwrap();
    std::fs::write(dir.join("harn.toml"), "[package]\nname = \"x\"\n").unwrap();
    std::fs::write(
        dir.join("lib/mode/lane-classifier.harn.prompt"),
        "task: {{task}}\n",
    )
    .unwrap();
    let file = dir.join("lib/runtime/chat.harn");
    let source = r#"
pub fn chat() -> string {
  return render_prompt("lane-classifier.harn.prompt", {task: "hi"})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let render_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("render_prompt target"))
        .expect("expected render_prompt target diagnostic");
    let help = render_diag
        .help
        .as_ref()
        .expect("expected diagnostic help text");
    assert!(
        help.contains("did you mean"),
        "expected help text to include 'did you mean' suggestion, got: {help}",
    );
    assert!(
        help.contains("lib/mode/lane-classifier.harn.prompt"),
        "expected help text to point at the misfiled location, got: {help}",
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// Acceptance for issue #771: when no near-miss exists, the diagnostic
/// must still emit useful generic guidance instead of the misleading
/// "did you mean ..." prefix.
#[test]
fn preflight_omits_did_you_mean_when_no_near_miss() {
    let dir = unique_temp_dir("harn-check-render-no-suggest");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("harn.toml"), "[package]\nname = \"x\"\n").unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let prompt = render_prompt("nowhere.harn.prompt", {})
  println(prompt)
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    let render_diag = diagnostics
        .iter()
        .find(|d| d.message.contains("render_prompt target"))
        .expect("expected render_prompt target diagnostic");
    let help = render_diag
        .help
        .as_ref()
        .expect("expected diagnostic help text");
    assert!(
        !help.contains("did you mean"),
        "expected no 'did you mean' when there's no near-miss, got: {help}",
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_resolves_imports_with_implicit_harn_extension() {
    let dir = unique_temp_dir("harn-check");
    std::fs::create_dir_all(dir.join("lib")).unwrap();
    std::fs::write(dir.join("lib").join("helpers.harn"), "pub fn x() { 1 }\n").unwrap();
    let file = dir.join("main.harn");
    let resolved = resolve_import_path(&file, "lib/helpers");
    assert_eq!(resolved, Some(dir.join("lib").join("helpers.harn")));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_missing_worker_execution_repo() {
    let dir = unique_temp_dir("harn-check-worker");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  spawn_agent({
    task: "do it",
    node: {kind: "stage"},
    execution: {worktree: {repo: "./missing-repo"}}
  })
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert_eq!(diagnostics.len(), 1);
    assert!(diagnostics[0].message.contains("worktree repo"));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_detects_import_collision() {
    let dir = unique_temp_dir("harn-check-collision");
    std::fs::create_dir_all(dir.join("lib")).unwrap();
    std::fs::write(dir.join("lib").join("a.harn"), "pub fn helper() { 1 }\n").unwrap();
    std::fs::write(dir.join("lib").join("b.harn"), "pub fn helper() { 2 }\n").unwrap();
    let file = dir.join("main.harn");
    let source = r#"
import "lib/a.harn"
import "lib/b.harn"

pipeline main() {
  log(helper())
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("import collision")),
        "expected import collision diagnostic, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_no_collision_with_selective_imports() {
    let dir = unique_temp_dir("harn-check-selective");
    std::fs::create_dir_all(dir.join("lib")).unwrap();
    std::fs::write(
        dir.join("lib").join("a.harn"),
        "pub fn foo() { 1 }\npub fn shared() { 2 }\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("lib").join("b.harn"),
        "pub fn bar() { 3 }\npub fn shared() { 4 }\n",
    )
    .unwrap();
    let file = dir.join("main.harn");
    let source = r#"
import { foo } from "lib/a.harn"
import { bar } from "lib/b.harn"

pipeline main() {
  log(foo())
  log(bar())
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("import collision")),
        "unexpected collision: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_unknown_host_capability() {
    let dir = unique_temp_dir("harn-check-host");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_call("unknown_cap.do_stuff", {})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("unknown host capability")),
        "expected unknown host capability diagnostic, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_tool_define_unknown_host_capability() {
    // harn#743: a host_bridge tool's host_capability binding is
    // validated against the same capability map host_call uses, so
    // typos surface during `harn check` rather than at first model
    // call.
    let dir = unique_temp_dir("harn-check-tool-define-cap");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let r = tool_registry()
  tool_define(
    r,
    "ask_user",
    "Ask the user",
    {
      parameters: {prompt: "string"},
      executor: "host_bridge",
      host_capability: "interaction.unknown_op",
    },
  )
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("interaction.unknown_op")
                && d.message.contains("not declared by the host")),
        "expected tool_define host_capability diagnostic, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_accepts_tool_define_known_host_capability() {
    let dir = unique_temp_dir("harn-check-tool-define-cap-ok");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let r = tool_registry()
  tool_define(
    r,
    "ask_user",
    "Ask the user",
    {
      parameters: {prompt: "string"},
      executor: "host_bridge",
      host_capability: "interaction.ask",
    },
  )
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("not declared by the host")),
        "unexpected diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_tool_define_host_bridge_missing_capability() {
    let dir = unique_temp_dir("harn-check-tool-define-missing");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let r = tool_registry()
  tool_define(
    r,
    "ask_user",
    "Ask the user",
    {parameters: {prompt: "string"}, executor: "host_bridge"},
  )
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("no `host_capability` binding")),
        "expected missing-capability diagnostic, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_reports_tool_define_unknown_executor_value() {
    let dir = unique_temp_dir("harn-check-tool-define-executor");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let r = tool_registry()
  tool_define(
    r,
    "fly",
    "Fly",
    {parameters: {distance: "int"}, executor: "rocketship"},
  )
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("unknown executor \"rocketship\"")),
        "expected unknown-executor diagnostic, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_accepts_known_host_capabilities() {
    let dir = unique_temp_dir("harn-check-host-ok");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_call("project.metadata_get", {dir: ".", namespace: "facts"})
  host_call("process.exec", {command: "ls"})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("unknown host capability")),
        "unexpected host cap diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn check_file_inner_enforces_invariants_when_requested() {
    let dir = unique_temp_dir("harn-check-invariants");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    std::fs::write(
        &file,
        r#"
@invariant("fs.writes", "src/**")
fn handler() {
  write_file("/tmp/out.txt", "unsafe")
}
"#,
    )
    .unwrap();

    let files = vec![file.clone()];
    let module_graph = build_module_graph(&files);
    let cross_file_imports = collect_cross_file_imports(&module_graph);
    let outcome = check_file_inner(
        &file,
        &CheckConfig::default(),
        &cross_file_imports,
        &module_graph,
        true,
    );

    assert!(
        outcome.has_error,
        "expected invariant violation to fail check"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn check_file_inner_skips_invariants_when_disabled() {
    let dir = unique_temp_dir("harn-check-invariants-off");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    std::fs::write(
        &file,
        r#"
@invariant("fs.writes", "src/**")
fn handler() {
  write_file("/tmp/out.txt", "unsafe")
}
"#,
    )
    .unwrap();

    let files = vec![file.clone()];
    let module_graph = build_module_graph(&files);
    let cross_file_imports = collect_cross_file_imports(&module_graph);
    let outcome = check_file_inner(
        &file,
        &CheckConfig::default(),
        &cross_file_imports,
        &module_graph,
        false,
    );

    assert!(
        !outcome.has_error,
        "invariants should only run behind --invariants"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_accepts_extended_host_capabilities_from_config() {
    let dir = unique_temp_dir("harn-check-host-extended");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_call("project.scan", {})
  host_call("runtime.set_result", {})
}
"#;
    let program = parse_program(source);
    let diagnostics = collect_preflight_diagnostics(
        &file,
        source,
        &program,
        &CheckConfig {
            host_capabilities: HashMap::from([
                ("project".to_string(), vec!["scan".to_string()]),
                ("runtime".to_string(), vec!["set_result".to_string()]),
            ]),
            ..CheckConfig::default()
        },
    );
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("unknown host capability")),
        "unexpected host cap diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_accepts_runtime_task_and_session_ops() {
    let dir = unique_temp_dir("harn-check-host-runtime");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_call("runtime.task", {})
  host_call("session.changed_paths", {})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("unknown host capability")),
        "unexpected host cap diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_accepts_host_operations_registered_via_host_mock() {
    let dir = unique_temp_dir("harn-check-host-mock");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_mock("project", "metadata_get", {result: {value: "facts"}})
  host_call("project.metadata_get", {dir: "pkg"})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("unknown host capability")),
        "unexpected host cap diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn collect_harn_targets_recurses_directories_and_deduplicates() {
    let dir = unique_temp_dir("harn-check-targets");
    std::fs::create_dir_all(dir.join("nested")).unwrap();
    std::fs::write(dir.join("a.harn"), "pipeline a() {}\n").unwrap();
    std::fs::write(dir.join("nested").join("b.harn"), "pipeline b() {}\n").unwrap();
    std::fs::write(dir.join("nested").join("ignore.txt"), "x\n").unwrap();

    let target_dir = dir.display().to_string();
    let target_file = dir.join("a.harn").display().to_string();
    let files = collect_harn_targets(&[target_dir.as_str(), target_file.as_str()]);

    assert_eq!(files.len(), 2);
    assert!(files.contains(&dir.join("a.harn")));
    assert!(files.contains(&dir.join("nested").join("b.harn")));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn parse_host_capability_value_accepts_top_level_object_schema() {
    let value = serde_json::json!({
        "workspace": ["project_root", "file_exists"],
        "runtime": {
            "operations": ["task", "pipeline_input"]
        }
    });
    let parsed = parse_host_capability_value(&value);
    assert!(parsed["workspace"].contains("project_root"));
    assert!(parsed["workspace"].contains("file_exists"));
    assert!(parsed["runtime"].contains("task"));
    assert!(parsed["runtime"].contains("pipeline_input"));
}

#[test]
fn preflight_accepts_render_target_from_bundle_root() {
    let dir = unique_temp_dir("harn-check-bundle-root");
    std::fs::create_dir_all(dir.join("bundle")).unwrap();
    std::fs::write(dir.join("bundle").join("shared.prompt"), "hello").unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  let text = render("shared.prompt")
  println(text)
}
"#;
    let program = parse_program(source);
    let diagnostics = collect_preflight_diagnostics(
        &file,
        source,
        &program,
        &CheckConfig {
            bundle_root: Some(dir.join("bundle").display().to_string()),
            ..CheckConfig::default()
        },
    );
    assert!(
        diagnostics
            .iter()
            .all(|d| !d.message.contains("render target")),
        "unexpected render diagnostic: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_validates_render_in_imported_module() {
    let dir = unique_temp_dir("harn-check-import-render");
    std::fs::create_dir_all(dir.join("lib")).unwrap();
    // Module references a template that doesn't exist
    std::fs::write(
        dir.join("lib").join("tmpl.harn"),
        "pub fn load() { render(\"missing_template.txt\") }\n",
    )
    .unwrap();
    let file = dir.join("main.harn");
    let source = r#"
import "lib/tmpl.harn"

pipeline main() {
  log(load())
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.message.contains("render target")),
        "expected render target diagnostic for imported module, got: {:?}",
        diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn bundle_manifest_tracks_prompt_assets_host_caps_and_worktree_repos() {
    let dir = unique_temp_dir("harn-check-bundle-manifest");
    std::fs::create_dir_all(dir.join("prompts")).unwrap();
    std::fs::create_dir_all(dir.join("shared")).unwrap();
    std::fs::create_dir_all(dir.join("lib")).unwrap();
    std::fs::write(dir.join("prompts").join("review.harn.prompt"), "review").unwrap();
    std::fs::write(dir.join("shared").join("snippet.prompt"), "snippet").unwrap();
    std::fs::write(
        dir.join("lib").join("helper.harn"),
        r#"
pub fn helper() -> string {
  return "ok"
}
"#,
    )
    .unwrap();
    std::fs::write(
        dir.join("main.harn"),
        r#"
import "lib/helper.harn"

pipeline main() {
  let review = render_prompt("prompts/review.harn.prompt")
  let snippet = render("shared/snippet.prompt")
  host_call("project.scan", {})
  exec_at("shared", "pwd")
  spawn_agent({
    task: "scan",
    node: {kind: "stage"},
    execution: {worktree: {repo: "./repo"}}
  })
  println(review + snippet)
}
"#,
    )
    .unwrap();
    let manifest = build_bundle_manifest(&[dir.join("main.harn")], &CheckConfig::default());
    assert_eq!(
        manifest["entry_modules"].as_array().map(|v| v.len()),
        Some(1)
    );
    assert_eq!(
        manifest["import_modules"].as_array().map(|v| v.len()),
        Some(1)
    );
    assert!(manifest["module_dependencies"]
        .as_array()
        .expect("module dependencies")
        .iter()
        .any(|edge| edge["from"]
            .as_str()
            .is_some_and(|value| value.ends_with("/main.harn"))
            && edge["to"]
                .as_str()
                .is_some_and(|value| value.ends_with("/lib/helper.harn"))));
    let assets = manifest["assets"].as_array().expect("assets array");
    assert!(assets.iter().any(|asset| {
        asset["kind"] == "prompt_asset"
            && asset["via"] == "render_prompt"
            && asset["target"] == "prompts/review.harn.prompt"
    }));
    assert!(assets.iter().any(|asset| {
        asset["kind"] == "prompt_asset"
            && asset["via"] == "render"
            && asset["target"] == "shared/snippet.prompt"
    }));
    assert!(manifest["prompt_assets"]
        .as_array()
        .expect("prompt assets")
        .iter()
        .any(|entry| entry
            .as_str()
            .is_some_and(|value| value.ends_with("/prompts/review.harn.prompt"))));
    assert!(manifest["prompt_assets"]
        .as_array()
        .expect("prompt assets")
        .iter()
        .any(|entry| entry
            .as_str()
            .is_some_and(|value| value.ends_with("/shared/snippet.prompt"))));
    assert_eq!(manifest["summary"]["prompt_asset_count"].as_u64(), Some(2));
    assert_eq!(
        manifest["summary"]["module_dependency_count"].as_u64(),
        Some(1)
    );
    assert_eq!(manifest["required_host_capabilities"]["project"][0], "scan");
    assert!(manifest["execution_dirs"]
        .as_array()
        .expect("execution dirs")
        .iter()
        .any(|entry| entry
            .as_str()
            .is_some_and(|value| value.ends_with("/shared"))));
    assert!(manifest["worktree_repos"]
        .as_array()
        .expect("worktree repos")
        .iter()
        .any(|entry| entry.as_str().is_some_and(|value| value.ends_with("/repo"))));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn unknown_host_capability_diagnostic_carries_tag() {
    let dir = unique_temp_dir("harn-check-host-tag");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("main.harn");
    let source = r#"
pipeline main() {
  host_call("custom_cap.do_thing", {})
}
"#;
    let program = parse_program(source);
    let diagnostics =
        collect_preflight_diagnostics(&file, source, &program, &CheckConfig::default());
    assert!(
        diagnostics
            .iter()
            .any(|d| d.tags.as_deref() == Some("custom_cap.do_thing")),
        "expected tagged diagnostic, got: {:?}",
        diagnostics
            .iter()
            .map(|d| (d.message.clone(), d.tags.clone()))
            .collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn preflight_allow_matches_exact_wildcard_and_capability_scope() {
    let exact = Some("project.scan".to_string());
    let other_op = Some("project.refresh".to_string());
    let other_cap = Some("editor.get_selection".to_string());

    // Exact match
    assert!(is_preflight_allowed(&exact, &["project.scan".to_string()]));
    // `project.*` wildcard matches any op in the project capability
    assert!(is_preflight_allowed(&other_op, &["project.*".to_string()]));
    // Bare capability name also matches any op in that capability
    assert!(is_preflight_allowed(&other_op, &["project".to_string()]));
    // `*` blanket match
    assert!(is_preflight_allowed(&exact, &["*".to_string()]));
    // No match when capability differs
    assert!(!is_preflight_allowed(
        &other_cap,
        &["project.*".to_string()]
    ));
    // Untagged diagnostics never match
    assert!(!is_preflight_allowed(&None, &["*".to_string()]));
}

#[test]
fn check_lint_reports_missing_harndoc_for_public_functions() {
    let source = r#"
pub fn exposed() -> string {
  return "x"
}
"#;
    let program = parse_program(source);
    let diagnostics = harn_lint::lint_with_config_and_source(
        &program,
        &CheckConfig::default().disable_rules,
        Some(source),
    );
    assert!(
        diagnostics.iter().any(|d| d.rule == "missing-harndoc"),
        "expected missing-harndoc warning, got: {:?}",
        diagnostics.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );
}