harn-stdlib 0.9.4

Embedded Harn standard library source catalog
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
/**
 * std/verification — deterministic verification facts and helper shapes.
 *
 * Import: import "std/verification"
 *
 * This module is the Harn-owned home for reusable verification intelligence
 * primitives. It intentionally starts with fact capture, not policy: callers
 * can bind diagnostics and background check results to file snapshots without
 * duplicating hostlib plumbing or inventing product-specific hash logic.
 */
import { command_run, command_wait } from "std/command"
import { shell_quote } from "std/runtime"
import { regex_first_capture, truncate_text } from "std/text"

type VerificationFileHashSnapshotEntry = {
  path: string,
  known: bool,
  readable: bool,
  hash: string?,
  hash_source: "indexed" | "disk" | "missing",
  size: int?,
  mtime_ms: int?,
  indexed_hash: string?,
  indexed_mtime_ms: int?,
  last_edit_seq: int,
}

type VerificationFileHashSnapshot = {
  seq: int,
  captured_at_ms: int,
  algorithm: string,
  snapshot: dict,
  missing: list<string>,
  files: list<VerificationFileHashSnapshotEntry>,
}

type VerificationCheckObservation = {
  durationMs?: int,
  warm: bool,
  at?: string,
  exit?: int,
  failureSignature?: string,
  snapshot?: dict,
}

type VerificationRecordedCheck = {
  result: dict,
  observation: VerificationCheckObservation,
  row: dict?,
  snapshot: VerificationFileHashSnapshot?,
}

type VerificationStartedCheck = {
  row_id: string,
  started: dict,
  observation_options: dict,
  snapshot: VerificationFileHashSnapshot?,
}

type VerificationToolchainFact = {
  id: string,
  name: string,
  available: bool,
  version?: string,
  raw_version: string,
  cache_identity: dict,
  probe: dict,
}

type VerificationAffectedTarget = dict

type VerificationAffectedAdapterFact = {
  id: string,
  parser_id: string,
  status: string,
  ok: bool,
  target_count: int,
  exit?: int,
  error?: string,
}

type VerificationAffectedTargetsFact = {
  changed_paths: list<string>,
  targets: list<VerificationAffectedTarget>,
  adapters: list<VerificationAffectedAdapterFact>,
  fallback: dict,
}

type VerificationProfileMatch = {row: dict, specificity: int, index: int}

type VerificationLadderPlanEntry = dict

type VerificationLadderPlan = {
  schema: string,
  query: dict,
  matches: list<VerificationProfileMatch>,
  selected: list<VerificationLadderPlanEntry>,
  skipped: list<dict>,
  fallback: bool,
  reason: string,
}

fn __verification_opts(options) {
  return options ?? {}
}

fn __verification_result_ok(result) -> bool {
  if result?.ok != nil {
    return result.ok ? true : false
  }
  if result?.success != nil {
    return result.success ? true : false
  }
  let exit = to_int(result?.exit_code)
  let status = result?.status ?? "completed"
  return status == "completed" && exit == 0 && !(result?.timed_out ?? false)
}

fn __verification_duration_ms(result, opts) {
  if opts?.duration_ms != nil {
    return to_int(opts.duration_ms)
  }
  if result?.duration_ms != nil {
    return to_int(result.duration_ms)
  }
  if result?.execution_duration_ms != nil {
    return to_int(result.execution_duration_ms)
  }
  return nil
}

fn __verification_exit(result, opts) {
  if opts?.exit != nil {
    return to_int(opts.exit)
  }
  if result?.exit_code != nil {
    return to_int(result.exit_code)
  }
  if result?.status == "timed_out" || result?.timed_out == true {
    return 124
  }
  if result?.ok != nil || result?.success != nil {
    return __verification_result_ok(result) ? 0 : 1
  }
  return nil
}

fn __verification_warm(opts) -> bool {
  if opts?.warm != nil {
    return opts.warm ? true : false
  }
  if opts?.cold != nil {
    return !(opts.cold ? true : false)
  }
  return true
}

fn __verification_snapshot_map(value) {
  if value == nil {
    return nil
  }
  if type_of(value) == "dict" && value?.snapshot != nil {
    return value.snapshot
  }
  return value
}

fn __verification_capture_snapshot(opts) {
  var snapshot_fact = nil
  var snapshot = __verification_snapshot_map(opts?.snapshot)
  if opts?.snapshot_paths != nil {
    snapshot_fact = verification_file_hash_snapshot(opts.snapshot_paths)
    snapshot = snapshot_fact.snapshot
  }
  return {fact: snapshot_fact, snapshot: snapshot}
}

