harn-parser 0.7.55

Parser, AST, and type checker for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Basic typing: literals, fn / pipeline signatures, generics, type aliases, variance.

use super::*;

#[test]
fn test_no_errors_for_untyped_code() {
    let errs = errors("pipeline t(task) { let x = 42\nlog(x) }");
    assert!(errs.is_empty());
}

#[test]
fn test_correct_typed_let() {
    let errs = errors("pipeline t(task) { let x: int = 42 }");
    assert!(errs.is_empty());
}

#[test]
fn test_type_mismatch_let() {
    let errs = errors(r#"pipeline t(task) { let x: int = "hello" }"#);
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("expected int"));
    assert!(errs[0].contains("found string"));
}

#[test]
fn test_match_expression_infers_common_arm_type() {
    let errs = errors(
        r#"pipeline t(task) {
  let input = "b"
  let value: string = match input {
    "a" -> { "alpha" }
    "b" -> {
      let suffix = "ravo"
      "b" + suffix
    }
    _ -> { "other" }
  }
}"#,
    );
    assert!(errs.is_empty(), "unexpected errors: {errs:?}");
}

#[test]
fn test_match_expression_assignment_uses_arm_value_type() {
    let errs = errors(
        r#"pipeline t(task) {
  let input = "a"
  let value: int = match input {
    "a" -> { "alpha" }
    _ -> { "other" }
  }
}"#,
    );
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("expected int"));
    assert!(errs[0].contains("found string"));
}

#[test]
fn test_match_expression_mixed_arms_infer_union() {
    let errs = errors(
        r#"pipeline t(task) {
  let input = "a"
  let value: string | int = match input {
    "a" -> { "alpha" }
    _ -> { 42 }
  }
}"#,
    );
    assert!(errs.is_empty(), "unexpected errors: {errs:?}");
}

#[test]
fn test_match_expression_infers_list_pattern_binding_type() {
    let errs = errors(
        r#"pipeline t(task) {
  let pair = [10, 20]
  let value: string = match pair {
    [_, item] -> { item }
    _ -> { 0 }
  }
}"#,
    );
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("expected string"));
    assert!(errs[0].contains("found int"));
}

#[test]
fn test_correct_typed_fn() {
    let errs =
        errors("pipeline t(task) { fn add(a: int, b: int) -> int { return a + b }\nadd(1, 2) }");
    assert!(errs.is_empty());
}

#[test]
fn test_flow_predicate_mode_attributes_are_recognized_on_functions() {
    let warns = warnings(
        r#"
@deterministic
fn pure_check(slice) -> bool { return true }

@semantic
fn semantic_check(slice) -> bool { return true }
"#,
    );
    assert!(
        warns
            .iter()
            .all(|warning| !warning.contains("unknown attribute")),
        "predicate mode attributes should not warn as unknown: {warns:?}"
    );
}

#[test]
fn test_runtime_attributes_are_recognized_on_valid_declarations() {
    let warns = warnings(
        r#"
@test
pipeline smoke(task) {}

@acp_skill(name: "deploy", when_to_use: "ship", invocation: "explicit")
fn deploy_activate() -> string { return "ready" }
"#,
    );
    assert!(
        warns
            .iter()
            .all(|warning| !warning.contains("unknown attribute")
                && !warning.contains("only applies")),
        "runtime attributes should not warn on valid declarations: {warns:?}"
    );
}

#[test]
fn test_durable_persona_annotations_are_recognized_and_validated() {
    let warns = warnings(
        r#"
@persona(
  triggers: [github.pr_opened, schedule("*/30 * * * *")],
  tools: [github, ci, linear],
  autonomy: act_with_approval,
  budget: {daily_usd: 20, frontier_escalations: 3},
  handoffs: [review_captain, human_maintainer],
  receipts: required,
)
@trigger(github.check_failed)
@handoff(target: review_captain, reason: "risky diff")
@budget(daily_usd: 20, max_tokens: 100000)
fn merge_captain(ctx) -> string { return "ok" }
"#,
    );
    assert!(
        warns
            .iter()
            .all(|warning| !warning.contains("unknown attribute")
                && !warning.contains("only applies")
                && !warning.contains("must")),
        "durable persona annotations should validate cleanly: {warns:?}"
    );
}