fn __verification_result_text(result, source: string) -> string {
  if source == "stderr" {
    return result?.stderr ?? ""
  }
  if source == "stdout" {
    return result?.stdout ?? ""
  }
  if source == "combined" {
    return result?.combined ?? ((result?.stdout ?? "") + (result?.stderr ?? ""))
  }
  return ""
}

fn __verification_failure_signature(result, opts) {
  if opts?.failure_signature != nil {
    let explicit = to_string(opts.failure_signature)
    return trim(explicit) == "" ? nil : explicit
  }
  if __verification_result_ok(result) {
    return nil
  }
  let source = opts?.failure_signature_from ?? "combined"
  if source == "none" {
    return nil
  }
  let max_chars = to_int(opts?.max_failure_signature_chars) ?? 4000
  let text = trim(__verification_result_text(result, source))
  if text != "" {
    return truncate_text(text, max_chars)
  }
  let status = result?.status ?? "failed"
  let exit = __verification_exit(result, opts)
  return "check " + to_string(status) + " exit=" + to_string(exit)
}

fn __verification_row_id(row, index: int) -> string {
  let id = trim(to_string(row?.id ?? row?.name ?? ""))
  if id != "" {
    return id
  }
  return "toolchain/" + to_string(index)
}

fn __verification_toolchain_name(row, id: string) -> string {
  let name = trim(to_string(row?.name ?? ""))
  return name == "" ? id : name
}

fn __verification_toolchain_probe(row) {
  let probe = row?.versionProbe ?? row?.probe
  if probe == nil {
    return nil
  }
  if type_of(probe) == "dict" && probe?.spec != nil {
    return probe.spec
  }
  return probe
}

fn __verification_toolchain_probe_options(row, opts) {
  let probe = row?.versionProbe ?? row?.probe ?? {}
  return (opts?.command_options ?? {}) + (probe?.command_options ?? row?.command_options ?? {})
}

fn __verification_toolchain_version_pattern(row, opts) -> string {
  let probe = row?.versionProbe ?? row?.probe ?? {}
  return to_string(
    probe?.versionPattern
      ?? probe?.version_pattern
      ?? row?.versionPattern
      ?? row?.version_pattern
      ?? opts?.version_pattern
      ?? "([0-9]+(\\.[0-9A-Za-z_+\\-]+)+)",
  )
}

fn __verification_toolchain_raw_version(result) -> string {
  let stdout = trim(result?.stdout ?? "")
  if stdout != "" {
    return stdout
  }
  return trim(result?.stderr ?? "")
}

fn __verification_toolchain_cache_identity(row, opts) -> dict {
  return (opts?.cache_identity ?? {}) + (row?.cacheIdentity ?? row?.cache_identity ?? {})
}

fn __verification_string_list(value) -> list<string> {
  if value == nil {
    return []
  }
  let raw = type_of(value) == "list" ? value : [value]
  var out: list<string> = []
  for item in raw {
    let text = trim(to_string(item ?? ""))
    if text != "" && !contains(out, text) {
      out = out + [text]
    }
  }
  return out
}

fn __verification_clean_path(value) -> string {
  var path = regex_replace_all("\\\\", "/", trim(to_string(value ?? "")))
  while starts_with(path, "./") {
    path = substring(path, 2)
  }
  return path
}

fn __verification_path_under(root_value, path_value) -> bool {
  let root = __verification_clean_path(root_value)
  let path = __verification_clean_path(path_value)
  if path == "" {
    return false
  }
  if root == "" || root == "." {
    return true
  }
  return path == root || starts_with(path, root + "/")
}

fn __verification_shell_join(values) -> string {
  var quoted = []
  for value in values ?? [] {
    quoted = quoted + [shell_quote(to_string(value))]
  }
  return join(quoted, " ")
}

fn __verification_render_adapter_value(value, ctx) {
  if type_of(value) == "string" {
    return render_string(value, ctx)
  }
  if type_of(value) == "list" {
    var out = []
    for item in value {
      out = out + [__verification_render_adapter_value(item, ctx)]
    }
    return out
  }
  if type_of(value) == "dict" {
    var out = {}
    for key in value.keys() {
      out = out + {[key]: __verification_render_adapter_value(value[key], ctx)}
    }
    return out
  }
  return value
}

fn __verification_adapter_spec(row, changed_paths, opts) {
  let spec = row?.spec ?? row?.command
  if spec == nil {
    return nil
  }
  let ctx = (opts?.template_context ?? {})
    + (row?.template_context ?? {})
    + {
    changed_paths: changed_paths,
    changed_paths_json: json_stringify(changed_paths),
    changed_paths_space: __verification_shell_join(changed_paths),
    root: opts?.root ?? opts?.workspace_root ?? "",
  }
  return __verification_render_adapter_value(spec, ctx)
}

fn __verification_adapter_command_options(row, opts) {
  return (opts?.command_options ?? {}) + (row?.command_options ?? {})
}

fn __verification_adapter_id(row, index: int) -> string {
  let id = trim(to_string(row?.id ?? row?.name ?? ""))
  return id == "" ? "adapter/" + to_string(index) : id
}

fn __verification_parser_id(row) -> string {
  let parser = trim(to_string(row?.parser_id ?? row?.parser ?? "harn.targets_json.v1"))
  return parser == "" ? "harn.targets_json.v1" : parser
}

fn __verification_target_from_value(value, adapter_id: string, default_kind: string, files) {
  let base = if type_of(value) == "dict" {
    value
  } else {
    {id: to_string(value), label: to_string(value)}
  }
  let id = trim(to_string(base?.id ?? base?.name ?? base?.label ?? ""))
  if id == "" {
    return nil
  }
  var out = base + {id: id, adapter_id: adapter_id, source: base?.source ?? "adapter"}
  if out?.label == nil {
    out = out + {label: id}
  }
  if out?.kind == nil {
    out = out + {kind: default_kind}
  }
  if out?.files == nil {
    out = out + {files: __verification_string_list(files)}
  }
  return out
}

fn __verification_push_target(targets, target) {
  if target == nil {
    return targets
  }
  let key = trim(to_string(target?.id ?? ""))
  if key == "" {
    return targets
  }
  for existing in targets {
    if existing?.id == key {
      return targets
    }
  }
  return targets + [target]
}

fn __verification_json_target_values(data) {
  if type_of(data) == "list" {
    return data
  }
  if type_of(data) == "dict" {
    let targets = data?.targets ?? data?.affectedTargets ?? data?.affected_targets
    if type_of(targets) == "list" {
      return targets
    }
  }
  return []
}

fn __verification_parse_json_targets(adapter_id: string, data, changed_paths) {
  var targets = []
  for item in __verification_json_target_values(data) {
    targets = __verification_push_target(
      targets,
      __verification_target_from_value(item, adapter_id, "target", item?.files ?? changed_paths),
    )
  }
  return targets
}

fn __verification_parse_line_targets(adapter_id: string, text: string, changed_paths) {
  var targets = []
  for line in text.split("\n") {
    let id = trim(line)
    if id != "" {
      targets = __verification_push_target(
        targets,
        __verification_target_from_value(id, adapter_id, "target", changed_paths),
      )
    }
  }
  return targets
}

fn __verification_cargo_package_files(package, changed_paths) -> list<string> {
  let manifest = __verification_clean_path(package?.manifest_path ?? "")
  let root = dirname(manifest)
  var files: list<string> = []
  for path in changed_paths {
    if __verification_path_under(root, path) {
      files = files + [path]
    }
  }
  return files
}

fn __verification_cargo_target_names(package) -> list<string> {
  var names: list<string> = []
  for target in package?.targets ?? [] {
    let name = trim(to_string(target?.name ?? target))
    if name != "" && !contains(names, name) {
      names = names + [name]
    }
  }
  return names
}

fn __verification_parse_cargo_metadata(adapter_id: string, data, changed_paths) {
  var targets = []
  for package in data?.packages ?? [] {
    let files = __verification_cargo_package_files(package, changed_paths)
    if len(files) == 0 {
      continue
    }
    let name = trim(to_string(package?.name ?? ""))
    if name == "" {
      continue
    }
    targets = __verification_push_target(
      targets,
      {
        id: "cargo:" + name,
        label: name,
        kind: "cargo-package",
        adapter_id: adapter_id,
        source: "adapter",
        files: files,
        manifest_path: package?.manifest_path,
        target_names: __verification_cargo_target_names(package),
      },
    )
  }
  return targets
}

fn __verification_project_targets(project) -> list<string> {
  let raw = project?.targets ?? project?.tasks ?? []
  if type_of(raw) == "dict" {
    return raw.keys().sort()
  }
  var names: list<string> = []
  for item in raw {
    let name = trim(to_string(item?.name ?? item))
    if name != "" && !contains(names, name) {
      names = names + [name]
    }
  }
  return names.sort()
}