#[test]
fn test_durable_persona_annotation_arg_type_warnings() {
    let warns = warnings(
        r#"
@persona(triggers: "github.pr_opened", tools: [github, 1], budget: {daily_usd: "twenty"})
@budget(max_tokens: "many")
fn bad_persona(ctx) { return ctx }
"#,
    );
    assert!(
        warns
            .iter()
            .any(|warning| warning.contains("`@persona(triggers: ...)` must be a list")),
        "expected persona trigger list warning, got {warns:?}"
    );
    assert!(
        warns
            .iter()
            .any(|warning| warning.contains("`@persona(tools: ...)` must contain only")),
        "expected persona tools warning, got {warns:?}"
    );
    assert!(
        warns
            .iter()
            .any(|warning| warning.contains("`@persona(daily_usd: ...)` must be a number")),
        "expected inline budget warning, got {warns:?}"
    );
    assert!(
        warns
            .iter()
            .any(|warning| warning.contains("`@budget(max_tokens: ...)` must be a number")),
        "expected budget warning, got {warns:?}"
    );
}

#[test]
fn test_command_attribute_recognized_on_pipelines_with_known_args() {
    let warns = warnings(
        r#"
@command(name: "review", description: "Review the diff", hint: "focus area")
pipeline review_branch(task) {}
"#,
    );
    assert!(
        warns.iter().all(|warning| !warning.contains("unknown")
            && !warning.contains("only applies")
            && !warning.contains("must")),
        "@command on a pipeline with known args should validate cleanly: {warns:?}"
    );
}

#[test]
fn test_command_attribute_warns_on_unknown_args() {
    let warns = warnings(
        r#"
@command(label: "oops")
pipeline review_branch(task) {}
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("unknown `@command` argument `label`")),
        "expected unknown-arg warning, got {warns:?}"
    );
}

#[test]
fn test_command_attribute_warns_on_function_decls() {
    let warns = warnings(
        r#"
@command(name: "review")
fn review_branch(task) {}
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("`@command` only applies to pipeline declarations")),
        "expected placement warning, got {warns:?}"
    );
}

#[test]
fn test_flow_predicate_mode_attributes_warn_off_functions() {
    let warns = warnings(
        r#"
@deterministic
pipeline invalid(task) {}
"#,
    );
    assert!(
        warns
            .iter()
            .any(|warning| warning.contains("`@deterministic` only applies to function")),
        "expected placement warning, got {warns:?}"
    );
}

#[test]
fn test_flow_invariant_archivist_attributes_recognized() {
    let warns = warnings(
        r#"
@invariant
@deterministic
@archivist(evidence: ["https://example.com/spec"], confidence: 0.95, source_date: "2026-04-01", coverage_examples: ["case-a"])
@retroactive
fn complete_predicate(slice) -> bool { return true }
"#,
    );
    assert!(
        warns
            .iter()
            .all(|warning| !warning.contains("unknown attribute")),
        "archivist/retroactive attributes should be recognised: {warns:?}"
    );
}

#[test]
fn test_flow_invariant_requires_kind_and_archivist() {
    let warns = warnings(
        r#"
@invariant
fn bare_predicate(slice) -> bool { return true }
"#,
    );
    assert!(
        warns.iter().any(|w| w.contains("requires exactly one of")),
        "expected kind-required warning, got {warns:?}"
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("missing `@archivist(...)`")),
        "expected archivist-required warning, got {warns:?}"
    );
}