fn __verification_project_rows(data) {
  let raw = data?.projects ?? data?.workspaces ?? data
  var rows = []
  if type_of(raw) == "dict" {
    for name in raw.keys().sort() {
      rows = rows + [(raw[name] ?? {}) + {name: name}]
    }
    return rows
  }
  if type_of(raw) == "list" {
    return raw
  }
  return []
}

fn __verification_parse_js_workspace_graph(adapter_id: string, data, changed_paths) {
  var targets = []
  for project in __verification_project_rows(data) {
    let root = project?.root ?? project?.sourceRoot ?? project?.source_root ?? ""
    var files: list<string> = []
    for path in changed_paths {
      if __verification_path_under(root, path) {
        files = files + [path]
      }
    }
    if len(files) == 0 {
      continue
    }
    let name = trim(to_string(project?.name ?? project?.id ?? root))
    if name == "" {
      continue
    }
    targets = __verification_push_target(
      targets,
      {
        id: "js:" + name,
        label: name,
        kind: "js-project",
        adapter_id: adapter_id,
        source: "adapter",
        files: files,
        root: root,
        target_names: __verification_project_targets(project),
      },
    )
  }
  return targets
}

fn __verification_parse_adapter_targets(
  row,
  adapter_id: string,
  parser_id: string,
  result,
  changed_paths,
) {
  if parser_id == "harn.targets_lines.v1" || parser_id == "lines.v1" {
    return __verification_parse_line_targets(adapter_id, result?.stdout ?? "", changed_paths)
  }
  let data = json_parse(result?.stdout ?? "null")
  if parser_id == "harn.targets_json.v1" || parser_id == "json.targets.v1" {
    return __verification_parse_json_targets(adapter_id, data, changed_paths)
  }
  if parser_id == "cargo.metadata.v1" {
    return __verification_parse_cargo_metadata(adapter_id, data, changed_paths)
  }
  if parser_id == "js.workspace_graph.v1" || parser_id == "nx.project_graph.v1" {
    return __verification_parse_js_workspace_graph(adapter_id, data, changed_paths)
  }
  throw "verification_affected_targets: unsupported parser_id `" + parser_id + "`"
}

fn __verification_code_index_fallback(changed_paths, opts) {
  if opts?.fallback == false {
    return {enabled: false, available: false, targets: []}
  }
  var targets = []
  var errors = []
  for path in changed_paths {
    targets = __verification_push_target(
      targets,
      {
        id: "file:" + path,
        label: path,
        kind: "file",
        source: "code_index",
        files: [path],
        reason: "changed_file",
      },
    )
    let file_id = try {
      hostlib_code_index_path_to_id({path: path})
    } catch (e) {
      errors = errors + [to_string(e)]
      nil
    }
    if file_id == nil || file_id == 0 {
      continue
    }
    let importers = try {
      hostlib_code_index_deps_get({file_id: file_id, direction: "importers"})
    } catch (e) {
      errors = errors + [to_string(e)]
      []
    }
    for importer_id in importers {
      let importer_path = try {
        hostlib_code_index_id_to_path({file_id: importer_id})
      } catch (_e) {
        nil
      }
      if importer_path != nil {
        targets = __verification_push_target(
          targets,
          {
            id: "file:" + importer_path,
            label: importer_path,
            kind: "file",
            source: "code_index",
            files: [importer_path],
            reason: "reverse_dependency",
            changed_path: path,
          },
        )
      }
    }
  }
  return {enabled: true, available: len(errors) == 0, targets: targets, errors: errors}
}

fn __verification_profile_row_id(row, index: int) -> string {
  let id = trim(to_string(row?.id ?? row?.name ?? ""))
  if id != "" {
    return id
  }
  return "profile/" + to_string(index)
}

fn __verification_check(row) -> dict {
  if type_of(row?.check) == "dict" {
    return row.check
  }
  return {}
}

fn __verification_rung_text(value) -> string {
  return uppercase(trim(to_string(value ?? "")))
}

fn __verification_rung_rank(value) {
  let rung = __verification_rung_text(value)
  let direct = to_int(rung)
  if direct != nil && direct >= 0 && direct <= 5 {
    return direct
  }
  if len(rung) == 2 && starts_with(rung, "R") {
    let parsed = to_int(substring(rung, 1))
    if parsed != nil && parsed >= 0 && parsed <= 5 {
      return parsed
    }
  }
  return nil
}

fn __verification_rung_bound(value, fallback: int) -> int {
  let rank = __verification_rung_rank(value)
  return rank ?? fallback
}

fn __verification_resource_class(row, check) -> string {
  let raw = check?.resourceClass ?? check?.resource_class ?? row?.resourceClass ?? row?.resource_class
    ?? "moderate"
  let value = lowercase(trim(to_string(raw)))
  return value == "" ? "moderate" : value
}

fn __verification_resource_rank(value) -> int {
  let resource = lowercase(trim(to_string(value ?? "")))
  if resource == "cheap" {
    return 0
  }
  if resource == "moderate" {
    return 1
  }
  if resource == "heavy" {
    return 2
  }
  if resource == "remote_ok" || resource == "remote-ok" || resource == "remote" {
    return 3
  }
  return 4
}

fn __verification_lower_string_list(value) -> list<string> {
  var out: list<string> = []
  for item in __verification_string_list(value) {
    let text = lowercase(item)
    if !contains(out, text) {
      out = out + [text]
    }
  }
  return out
}

fn __verification_resource_allowed(resource: string, opts) -> bool {
  let allowed = __verification_lower_string_list(opts?.resource_classes ?? opts?.allowed_resource_classes)
  if len(allowed) == 0 {
    return true
  }
  return contains(allowed, lowercase(resource))
}

fn __verification_row_p95_ms(row, opts) -> int {
  let kind = lowercase(trim(to_string(opts?.timing_kind ?? "warm")))
  let timings = row?.timings ?? {}
  let raw = if kind == "cold" {
    timings?.coldMs?.p95
  } else if kind == "any" {
    timings?.warmMs?.p95 ?? timings?.coldMs?.p95
  } else {
    timings?.warmMs?.p95 ?? timings?.coldMs?.p95
  }
  return to_int(raw) ?? to_int(opts?.unknown_p95_ms) ?? 999999
}

fn __verification_row_command(row, check) {
  return check?.command ?? check?.spec ?? row?.command ?? row?.spec
}

fn __verification_command_present(command) -> bool {
  if command == nil {
    return false
  }
  if type_of(command) == "string" {
    return trim(command) != ""
  }
  return true
}

fn __verification_skip(row_id: string, reason: string, profile_match) -> dict {
  return {
    row_id: row_id,
    reason: reason,
    specificity: profile_match?.specificity ?? 0,
    index: profile_match?.index ?? 0,
  }
}

fn __verification_ladder_candidate(profile_match, opts) {
  let row = profile_match?.row ?? {}
  let row_id = __verification_profile_row_id(row, to_int(profile_match?.index) ?? 0)
  let check = __verification_check(row)
  let rung_rank = __verification_rung_rank(check?.rung ?? row?.rung)
  if rung_rank == nil {
    return {entry: nil, skip: __verification_skip(row_id, "missing_or_invalid_rung", profile_match)}
  }
  let rung = "R" + to_string(rung_rank)
  let min_rank = __verification_rung_bound(opts?.min_rung, 0)
  let max_rank = __verification_rung_bound(opts?.max_rung, 5)
  if rung_rank < min_rank {
    return {entry: nil, skip: __verification_skip(row_id, "below_min_rung", profile_match)}
  }
  if rung_rank > max_rank {
    return {entry: nil, skip: __verification_skip(row_id, "above_max_rung", profile_match)}
  }
  let resource = __verification_resource_class(row, check)
  if !__verification_resource_allowed(resource, opts) {
    return {entry: nil, skip: __verification_skip(row_id, "resource_class_filtered", profile_match)}
  }
  if opts?.allow_stale_prone == false
    && (check?.staleProne ?? check?.stale_prone ?? row?.staleProne ?? row?.stale_prone ?? false) {
    return {entry: nil, skip: __verification_skip(row_id, "stale_prone_filtered", profile_match)}
  }
  let command = __verification_row_command(row, check)
  if !__verification_command_present(command) {
    return {entry: nil, skip: __verification_skip(row_id, "missing_command", profile_match)}
  }
  let p95_ms = __verification_row_p95_ms(row, opts)
  let specificity = to_int(profile_match?.specificity) ?? 0
  let index = to_int(profile_match?.index) ?? 0
  let sort_key = [rung_rank, __verification_resource_rank(resource), p95_ms, 0 - specificity, index]
  return {
    entry: {
      row_id: row_id,
      row: row,
      rung: rung,
      rung_rank: rung_rank,
      command: command,
      runnable: true,
      granularity: check?.granularity ?? row?.granularity,
      trust: check?.trust ?? check?.trust_level ?? row?.trust ?? row?.trust_level,
      resource_class: resource,
      p95_ms: p95_ms,
      specificity: specificity,
      index: index,
      sort_key: sort_key,
      background: check?.background ?? row?.background ?? false,
    },
    skip: nil,
  }
}