#[test]
fn test_flow_invariant_with_kind_only_still_warns_about_archivist() {
    let warns = warnings(
        r#"
@invariant
@deterministic
fn kinded_predicate(slice) -> bool { return true }
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("missing `@archivist(...)`")),
        "expected archivist-required warning, got {warns:?}"
    );
    assert!(
        warns.iter().all(|w| !w.contains("requires exactly one of")),
        "should not also warn about missing kind: {warns:?}"
    );
}

#[test]
fn test_flow_invariant_kinds_are_mutually_exclusive() {
    let warns = warnings(
        r#"
@invariant
@deterministic
@semantic
@archivist(evidence: ["x"])
fn confused(slice) -> bool { return true }
"#,
    );
    assert!(
        warns.iter().any(|w| w.contains("mutually exclusive")),
        "expected mutual-exclusion warning, got {warns:?}"
    );
}

#[test]
fn test_archivist_without_invariant_warns() {
    let warns = warnings(
        r#"
@archivist(evidence: ["https://x"])
fn standalone() -> int { return 1 }
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("only applies to Flow predicates marked")),
        "expected standalone-archivist warning, got {warns:?}"
    );
}

#[test]
fn test_handler_ir_invariant_does_not_trigger_flow_lints() {
    // `@invariant("name")` is the harn-ir handler form, validated
    // separately. Flow lints must not fire for it.
    let warns = warnings(
        r#"
@invariant("approval.reachability")
fn handler() -> int { return 1 }
"#,
    );
    assert!(
        warns
            .iter()
            .all(|w| !w.contains("`@archivist(...)`") && !w.contains("requires exactly one of")),
        "handler-IR @invariant should not trigger Flow lints: {warns:?}"
    );
}

#[test]
fn test_archivist_unknown_arg_warns() {
    let warns = warnings(
        r#"
@invariant
@deterministic
@archivist(evidence: ["x"], typo_key: "oops")
fn oops(slice) -> bool { return true }
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("unknown `@archivist` argument `typo_key`")),
        "expected unknown-arg warning, got {warns:?}"
    );
}

#[test]
fn test_archivist_confidence_out_of_range_warns() {
    let warns = warnings(
        r#"
@invariant
@deterministic
@archivist(evidence: ["x"], confidence: 1.5)
fn loud(slice) -> bool { return true }
"#,
    );
    assert!(
        warns
            .iter()
            .any(|w| w.contains("confidence") && w.contains("[0.0, 1.0]")),
        "expected confidence-range warning, got {warns:?}"
    );
}

#[test]
fn test_fn_arg_type_mismatch() {
    let errs = errors(
        r#"pipeline t(task) { fn add(a: int, b: int) -> int { return a + b }
add("hello", 2) }"#,
    );
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("argument 1 `a`"));
    assert!(errs[0].contains("expected int"));
}

#[test]
fn test_return_type_mismatch() {
    let errs = errors(r#"pipeline t(task) { fn get() -> int { return "hello" } }"#);
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("return value: expected int, found string"));
}