/**
 * Capture current on-disk hashes for `paths` under one code-index sequence
 * binding. Unknown-but-readable workspace files are included with
 * `known = false`; unreadable or out-of-workspace paths return a null hash
 * and appear in `missing`. The `snapshot` field is the direct path->hash map
 * consumed by `verification_diagnostic_classify`.
 *
 * @effects: [host, fs]
 * @errors: [backend, invalid_argument]
 * @api_stability: experimental
 * @example: verification_file_hash_snapshot(["src/main.zig", "build.zig"])
 */
pub fn verification_file_hash_snapshot(paths: list<string>) -> VerificationFileHashSnapshot {
  return hostlib_code_index_file_hash_snapshot({paths: paths})
}

/**
 * Resolve build/test targets affected by changed files using data-declared
 * adapters. Each adapter row supplies a command `spec` (or `command`) and a
 * `parser_id`; Harn ships parser ids for generic JSON/line targets, Cargo
 * metadata, and JS workspace graphs, while arbitrary stacks can add rows
 * without changing Rust code.
 *
 * Supported parser ids:
 * - `harn.targets_json.v1`: stdout JSON is `[{id, ...}]` or `{targets:[...]}`
 * - `harn.targets_lines.v1`: one target id per stdout line
 * - `cargo.metadata.v1`: Cargo metadata JSON; changed files map to packages
 * - `js.workspace_graph.v1`: `{projects:{name:{root, targets}}}` or list rows
 *
 * If adapters produce no targets, the helper falls back to the existing
 * code-index file graph: the changed file plus reverse importers become
 * conservative file targets. Pass `{fallback:false}` to disable that.
 *
 * @effects: [process, host]
 * @errors: [invalid_argument]
 * @api_stability: experimental
 */
pub fn verification_affected_targets(changed_paths: list<string>, adapters = nil, options = nil) -> VerificationAffectedTargetsFact {
  let opts = __verification_opts(options)
  let paths = __verification_string_list(changed_paths)
  let rows = adapters ?? opts?.adapters ?? []
  var targets = []
  var adapter_facts: list<VerificationAffectedAdapterFact> = []
  var index = 0
  for row in rows {
    let adapter_id = __verification_adapter_id(row, index)
    let parser_id = __verification_parser_id(row)
    let spec = __verification_adapter_spec(row, paths, opts)
    if spec == nil {
      adapter_facts = adapter_facts
        + [{id: adapter_id, parser_id: parser_id, status: "not_configured", ok: false, target_count: 0}]
      index = index + 1
      continue
    }
    let result = command_run(spec, __verification_adapter_command_options(row, opts))
    let parsed = try {
      __verification_parse_adapter_targets(row, adapter_id, parser_id, result, paths)
    } catch (e) {
      if opts?.fail_on_adapter_error ?? false {
        throw e
      }
      adapter_facts = adapter_facts
        + [
        {
          id: adapter_id,
          parser_id: parser_id,
          status: result?.status ?? "failed",
          ok: false,
          exit: __verification_exit(result, {}),
          target_count: 0,
          error: to_string(e),
        },
      ]
      []
    }
    for target in parsed {
      targets = __verification_push_target(targets, target)
    }
    if len(parsed) > 0 || len(adapter_facts) == index {
      adapter_facts = adapter_facts
        + [
        {
          id: adapter_id,
          parser_id: parser_id,
          status: result?.status ?? "completed",
          ok: __verification_result_ok(result),
          exit: __verification_exit(result, {}),
          target_count: len(parsed),
        },
      ]
    }
    index = index + 1
  }
  let fallback = if len(targets) == 0 || opts?.include_fallback == true {
    __verification_code_index_fallback(paths, opts)
  } else {
    {enabled: false, available: false, targets: []}
  }
  for target in fallback.targets ?? [] {
    targets = __verification_push_target(targets, target)
  }
  return {changed_paths: paths, targets: targets, adapters: adapter_facts, fallback: fallback}
}

/**
 * Build a data-driven verification ladder plan from profile rows.
 *
 * The selector engine lives in the Harn VM builtin
 * `verification_profile_matches`; this helper only ranks matching rows by
 * declared rung, resource class, observed p95 timing, selector specificity,
 * and row order. It never hardcodes languages, toolchains, or commands.
 *
 * Options:
 * - `dir`: profile-store directory to read from.
 * - `min_rung` / `max_rung`: inclusive bounds, default `R0`..`R5`.
 * - `resource_classes`: optional allow-list such as `["cheap", "moderate"]`.
 * - `timing_kind`: `warm` (default), `cold`, or `any`.
 * - `unknown_p95_ms`: timing fallback for unseen rows, default `999999`.
 * - `allow_stale_prone`: set false to skip stale-prone checks.
 * - `limit`: optional maximum selected checks.
 *
 * @effects: [state]
 * @errors: []
 * @api_stability: experimental
 */