#[test]
fn test_union_type_compatible() {
    let errs = errors(r#"pipeline t(task) { let x: string | nil = nil }"#);
    assert!(errs.is_empty());
}

#[test]
fn test_union_type_mismatch() {
    let errs = errors(r#"pipeline t(task) { let x: string | nil = 42 }"#);
    assert_eq!(errs.len(), 1);
    // Type-checker errors print the canonical sugared form for
    // `T | nil` unions; the source can use either spelling.
    assert!(
        errs[0].contains("expected string?"),
        "expected sugared form in: {}",
        errs[0]
    );
    assert!(errs[0].contains("found int"));
}

#[test]
fn test_var_nil_widens_on_first_concrete_assignment() {
    let errs = errors(
        r#"pipeline t(task) {
  var hit = nil
  hit = {name: "b", score: 2}
  let widened: {name: string, score: int} | nil = hit
  hit = nil
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_var_nil_widens_inside_nil_guard() {
    let errs = errors(
        r#"pipeline t(task) {
  var hit = nil
  if hit == nil {
    hit = {name: "b", score: 2}
  }
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_explicit_nullable_var_annotation_still_accepts_nil_and_concrete() {
    let errs = errors(
        r#"pipeline t(task) {
  var hit: {name: string, score: int} | nil = nil
  hit = {name: "b", score: 2}
  hit = nil
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_explicit_nil_var_does_not_widen() {
    let errs = errors(
        r#"pipeline t(task) {
  var hit: nil = nil
  hit = {name: "b", score: 2}
}"#,
    );
    assert_eq!(errs.len(), 1, "expected 1 error, got: {errs:?}");
    assert!(errs[0].contains("expected nil"), "got: {}", errs[0]);
}

#[test]
fn test_type_inference_propagation() {
    let errs = errors(
        r#"pipeline t(task) {
  fn add(a: int, b: int) -> int { return a + b }
  let result: string = add(1, 2)
}"#,
    );
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("expected string"));
    assert!(errs[0].contains("found int"));
    assert!(errs[0].contains("string"));
    assert!(errs[0].contains("int"));
}

#[test]
fn test_generic_return_type_instantiates_from_callsite() {
    let errs = errors(
        r#"pipeline t(task) {
  fn identity<T>(x: T) -> T { return x }
  fn first<T>(items: list<T>) -> T { return items[0] }
  let n: int = identity(42)
  let s: string = first(["a", "b"])
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_explicit_generic_call_type_args_are_checked() {
    let errs = errors(
        r#"pipeline t(task) {
  fn identity<T>(x: T) -> T { return x }
  let n: int = identity<int>(42)
  let words: [string] = identity<[string]>(["a", "b"])
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_explicit_generic_call_type_args_must_match_arguments() {
    let errs = errors(
        r#"pipeline t(task) {
  fn identity<T>(x: T) -> T { return x }
  let n: int = identity<int>("oops")
}"#,
    );
    assert_eq!(errs.len(), 2, "expected 2 errors, got: {errs:?}");
    assert!(
        errs.iter()
            .any(|err| err.contains("type parameter 'T' was inferred as both int and string")),
        "missing explicit type binding conflict error: {errs:?}"
    );
    assert!(
        errs.iter()
            .any(|err| err.contains("expected int, found string")),
        "missing explicit type-arg mismatch error: {errs:?}"
    );
}

#[test]
fn test_generic_type_param_must_bind_consistently() {
    let errs = errors(
        r#"pipeline t(task) {
  fn keep<T>(a: T, b: T) -> T { return a }
  keep(1, "x")
}"#,
    );
    assert_eq!(errs.len(), 2, "expected 2 errors, got: {:?}", errs);
    assert!(
        errs.iter()
            .any(|err| err.contains("type parameter 'T' was inferred as both int and string")),
        "missing generic binding conflict error: {:?}",
        errs
    );
    assert!(
        errs.iter()
            .any(|err| err.contains("argument 2 `b`: expected int, found string")),
        "missing instantiated argument mismatch error: {:?}",
        errs
    );
}

#[test]
fn test_generic_list_binding_propagates_element_type() {
    let errs = errors(
        r#"pipeline t(task) {
  fn first<T>(items: list<T>) -> T { return items[0] }
  let bad: string = first([1, 2, 3])
}"#,
    );
    assert_eq!(errs.len(), 1, "expected 1 error, got: {:?}", errs);
    assert!(errs[0].contains("expected string, found int"));
}

#[test]
fn test_generic_struct_literal_instantiates_type_arguments() {
    let errs = errors(
        r#"pipeline t(task) {
  struct Pair<A, B> {
first: A
second: B
  }
  let pair: Pair<int, string> = Pair { first: 1, second: "two" }
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_unknown_struct_literal_reports_error() {
    let diagnostics = check_source(
        r#"pipeline t(task) {
  let p = Point {x: 3, y: 4}
}"#,
    );
    let errors: Vec<_> = diagnostics
        .into_iter()
        .filter(|diag| diag.severity == DiagnosticSeverity::Error)
        .collect();
    assert_eq!(errors.len(), 1, "expected one error, got: {errors:?}");
    assert_eq!(errors[0].message, "unknown struct type `Point`");
}

#[test]
fn test_unknown_struct_literal_suggests_close_match() {
    let diagnostics = check_source(
        r#"pipeline t(task) {
  struct Point {
    x: int
    y: int
  }

  let p = Piont {x: 3, y: 4}
}"#,
    );
    let errors: Vec<_> = diagnostics
        .into_iter()
        .filter(|diag| diag.severity == DiagnosticSeverity::Error)
        .collect();
    assert_eq!(errors.len(), 1, "expected one error, got: {errors:?}");
    assert_eq!(
        errors[0].message,
        "unknown struct type `Piont` — did you mean `Point`?"
    );
    assert_eq!(
        errors[0].help.as_deref(),
        Some("declare `struct Point { ... }` or fix the type name")
    );
}

#[test]
fn test_generic_enum_construct_instantiates_type_arguments() {
    let errs = errors(
        r#"pipeline t(task) {
  enum Option<T> {
Some(value: T),
None
  }
  let value: Option<int> = Option.Some(42)
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_result_generic_type_compatibility() {
    let errs = errors(
        r#"pipeline t(task) {
  let ok: Result<int, string> = Result.Ok(42)
  let err: Result<int, string> = Result.Err("oops")
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_result_generic_type_mismatch_reports_error() {
    let errs = errors(
        r#"pipeline t(task) {
  let bad: Result<int, string> = Result.Err(42)
}"#,
    );
    assert_eq!(errs.len(), 1, "expected 1 error, got: {errs:?}");
    assert!(errs[0].contains("Result<int, string>"));
    assert!(errs[0].contains("Result<_, int>"));
}

#[test]
fn test_builtin_return_type_inference() {
    let errs = errors(r#"pipeline t(task) { let x: string = to_int("42") }"#);
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("string"));
    assert!(errs[0].contains("int"));
}

#[test]
fn test_workflow_and_transcript_builtins_are_known() {
    let errs = errors(
        r#"pipeline t(task) {
  let flow = workflow_graph({name: "demo", entry: "act", nodes: {act: {kind: "stage"}}})
  let report: dict = workflow_policy_report(flow, {tools: tool_registry(), capabilities: {workspace: ["read_text"]}})
  let run: dict = workflow_execute("task", flow, [], {})
  let tree: dict = load_run_tree("run.json")
  let fixture: dict = run_record_fixture(run?.run)
  let suite: dict = run_record_eval_suite([{run: run?.run, fixture: fixture}])
  let diff: dict = run_record_diff(run?.run, run?.run)
  let manifest: dict = eval_suite_manifest({cases: [{run_path: "run.json"}]})
  let suite_report: dict = eval_suite_run(manifest)
  let wf: dict = artifact_workspace_file("src/main.rs", "fn main() {}", {source: "host"})
  let snap: dict = artifact_workspace_snapshot(["src/main.rs"], "snapshot")
  let selection: dict = artifact_editor_selection("src/main.rs", "main")
  let verify: dict = artifact_verification_result("verify", "ok")
  let test_result: dict = artifact_test_result("tests", "pass")
  let cmd: dict = artifact_command_result("cargo test", {status: 0})
  let patch: dict = artifact_diff("src/main.rs", "old", "new")
  let git: dict = artifact_git_diff("diff --git a b")
  let review: dict = artifact_diff_review(patch, "review me")
  let decision: dict = artifact_review_decision(review, "accepted")
  let proposal: dict = artifact_patch_proposal(review, "*** Begin Patch")
  let bundle: dict = artifact_verification_bundle("checks", [{name: "fmt", ok: true}])
  let apply: dict = artifact_apply_intent(review, "apply")
  let transcript = transcript_reset({metadata: {source: "test"}})
  let visible: string = transcript_render_visible(transcript_archive(transcript))
  let events: list = transcript_events(transcript)
  let worker: dict = worker_trigger({id: "worker_1"}, {follow_up: "next"})
  let context: string = artifact_context([], {max_artifacts: 1})
  println(report)
  println(run)
  println(tree)
  println(fixture)
  println(suite)
  println(diff)
  println(manifest)
  println(suite_report)
  println(wf)
  println(snap)
  println(selection)
  println(verify)
  println(test_result)
  println(cmd)
  println(patch)
  println(git)
  println(review)
  println(decision)
  println(proposal)
  println(bundle)
  println(apply)
  println(visible)
  println(events)
  println(worker)
  println(context)
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_binary_op_type_inference() {
    let errs = errors("pipeline t(task) { let x: string = 1 + 2 }");
    assert_eq!(errs.len(), 1);
}

#[test]
fn test_exponentiation_requires_numeric_operands() {
    let errs = errors(r#"pipeline t(task) { let x = "nope" ** 2 }"#);
    assert!(
        errs.iter().any(|err| err.contains("can't use '**'")),
        "missing exponentiation type error: {errs:?}"
    );
}

#[test]
fn test_comparison_returns_bool() {
    let errs = errors("pipeline t(task) { let x: bool = 1 < 2 }");
    assert!(errs.is_empty());
}

#[test]
fn test_int_float_promotion() {
    let errs = errors("pipeline t(task) { let x: float = 42 }");
    assert!(errs.is_empty());
}

#[test]
fn test_untyped_code_no_errors() {
    let errs = errors(
        r#"pipeline t(task) {
  fn process(data) {
let result = data + " processed"
return result
  }
  log(process("hello"))
}"#,
    );
    assert!(errs.is_empty());
}

#[test]
fn test_type_alias() {
    let errs = errors(
        r#"pipeline t(task) {
  type Name = string
  let x: Name = "hello"
}"#,
    );
    assert!(errs.is_empty());
}

#[test]
fn test_type_alias_mismatch() {
    let errs = errors(
        r#"pipeline t(task) {
  type Name = string
  let x: Name = 42
}"#,
    );
    assert_eq!(errs.len(), 1);
}

#[test]
fn test_assignment_type_check() {
    let errs = errors(
        r#"pipeline t(task) {
  var x: int = 0
  x = "hello"
}"#,
    );
    assert_eq!(errs.len(), 1);
    assert!(errs[0].contains("expected int, found string"));
}

#[test]
fn test_type_mismatch_render_snapshot_with_coercion_help() {
    std::env::set_var("NO_COLOR", "1");
    let source = r#"pipeline t(task) {
  let label: string = 42
}"#;
    let diags = check_source_with_source(source);
    let rendered = crate::diagnostic::render_type_diagnostic(source, "test.harn", &diags[0]);
    assert_eq!(
        rendered,
        r#"error: let binding `label`: expected string, found int
  --> test.harn:2:23
   |
 2 |   let label: string = 42
   |                       ^^ found this type
   = help: did you mean `to_string(42)`?
   = note: expected type declared here
  --> test.harn:2:3
   |
 2 |   let label: string = 42
   |   ^^^^^^^^^^^^^^^^^^^^^^ expected type declared here
"#
    );
}

#[test]
fn test_type_mismatch_render_snapshot_with_nested_note() {
    std::env::set_var("NO_COLOR", "1");
    let source = r#"pipeline t(task) {
  let item: {name: string, count: int} = {name: 1, count: 2}
}"#;
    let diags = check_source_with_source(source);
    let rendered = crate::diagnostic::render_type_diagnostic(source, "test.harn", &diags[0]);
    assert_eq!(
        rendered,
        r#"error: let binding `item`: expected {name: string, count: int}, found {name: int, count: int} (field 'name' has type int, expected string)
  --> test.harn:2:42
   |
 2 |   let item: {name: string, count: int} = {name: 1, count: 2}
   |                                          ^^^^^^^^^^^^^^^^^^^ found this type
   = note: expected type declared here
  --> test.harn:2:3
   |
 2 |   let item: {name: string, count: int} = {name: 1, count: 2}
   |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type declared here
   = note: nested mismatch: field `name` expected string, found int
  --> test.harn:2:42
   |
 2 |   let item: {name: string, count: int} = {name: 1, count: 2}
   |                                          ^^^^^^^^^^^^^^^^^^^ nested mismatch: field `name` expected string, found int
"#
    );
}

#[test]
fn test_covariance_int_to_float_in_fn() {
    let errs =
        errors("pipeline t(task) { fn scale(x: float) -> float { return x * 2.0 }\nscale(42) }");
    assert!(errs.is_empty());
}

#[test]
fn test_covariance_return_type() {
    let errs = errors("pipeline t(task) { fn get() -> float { return 42 } }");
    assert!(errs.is_empty());
}

#[test]
fn test_no_contravariance_float_to_int() {
    let errs = errors("pipeline t(task) { fn add(a: int) -> int { return a + 1 }\nadd(3.14) }");
    assert_eq!(errs.len(), 1);
}

// --- Comprehensive variance (issue #34) --------------------------------

#[test]
fn test_fn_param_contravariance_positive() {
    // A closure that accepts a float (a supertype of int) can
    // stand in for an expected `fn(int) -> int`: anything the
    // caller hands in (an int) the closure can still accept.
    let errs = errors(
        r#"pipeline t(task) {
            let wide = fn(x: float) { return 0 }
            let cb: fn(int) -> int = wide
        }"#,
    );
    assert!(
        errs.is_empty(),
        "expected fn(float)->int to satisfy fn(int)->int, got: {errs:?}"
    );
}

#[test]
fn test_fn_param_contravariance_negative() {
    // A closure that only accepts ints cannot stand in for an
    // expected `fn(float) -> int`: the caller may hand it a
    // float, which it is not prepared to receive.
    let errs = errors(
        r#"pipeline t(task) {
            let narrow = fn(x: int) { return 0 }
            let cb: fn(float) -> int = narrow
        }"#,
    );
    assert!(
        !errs.is_empty(),
        "expected fn(int)->int NOT to satisfy fn(float)->int, but type-check passed"
    );
}

#[test]
fn test_list_invariant_int_to_float_rejected() {
    // `list<int>` must not flow into `list<float>` — lists are
    // mutable, so a covariant assignment is unsound.
    let errs = errors(
        r#"pipeline t(task) {
            let xs: list<int> = [1, 2, 3]
            let ys: list<float> = xs
        }"#,
    );
    assert!(
        !errs.is_empty(),
        "expected list<int> NOT to flow into list<float>, but type-check passed"
    );
}

#[test]
fn test_iter_covariant_int_to_float_accepted() {
    // Iterators are read-only, so element-type widening is sound.
    let errs = errors(
        r#"pipeline t(task) {
            fn sink(ys: iter<float>) -> int { return 0 }
            fn pipe(xs: iter<int>) -> int { return sink(xs) }
        }"#,
    );
    assert!(
        errs.is_empty(),
        "expected iter<int> to flow into iter<float>, got: {errs:?}"
    );
}

#[test]
fn test_decl_site_out_used_in_contravariant_position_rejected() {
    // `type Box<out T> = fn(T) -> ()` — T is declared covariant
    // but appears only as an input (contravariant). Must be
    // rejected at declaration time.
    let errs = errors(
        r#"pipeline t(task) {
            type Box<out T> = fn(T) -> int
        }"#,
    );
    assert!(
        errs.iter().any(|e| e.contains("declared 'out'")),
        "expected 'out T' misuse diagnostic, got: {errs:?}"
    );
}

#[test]
fn test_decl_site_in_used_in_covariant_position_rejected() {
    // `interface Producer<in T> { fn next() -> T }` — T is declared
    // contravariant but appears only in output position.
    let errs = errors(
        r#"pipeline t(task) {
            interface Producer<in T> { fn next() -> T }
        }"#,
    );
    assert!(
        errs.iter().any(|e| e.contains("declared 'in'")),
        "expected 'in T' misuse diagnostic, got: {errs:?}"
    );
}