pub fn verification_ladder_plan(query: dict, options = nil) -> VerificationLadderPlan {
  let opts = __verification_opts(options)
  let matches = verification_profile_matches(query, opts?.dir)
  var selected = []
  var skipped = []
  for profile_match in matches {
    let candidate = __verification_ladder_candidate(profile_match, opts)
    if candidate.entry != nil {
      selected = selected + [candidate.entry]
    } else if candidate.skip != nil {
      skipped = skipped + [candidate.skip]
    }
  }
  selected = selected.sort_by({ entry -> entry.sort_key })
  let limit = to_int(opts?.limit)
  if limit != nil && limit >= 0 && len(selected) > limit {
    selected = selected.slice(0, limit)
  }
  let reason = if len(matches) == 0 {
    "no_profile_rows"
  } else if len(selected) == 0 {
    "no_matching_runnable_rows"
  } else {
    "profile_rows_selected"
  }
  return {
    schema: "harn.verification.ladder_plan.v1",
    query: query,
    matches: matches,
    selected: selected,
    skipped: skipped,
    fallback: len(selected) == 0,
    reason: reason,
  }
}

/**
 * Convert a normalized command/check result into the canonical profile-store
 * observation shape: `{durationMs, warm, exit, failureSignature?, snapshot?}`.
 * This keeps timing capture DRY while leaving scheduler policy to the caller.
 *
 * Options:
 * - `warm` / `cold`: classify the run for warm/cold timing distributions.
 * - `snapshot`: either a direct file->hash map or a
 *   `VerificationFileHashSnapshot`.
 * - `failure_signature`: explicit signature to persist on failing runs.
 * - `failure_signature_from`: `combined` (default), `stderr`, `stdout`, or
 *   `none`.
 * - `max_failure_signature_chars`: defaults to 4000.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn verification_observation_from_command_result(result: dict, options = nil) -> VerificationCheckObservation {
  let opts = __verification_opts(options)
  var observation = {warm: __verification_warm(opts)}
  let duration_ms = __verification_duration_ms(result, opts)
  if duration_ms != nil {
    observation = observation + {durationMs: duration_ms}
  }
  let exit_code = __verification_exit(result, opts)
  if exit_code != nil {
    observation = observation + {exit: exit_code}
  }
  let snapshot = __verification_snapshot_map(opts?.snapshot)
  if snapshot != nil {
    observation = observation + {snapshot: snapshot}
  }
  let failure_signature = __verification_failure_signature(result, opts)
  if failure_signature != nil {
    observation = observation + {failureSignature: failure_signature}
  }
  if opts?.at != nil {
    observation = observation + {at: to_string(opts.at)}
  }
  return observation
}

/**
 * Record one command/check result into a verification profile row and return
 * the persisted row plus the observation that was applied. Unknown row ids
 * return `row = nil`, matching `verification_profile_record_run`.
 *
 * @effects: [state]
 * @errors: [invalid_argument]
 * @api_stability: experimental
 */
pub fn verification_record_check_result(row_id: string, result: dict, options = nil) -> VerificationRecordedCheck {
  let opts = __verification_opts(options)
  let observation = verification_observation_from_command_result(result, opts)
  let row = verification_profile_record_run(row_id, observation, opts?.dir)
  return {result: result, observation: observation, row: row, snapshot: nil}
}

/**
 * Run a command as one verification check, capture optional launch-time file
 * hashes, and record exactly one profile observation for the completed result.
 *
 * Options:
 * - `command_options`: options passed to `command_run`.
 * - `snapshot_paths`: file paths hashed before the command launches.
 * - `snapshot`: explicit file->hash map when the caller already captured one.
 * - `record`: set `false` to run and build the observation without updating
 *   the profile store.
 * - any `verification_observation_from_command_result` option.
 *
 * @effects: [process, host, fs, state]
 * @errors: [backend, invalid_argument]
 * @api_stability: experimental
 */