#[test]
fn test_decl_site_out_in_covariant_position_ok() {
    // `type Reader<out T> = fn() -> T` — T appears in a covariant
    // position, consistent with `out T`.
    let errs = errors(
        r#"pipeline t(task) {
            type Reader<out T> = fn() -> T
        }"#,
    );
    assert!(
        errs.iter().all(|e| !e.contains("declared 'out'")),
        "unexpected variance diagnostic: {errs:?}"
    );
}

#[test]
fn test_dict_invariant_int_to_float_rejected() {
    let errs = errors(
        r#"pipeline t(task) {
            let d: dict<string, int> = {"a": 1}
            let e: dict<string, float> = d
        }"#,
    );
    assert!(
        !errs.is_empty(),
        "expected dict<string, int> NOT to flow into dict<string, float>"
    );
}

#[test]
fn test_generic_alias_distributes_over_closed_literal_union() {
    // `ActionContainer<Action>` must distribute into
    // `ActionContainer<"create"> | ActionContainer<"edit">`, which lets a
    // `fn("create") -> nil` value flow into the `"create"` branch without
    // running into contravariance grief (the TypeScript playground bug).
    let errs = errors(
        r#"
type Action = "create" | "edit"
type ActionContainer<T> = { action: T, process_action: fn(T) -> nil }

fn process_create(a: "create") {}
fn process_edit(a: "edit") {}

pipeline t(task) {
    let c: ActionContainer<Action> = {action: "create", process_action: process_create}
    let d: ActionContainer<Action> = {action: "edit",   process_action: process_edit}
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_bare_function_reference_infers_fn_type() {
    // Before the identifier-to-fn-type fallback, a bare function reference
    // used as a value inferred to `None`, which meant it collapsed to
    // `nil` when placed into a dict literal. That silently broke
    // assignability against any typed `fn(...) -> R` slot.
    let errs = errors(
        r#"
fn process(a: string) -> string { return a }

pipeline t(task) {
    let slot: fn(string) -> string = process
    let d: { handler: fn(string) -> string } = { handler: process }
}"#,
    );
    assert!(errs.is_empty(), "unexpected type errors: {errs:?}");
}

#[test]
fn test_generic_alias_distribution_preserves_non_union_arg() {
    // Non-union arguments still substitute plainly: `ActionContainer<int>`
    // expands to `{ action: int, process_action: fn(int) -> nil }` with no
    // distribution. A `fn(int) -> nil` handler fits; a `fn(string) -> nil`
    // does not.
    let ok_errs = errors(
        r#"
type ActionContainer<T> = { action: T, process_action: fn(T) -> nil }

fn process_int(a: int) {}

pipeline t(task) {
    let c: ActionContainer<int> = {action: 7, process_action: process_int}
}"#,
    );
    assert!(ok_errs.is_empty(), "expected no errors: {ok_errs:?}");

    let bad_errs = errors(
        r#"
type ActionContainer<T> = { action: T, process_action: fn(T) -> nil }

fn process_string(a: string) {}

pipeline t(task) {
    let c: ActionContainer<int> = {action: 7, process_action: process_string}
}"#,
    );
    assert!(
        !bad_errs.is_empty(),
        "expected an error: `fn(string)` cannot fill an `fn(int)` slot"
    );
}