pub fn verification_run_check(row_id: string, spec, options = nil) -> VerificationRecordedCheck {
  let opts = __verification_opts(options)
  if opts?.command_options?.background == true {
    throw "verification_run_check: background command_options are not supported; use verification_start_check"
  }
  let captured = __verification_capture_snapshot(opts)
  let result = command_run(spec, opts?.command_options)
  let observation = verification_observation_from_command_result(result, opts + {snapshot: captured.snapshot})
  var row = nil
  if opts?.record != false {
    row = verification_profile_record_run(row_id, observation, opts?.dir)
  }
  return {result: result, observation: observation, row: row, snapshot: captured.fact}
}

/**
 * Start a verification check in the background after capturing optional
 * launch-time file hashes. The returned receipt is safe to persist and pass to
 * `verification_finish_check`; no profile row is updated until finish records
 * the completed result.
 *
 * @effects: [process, host, fs]
 * @errors: [backend, invalid_argument]
 * @api_stability: experimental
 */
pub fn verification_start_check(row_id: string, spec, options = nil) -> VerificationStartedCheck {
  let opts = __verification_opts(options)
  let captured = __verification_capture_snapshot(opts)
  let command_options = (opts?.command_options ?? {}) + {background: true}
  let started = command_run(spec, command_options)
  return {
    row_id: row_id,
    started: started,
    observation_options: opts + {snapshot: captured.snapshot},
    snapshot: captured.fact,
  }
}

/**
 * Wait for a check started by `verification_start_check`, record its completed
 * command result into the profile row, and return the same recorded-check
 * receipt shape as `verification_run_check`.
 *
 * Options:
 * - `wait_options`: options passed to `command_wait`.
 * - `record`: set `false` to wait and build the observation without updating
 *   the profile store.
 * - `row_id`: override the row id stored in the started-check receipt.
 * - any observation option can override the started-check observation options.
 *
 * @effects: [process, state]
 * @errors: [backend, invalid_argument]
 * @api_stability: experimental
 */
pub fn verification_finish_check(started_check: dict, options = nil) -> VerificationRecordedCheck {
  let opts = __verification_opts(options)
  let row_id = opts?.row_id ?? started_check?.row_id
  if row_id == nil || trim(to_string(row_id)) == "" {
    throw "verification_finish_check: row_id must be supplied in the receipt or options"
  }
  let result = command_wait(started_check.started, opts?.wait_options ?? {timeout_ms: 60000})
  let observation_options = (started_check?.observation_options ?? {}) + opts
  let observation = verification_observation_from_command_result(result, observation_options)
  var row = nil
  if opts?.record != false && started_check?.observation_options?.record != false {
    row = verification_profile_record_run(to_string(row_id), observation, observation_options?.dir)
  }
  return {result: result, observation: observation, row: row, snapshot: started_check?.snapshot}
}

/**
 * Execute config-declared toolchain probes and return deterministic identity
 * facts. Rows are data, not code: Harn does not hardcode Go, Zig, Cargo, or
 * any other toolchain. A row may declare:
 *
 * - `id` / `name`
 * - `versionProbe`: a `command_run` spec or `{spec, versionPattern,
 *   command_options}`
 * - `cacheIdentity`: any cache/build-server/env identity fields the scheduler
 *   wants to bind to the profile row
 *
 * Failed or missing probes produce `available = false` facts instead of
 * throwing, so a verification scheduler can reason about unavailable tools.
 *
 * @effects: [process]
 * @errors: []
 * @api_stability: experimental
 */
pub fn verification_toolchain_facts(rows: list<dict>, options = nil) -> list<VerificationToolchainFact> {
  let opts = __verification_opts(options)
  var facts = []
  var index = 0
  for row in rows {
    let id = __verification_row_id(row, index)
    let name = __verification_toolchain_name(row, id)
    let spec = __verification_toolchain_probe(row)
    var result = nil
    if spec != nil {
      result = command_run(spec, __verification_toolchain_probe_options(row, opts))
    }
    let ok = result != nil && __verification_result_ok(result)
    let raw_version = result == nil ? "" : __verification_toolchain_raw_version(result)
    let version = ok ? regex_first_capture(__verification_toolchain_version_pattern(row, opts), raw_version) : nil
    let exit_code = result == nil ? nil : __verification_exit(result, {})
    let probe = {
      status: result?.status ?? "not_configured",
      exit: exit_code,
      durationMs: result?.duration_ms,
      stdout: result?.stdout ?? "",
      stderr: result?.stderr ?? "",
    }
    facts = facts
      + [
      {
        id: id,
        name: name,
        available: ok,
        version: version,
        raw_version: raw_version,
        cache_identity: __verification_toolchain_cache_identity(row, opts),
        probe: probe,
      },
    ]
    index = index + 1
  }
  return facts
}