epics-base-rs 0.18.4

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
use std::collections::HashMap;

use super::registry::*;
use crate::error::CaResult;
use crate::server::database::parse_pv_name;
use crate::server::db_loader;
use crate::types::EpicsValue;

/// Register all built-in iocsh commands.
pub(crate) fn register_builtins(registry: &mut CommandRegistry) {
    registry.register(cmd_help());
    registry.register(cmd_dbl());
    registry.register(cmd_dbgf());
    registry.register(cmd_dbpf());
    registry.register(cmd_dbpr());
    registry.register(cmd_dbsr());
    registry.register(cmd_dbglob());
    registry.register(cmd_dbgrep());
    registry.register(cmd_scanppl());
    registry.register(cmd_post_event());
    registry.register(cmd_post_event_alias());
    registry.register(cmd_ioc_stats());
    registry.register(cmd_db_load_records());
    registry.register(cmd_db_create_record());
    registry.register(cmd_db_delete_record());
    registry.register(cmd_epics_env_set());
    registry.register(cmd_pushd());
    registry.register(cmd_popd());
    registry.register(cmd_dirs());
    registry.register(cmd_ioc_init());
    registry.register(cmd_after_ioc_running());
    registry.register(cmd_exit());

    // H-5: core iocsh commands (echo, date, cd/pwd, epicsEnv*, ...)
    // and the access-security `as*` family. Without these a stock
    // `st.cmd` errors on the first unknown command and access
    // security cannot be loaded from the shell.
    super::core_commands::register(registry);
    super::access_commands::register(registry);
}

/// `afterIocRunning <command>` — queue an iocsh command line to run
/// after iocInit completes. Mirrors epics-base PR #558.
fn cmd_after_ioc_running() -> CommandDef {
    CommandDef::new(
        "afterIocRunning",
        vec![ArgDesc {
            name: "command",
            arg_type: ArgType::String,
            optional: false,
        }],
        "afterIocRunning <command> — schedule a command for post-iocInit execution",
        |args: &[ArgValue], ctx: &CommandContext| {
            let line = match &args[0] {
                ArgValue::String(s) => s.clone(),
                _ => {
                    ctx.println("afterIocRunning: missing command");
                    return Ok(CommandOutcome::Continue);
                }
            };
            ctx.db().queue_after_ioc_running(line);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `dbDeleteRecord <name>` — remove a record from the live database.
/// Mirrors epics-base PR #505 (record deletion at DB creation).
fn cmd_db_delete_record() -> CommandDef {
    CommandDef::new(
        "dbDeleteRecord",
        vec![ArgDesc {
            name: "recordName",
            arg_type: ArgType::String,
            optional: false,
        }],
        "dbDeleteRecord <name> — remove a record from the live database",
        |args: &[ArgValue], ctx: &CommandContext| {
            let name = match &args[0] {
                ArgValue::String(s) => s.clone(),
                _ => {
                    ctx.println("dbDeleteRecord: missing recordName");
                    return Ok(CommandOutcome::Continue);
                }
            };
            if ctx.block_on(ctx.db().remove_record(&name)) {
                ctx.println(&format!("dbDeleteRecord: removed '{name}'"));
            } else {
                ctx.println(&format!("dbDeleteRecord: no record named '{name}'"));
            }
            Ok(CommandOutcome::Continue)
        },
    )
}

/// Process-global directory stack for `pushd`/`popd`/`dirs`.
/// Mirrors epics-base PR #497 — bash-style directory navigation in
/// iocsh. Stack is shared across IocShell instances within one
/// process; iocsh is by convention single-instance.
fn dir_stack() -> &'static std::sync::Mutex<Vec<std::path::PathBuf>> {
    static STACK: std::sync::OnceLock<std::sync::Mutex<Vec<std::path::PathBuf>>> =
        std::sync::OnceLock::new();
    STACK.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}

fn print_stack(ctx: &CommandContext) {
    let cwd = std::env::current_dir().unwrap_or_default();
    let stack = dir_stack().lock().unwrap();
    // Bash convention: top-of-stack is leftmost, cwd is shown first.
    let parts: Vec<String> = std::iter::once(cwd.display().to_string())
        .chain(stack.iter().rev().map(|p| p.display().to_string()))
        .collect();
    ctx.println(&parts.join(" "));
}

fn cmd_help() -> CommandDef {
    CommandDef::new(
        "help",
        vec![ArgDesc {
            name: "command",
            arg_type: ArgType::String,
            optional: true,
        }],
        "help [command] - List commands or show usage for a specific command",
        |args: &[ArgValue], _ctx: &CommandContext| {
            // help needs access to the registry, which we handle specially in execute_line
            // This handler is a placeholder; the real logic is in IocShell::execute_line
            match &args[0] {
                ArgValue::String(name) => {
                    _ctx.println("Use 'help' without arguments to list all commands, or 'help <command>' for details.");
                    _ctx.println(&format!("(Looking for help on '{name}')"));
                }
                ArgValue::Missing => {
                    _ctx.println("Use 'help' to list all commands.");
                }
                _ => {}
            }
            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_dbl() -> CommandDef {
    CommandDef::new(
        "dbl",
        vec![ArgDesc {
            name: "recordType",
            arg_type: ArgType::String,
            optional: true,
        }],
        "dbl [recordType] - List record names, optionally filtered by type",
        |args: &[ArgValue], ctx: &CommandContext| {
            let type_filter = match &args[0] {
                ArgValue::String(s) => Some(s.as_str()),
                _ => None,
            };

            let names = ctx.block_on(ctx.db().all_record_names());
            let mut names = names;
            names.sort();

            for name in &names {
                if let Some(filter) = type_filter {
                    let rec = ctx.block_on(ctx.db().get_record(name));
                    if let Some(rec) = rec {
                        let inst = ctx.block_on(rec.read());
                        if inst.record.record_type() != filter {
                            continue;
                        }
                    }
                }
                ctx.println(name);
            }

            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_dbgf() -> CommandDef {
    CommandDef::new(
        "dbgf",
        vec![ArgDesc {
            name: "pvname",
            arg_type: ArgType::String,
            optional: false,
        }],
        "dbgf pvname - Get field value",
        |args: &[ArgValue], ctx: &CommandContext| {
            let name = match &args[0] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };

            match ctx.block_on(ctx.db().get_pv(name)) {
                Ok(val) => {
                    let type_name = dbf_type_name(&val);
                    // epics-base dc70dfd6: dbgf must C-style-escape
                    // non-printable bytes in CHAR-array output and
                    // wrap in double-quotes so a CHAR array carrying
                    // control bytes does not corrupt the operator's
                    // terminal. Other types fall through to the
                    // standard Display formatter.
                    let formatted = match &val {
                        EpicsValue::CharArray(arr) => {
                            format!("\"{}\"", escape_char_array_for_dbgf(arr))
                        }
                        _ => format!("{val}"),
                    };
                    ctx.println(&format!("{type_name}: {formatted}"));
                    Ok(CommandOutcome::Continue)
                }
                Err(e) => Err(format!("{e}")),
            }
        },
    )
}

fn cmd_dbpf() -> CommandDef {
    CommandDef::new(
        "dbpf",
        vec![
            ArgDesc {
                name: "pvname",
                arg_type: ArgType::String,
                optional: false,
            },
            ArgDesc {
                name: "value",
                arg_type: ArgType::String,
                optional: false,
            },
        ],
        "dbpf pvname value - Put field value",
        |args: &[ArgValue], ctx: &CommandContext| {
            let name = match &args[0] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };
            let value_str = match &args[1] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };

            let (base, field) = parse_pv_name(name);
            let field = field.to_ascii_uppercase();

            // Try to determine the field type for proper parsing
            let dbf_type = ctx.block_on(async {
                if let Some(rec) = ctx.db().get_record(base).await {
                    let inst = rec.read().await;
                    // Check record-specific fields
                    if let Some(desc) = inst.record.field_list().iter().find(|f| f.name == field) {
                        return Some(desc.dbf_type);
                    }
                    // Common field types
                    return common_field_dbf_type(&field);
                }
                None
            });

            let value = if let Some(dbf) = dbf_type {
                EpicsValue::parse(dbf, value_str)
                    .map_err(|e| format!("cannot parse '{value_str}' as {dbf:?}: {e}"))?
            } else {
                // No type info available, try as string
                EpicsValue::String(value_str.clone())
            };

            // Use put_record_field_from_ca for records (triggers process like CA put).
            // Fall back to put_pv for simple PVs.
            let put_result: CaResult<()> = ctx.block_on(async {
                let db = ctx.db();
                if db.get_record(base).await.is_some() {
                    db.put_record_field_from_ca(base, &field, value)
                        .await
                        .map(|_| ())
                } else {
                    db.put_pv(name, value).await
                }
            });
            put_result.map_err(|e| {
                // Round-23: epics-base PR #689 — when the field
                // doesn't exist, suggest near-by names so a typo
                // ("DSEC" instead of "DESC") is caught quickly.
                let msg = format!("{e}");
                if msg.contains("FieldNotFound") || msg.contains(&format!("'{field}'")) {
                    if let Some(suggestion) =
                        ctx.block_on(suggest_field_name(ctx.db(), base, &field))
                    {
                        return format!("{msg}; did you mean '{suggestion}'?");
                    }
                }
                msg
            })?;

            // Read back to confirm
            match ctx.block_on(ctx.db().get_pv(name)) {
                Ok(val) => {
                    let type_name = dbf_type_name(&val);
                    ctx.println(&format!("{type_name}: {val}"));
                }
                Err(_) => {}
            }

            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_dbpr() -> CommandDef {
    CommandDef::new(
        "dbpr",
        vec![
            ArgDesc {
                name: "record",
                arg_type: ArgType::String,
                optional: false,
            },
            ArgDesc {
                name: "level",
                arg_type: ArgType::Int,
                optional: true,
            },
        ],
        "dbpr record [level] - Print record fields (level 0-2)",
        |args: &[ArgValue], ctx: &CommandContext| {
            let name = match &args[0] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };
            let level = match &args[1] {
                ArgValue::Int(n) => *n as i32,
                ArgValue::Missing => 0,
                _ => 0,
            };

            let rec = ctx
                .block_on(ctx.db().get_record(name))
                .ok_or_else(|| format!("record '{}' not found", name))?;

            // Collect field values inside lock, format outside
            let fields: Vec<(String, String)> = ctx.block_on(async {
                let inst = rec.read().await;
                let mut fields = Vec::new();

                // Level 0: NAME, RTYP, VAL (+ alias names if any —
                // base's dbpr surfaces aliases here so admins know
                // every spelling that resolves to this record).
                fields.push(("NAME".to_string(), inst.name.clone()));
                let aliases = ctx.db().aliases_for_record(&inst.name).await;
                if !aliases.is_empty() {
                    fields.push(("ALIASES".to_string(), aliases.join(", ")));
                }
                fields.push(("RTYP".to_string(), inst.record.record_type().to_string()));
                if let Some(val) = inst.record.val() {
                    fields.push(("VAL".to_string(), format!("{val}")));
                }
                if inst.common.sevr != crate::server::record::AlarmSeverity::NoAlarm {
                    fields.push(("SEVR".to_string(), format!("{:?}", inst.common.sevr)));
                    fields.push(("STAT".to_string(), format!("{}", inst.common.stat)));
                }

                if level >= 1 {
                    fields.push(("SCAN".to_string(), format!("{}", inst.common.scan)));
                    fields.push(("DTYP".to_string(), inst.common.dtyp.clone()));
                    if !inst.common.inp.is_empty() {
                        fields.push(("INP".to_string(), inst.common.inp.clone()));
                    }
                    if !inst.common.out.is_empty() {
                        fields.push(("OUT".to_string(), inst.common.out.clone()));
                    }
                    if !inst.common.flnk.is_empty() {
                        fields.push(("FLNK".to_string(), inst.common.flnk.clone()));
                    }
                    fields.push(("PINI".to_string(), format!("{}", inst.common.pini)));
                    fields.push(("UDF".to_string(), format!("{}", inst.common.udf)));
                }

                if level >= 2 {
                    // All record-specific fields
                    for desc in inst.record.field_list() {
                        let fname = desc.name.to_string();
                        if fields.iter().any(|(n, _)| n == &fname) {
                            continue;
                        }
                        if let Some(val) = inst.record.get_field(desc.name) {
                            fields.push((fname, format!("{val}")));
                        }
                    }
                    // Alarm fields
                    if let Some(ref alarm) = inst.common.analog_alarm {
                        fields.push(("HIHI".to_string(), format!("{}", alarm.hihi)));
                        fields.push(("HIGH".to_string(), format!("{}", alarm.high)));
                        fields.push(("LOW".to_string(), format!("{}", alarm.low)));
                        fields.push(("LOLO".to_string(), format!("{}", alarm.lolo)));
                        fields.push(("HHSV".to_string(), format!("{:?}", alarm.hhsv)));
                        fields.push(("HSV".to_string(), format!("{:?}", alarm.hsv)));
                        fields.push(("LSV".to_string(), format!("{:?}", alarm.lsv)));
                        fields.push(("LLSV".to_string(), format!("{:?}", alarm.llsv)));
                    }
                    fields.push(("ASG".to_string(), inst.common.asg.clone()));
                    // Round-20: surface info(...) tags so admins can
                    // verify driver hints (asyn:READBACK, Q:group, …)
                    // landed on the record. Sorted for stable output.
                    let mut info_keys: Vec<&String> = inst.info.keys().collect();
                    info_keys.sort();
                    for key in info_keys {
                        let val = inst.info.get(key).cloned().unwrap_or_default();
                        fields.push((format!("info({key})"), val));
                    }
                }

                fields
            });

            // Format outside lock
            for (name, value) in &fields {
                ctx.println(&format!("{name:>8}: {value}"));
            }

            Ok(CommandOutcome::Continue)
        },
    )
}

/// Shared handler for the record-name glob search `dbglob` / `dbgrep`.
/// Mirrors epics-base PR #626 (rename `dbgrep` → `dbglob` with alias)
/// and PR #613 (add fields argument). The `fields` argument is comma-
/// separated; when present each matching record additionally dumps
/// the listed field values. (H-6: `dbsr` is the *server report* — a
/// separate command — not this name search.)
fn dbsr_handler(args: &[ArgValue], ctx: &CommandContext) -> CommandResult {
    let pattern = args
        .first()
        .and_then(|a| {
            if let ArgValue::String(s) = a {
                Some(s.as_str())
            } else {
                None
            }
        })
        .unwrap_or("*");
    let fields: Vec<String> = args
        .get(1)
        .and_then(|a| {
            if let ArgValue::String(s) = a {
                Some(s.split(',').map(|f| f.trim().to_string()).collect())
            } else {
                None
            }
        })
        .unwrap_or_default();

    // Walk record names + aliases + simple PVs. Base's
    // `dbFirstRecord` iteration only sees records, but our
    // PvDatabase also serves `add_pv`-registered simple PVs (CA
    // gateway shadows, IOC-stat scratchpads). A user globbing for
    // every channel name would be confused if simple PVs were
    // hidden. Field lookup via `get_record` follows alias→canonical
    // (round 7); for simple PVs the field-dump branch silently
    // skips since they're not records.
    let mut names = ctx.block_on(ctx.db().all_record_names());
    names.extend(ctx.block_on(ctx.db().all_alias_names()));
    names.extend(ctx.block_on(ctx.db().all_simple_pv_names()));
    names.sort();
    names.dedup();

    let mut count = 0;
    for name in &names {
        if !glob_match(pattern, name) {
            continue;
        }
        ctx.println(name);
        count += 1;
        if fields.is_empty() {
            continue;
        }
        // Dump each requested field for this record.
        if let Some(rec_arc) = ctx.block_on(ctx.db().get_record(name)) {
            let inst = ctx.block_on(rec_arc.read());
            for fname in &fields {
                let value = inst
                    .record
                    .get_field(fname)
                    .map(|v| format!("{v:?}"))
                    .unwrap_or_else(|| "<no field>".to_string());
                ctx.println(&format!("  {fname:>8}: {value}"));
            }
        }
    }
    ctx.println(&format!("Total: {count} records"));
    Ok(CommandOutcome::Continue)
}

/// `dbsr [interest level]` — Database Server Report.
///
/// H-6: C `dbIocRegister.c:142-144` registers `dbsr` as the *Database
/// Server Report* (`dbServerReport` — prints CA/PVA server status and
/// connected-client information). The Rust port previously aliased
/// `dbsr` to the record-name glob search, which is the wrong command
/// (`dbgrep`/`dbglob` is the name search — kept below).
///
/// This crate has no live CA-server client registry reachable from the
/// iocsh `CommandContext` (only `PvDatabase`), so the connected-client
/// detail a C `dbsr` prints is unavailable here. The report covers what
/// the database server *can* expose: the channel population it serves.
fn cmd_dbsr() -> CommandDef {
    CommandDef::new(
        "dbsr",
        vec![ArgDesc {
            name: "interest level",
            arg_type: ArgType::Int,
            optional: true,
        }],
        "dbsr [interest level] — Database Server Report (served-channel statistics)",
        |_args: &[ArgValue], ctx: &CommandContext| {
            let records = ctx.block_on(ctx.db().all_record_names());
            let aliases = ctx.block_on(ctx.db().all_alias_names());
            let simple = ctx.block_on(ctx.db().all_simple_pv_names());
            ctx.println("Database Server Report");
            ctx.println(&format!("  Records served:     {}", records.len()));
            ctx.println(&format!("  Record aliases:     {}", aliases.len()));
            ctx.println(&format!("  Simple PVs served:  {}", simple.len()));
            ctx.println(&format!(
                "  Total channels:     {}",
                records.len() + aliases.len() + simple.len()
            ));
            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_dbglob() -> CommandDef {
    CommandDef::new(
        "dbglob",
        vec![
            ArgDesc {
                name: "pattern",
                arg_type: ArgType::String,
                optional: true,
            },
            ArgDesc {
                name: "fields",
                arg_type: ArgType::String,
                optional: true,
            },
        ],
        "dbglob [pattern] [fields] — Search records by name pattern \
         (epics-base PR #626; `?` matches 0-or-1 chars)",
        dbsr_handler,
    )
}

fn cmd_dbgrep() -> CommandDef {
    CommandDef::new(
        "dbgrep",
        vec![
            ArgDesc {
                name: "pattern",
                arg_type: ArgType::String,
                optional: true,
            },
            ArgDesc {
                name: "fields",
                arg_type: ArgType::String,
                optional: true,
            },
        ],
        "dbgrep [pattern] [fields] — Search records by name pattern \
         (legacy spelling of dbglob, epics-base PR #626)",
        dbsr_handler,
    )
}

fn cmd_scanppl() -> CommandDef {
    CommandDef::new(
        "scanppl",
        vec![],
        "scanppl — Print scan phase lists",
        |_args: &[ArgValue], ctx: &CommandContext| {
            use crate::server::record::ScanType;
            let scan_types = [
                ScanType::Sec01,
                ScanType::Sec02,
                ScanType::Sec05,
                ScanType::Sec1,
                ScanType::Sec2,
                ScanType::Sec5,
                ScanType::Sec10,
                ScanType::Event,
                ScanType::Passive,
            ];

            for st in &scan_types {
                let names = ctx.block_on(ctx.db().records_for_scan(*st));
                if !names.is_empty() {
                    ctx.println(&format!("{st}: {} records", names.len()));
                    for name in &names {
                        ctx.println(&format!("  {name}"));
                    }
                }
            }

            let io_count = ctx
                .block_on(ctx.db().records_for_scan(ScanType::IoIntr))
                .len();
            if io_count > 0 {
                ctx.println(&format!("I/O Intr: {io_count} records"));
            }
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `pushd [dir]` — push the current directory onto the stack and `cd`.
/// With no argument, swaps the current dir with the top of the stack.
fn cmd_pushd() -> CommandDef {
    CommandDef::new(
        "pushd",
        vec![ArgDesc {
            name: "dir",
            arg_type: ArgType::String,
            optional: true,
        }],
        "pushd [dir] — push current dir onto stack and cd to <dir>",
        |args: &[ArgValue], ctx: &CommandContext| {
            let cwd = match std::env::current_dir() {
                Ok(p) => p,
                Err(e) => {
                    ctx.println(&format!("pushd: cannot read cwd: {e}"));
                    return Ok(CommandOutcome::Continue);
                }
            };
            match &args[0] {
                ArgValue::String(dir) => {
                    if let Err(e) = std::env::set_current_dir(dir) {
                        ctx.println(&format!("pushd: {dir}: {e}"));
                        return Ok(CommandOutcome::Continue);
                    }
                    dir_stack().lock().unwrap().push(cwd);
                }
                _ => {
                    // No arg: swap cwd with top of stack.
                    let mut stack = dir_stack().lock().unwrap();
                    let Some(top) = stack.pop() else {
                        ctx.println("pushd: directory stack empty");
                        return Ok(CommandOutcome::Continue);
                    };
                    if let Err(e) = std::env::set_current_dir(&top) {
                        // Restore on failure.
                        stack.push(top);
                        ctx.println(&format!("pushd: {e}"));
                        return Ok(CommandOutcome::Continue);
                    }
                    stack.push(cwd);
                }
            }
            print_stack(ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `popd` — pop the top of the directory stack and `cd` to it.
fn cmd_popd() -> CommandDef {
    CommandDef::new(
        "popd",
        vec![],
        "popd — pop top of directory stack and cd to it",
        |_args: &[ArgValue], ctx: &CommandContext| {
            let mut stack = dir_stack().lock().unwrap();
            let Some(top) = stack.pop() else {
                ctx.println("popd: directory stack empty");
                return Ok(CommandOutcome::Continue);
            };
            if let Err(e) = std::env::set_current_dir(&top) {
                // Restore the entry — failed cd must not lose stack state.
                stack.push(top);
                ctx.println(&format!("popd: {e}"));
                return Ok(CommandOutcome::Continue);
            }
            drop(stack);
            print_stack(ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `dirs` — list the directory stack (cwd + saved entries).
fn cmd_dirs() -> CommandDef {
    CommandDef::new(
        "dirs",
        vec![],
        "dirs — list the iocsh directory stack",
        |_args: &[ArgValue], ctx: &CommandContext| {
            print_stack(ctx);
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `dbCreateRecord <type> <name>` — create a new record at runtime.
///
/// Mirrors epics-base PR #812. Validates the name with the same rules
/// as `parse_db` (PR #78), refuses duplicate names, and routes the
/// instantiation through the same factory registry as `dbLoadRecords`.
fn cmd_db_create_record() -> CommandDef {
    CommandDef::new(
        "dbCreateRecord",
        vec![
            ArgDesc {
                name: "recordType",
                arg_type: ArgType::String,
                optional: false,
            },
            ArgDesc {
                name: "recordName",
                arg_type: ArgType::String,
                optional: false,
            },
        ],
        "dbCreateRecord <type> <name> — Create a new record of <type> at runtime",
        |args: &[ArgValue], ctx: &CommandContext| {
            let rec_type = match &args[0] {
                ArgValue::String(s) => s.clone(),
                _ => {
                    ctx.println("dbCreateRecord: missing recordType");
                    return Ok(CommandOutcome::Continue);
                }
            };
            let name = match &args[1] {
                ArgValue::String(s) => s.clone(),
                _ => {
                    ctx.println("dbCreateRecord: missing recordName");
                    return Ok(CommandOutcome::Continue);
                }
            };
            if let Err(e) = db_loader::validate_record_name(&name, 0, 0) {
                ctx.println(&format!("dbCreateRecord: {e}"));
                return Ok(CommandOutcome::Continue);
            }
            if ctx.block_on(ctx.db().get_record(&name)).is_some() {
                ctx.println(&format!("dbCreateRecord: record '{name}' already exists"));
                return Ok(CommandOutcome::Continue);
            }
            let record = match db_loader::create_record(&rec_type) {
                Ok(r) => r,
                Err(e) => {
                    ctx.println(&format!("dbCreateRecord: {e}"));
                    return Ok(CommandOutcome::Continue);
                }
            };
            if let Err(e) = ctx.block_on(ctx.db().add_record(&name, record)) {
                ctx.println(&format!("dbCreateRecord: {e}"));
                return Ok(CommandOutcome::Continue);
            }
            ctx.println(&format!("dbCreateRecord: created '{name}' ({rec_type})"));
            Ok(CommandOutcome::Continue)
        },
    )
}

/// `postEvent [event]` — process records scanned on a software event.
///
/// L-2: C `dbIocRegister.c` registers this command as `postEvent`
/// (camelCase); the Rust port previously registered the documented
/// name with an underscore (`post_event`), so an `st.cmd` calling the
/// real name hit "unknown command". Both spellings are registered now
/// — `postEvent` is the canonical C name, `post_event` is kept as a
/// back-compat alias for any existing Rust-side scripts.
fn cmd_post_event() -> CommandDef {
    CommandDef::new(
        "postEvent",
        vec![ArgDesc {
            name: "event",
            arg_type: ArgType::Int,
            optional: true,
        }],
        "postEvent [event] — Process records with SCAN=Event",
        post_event_handler,
    )
}

fn cmd_post_event_alias() -> CommandDef {
    CommandDef::new(
        "post_event",
        vec![ArgDesc {
            name: "event",
            arg_type: ArgType::Int,
            optional: true,
        }],
        "post_event [event] — Back-compat alias of postEvent",
        post_event_handler,
    )
}

fn post_event_handler(args: &[ArgValue], ctx: &CommandContext) -> CommandResult {
    // C `dbIocRegister.c` `postEvent <event>` routes through
    // `post_event(int)` -> `postEvent(pevent_list[event])`, posting
    // ONLY the records whose `EVNT` matches that event. Route to
    // `post_event_named` when an event argument is given; with no
    // argument fall back to the (non-C) "process every Event record".
    match args.first() {
        Some(ArgValue::Int(event)) => {
            ctx.block_on(ctx.db().post_event_named(&event.to_string()));
            ctx.println(&format!("Posted event {event}"));
        }
        Some(ArgValue::String(name)) if !name.is_empty() => {
            ctx.block_on(ctx.db().post_event_named(name));
            ctx.println(&format!("Posted event {name}"));
        }
        _ => {
            ctx.block_on(ctx.db().post_event());
            ctx.println("Event scan processed (all SCAN=Event records)");
        }
    }
    Ok(CommandOutcome::Continue)
}

/// Simple glob matching (* and ? wildcards).
fn glob_match(pattern: &str, text: &str) -> bool {
    let mut pi = pattern.chars().peekable();
    let mut ti = text.chars().peekable();

    fn do_match(
        pat: &mut std::iter::Peekable<std::str::Chars>,
        txt: &mut std::iter::Peekable<std::str::Chars>,
    ) -> bool {
        while let Some(&pc) = pat.peek() {
            match pc {
                '*' => {
                    pat.next();
                    if pat.peek().is_none() {
                        return true; // trailing * matches everything
                    }
                    // Try matching rest from every position
                    loop {
                        let mut pat_clone = pat.clone();
                        let mut txt_clone = txt.clone();
                        if do_match(&mut pat_clone, &mut txt_clone) {
                            return true;
                        }
                        if txt.next().is_none() {
                            return false;
                        }
                    }
                }
                '?' => {
                    // L-1: C `dbglob` documents `?` as matching "0 or
                    // one characters" (dbIocRegister.c:246-248), not
                    // exactly one. Try both the skip-zero and
                    // consume-one branches.
                    pat.next();
                    {
                        let mut pat_zero = pat.clone();
                        let mut txt_zero = txt.clone();
                        if do_match(&mut pat_zero, &mut txt_zero) {
                            return true;
                        }
                    }
                    if txt.next().is_none() {
                        return false;
                    }
                }
                c => {
                    pat.next();
                    match txt.next() {
                        Some(tc) if tc == c => {}
                        _ => return false,
                    }
                }
            }
        }
        txt.peek().is_none()
    }

    do_match(&mut pi, &mut ti)
}

fn cmd_ioc_stats() -> CommandDef {
    CommandDef::new(
        "iocStats",
        vec![],
        "iocStats — Show IOC runtime statistics",
        |_args: &[ArgValue], ctx: &CommandContext| {
            // Record count
            let names = ctx.block_on(ctx.db().all_record_names());
            ctx.println(&format!("Records:    {}", names.len()));

            // Uptime
            static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
            let start = START.get_or_init(std::time::Instant::now);
            let uptime = start.elapsed();
            let hours = uptime.as_secs() / 3600;
            let mins = (uptime.as_secs() % 3600) / 60;
            let secs = uptime.as_secs() % 60;
            ctx.println(&format!("Uptime:     {hours}h {mins}m {secs}s"));

            // Memory (RSS) — read from /proc on Linux, skip on other platforms
            #[cfg(target_os = "linux")]
            if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
                for line in status.lines() {
                    if let Some(val) = line.strip_prefix("VmRSS:") {
                        ctx.println(&format!("RSS:        {}", val.trim()));
                        break;
                    }
                }
            }

            // Thread count (approximate via tokio metrics if available)
            let threads = std::thread::available_parallelism()
                .map(|p| p.get())
                .unwrap_or(1);
            ctx.println(&format!("CPU cores:  {threads}"));

            // Scan types summary
            use crate::server::record::ScanType;
            let scan_types = [
                ScanType::Sec01,
                ScanType::Sec02,
                ScanType::Sec05,
                ScanType::Sec1,
                ScanType::Sec2,
                ScanType::Sec5,
                ScanType::Sec10,
            ];
            let mut total_scanned = 0;
            for st in &scan_types {
                total_scanned += ctx.block_on(ctx.db().records_for_scan(*st)).len();
            }
            let io_intr = ctx
                .block_on(ctx.db().records_for_scan(ScanType::IoIntr))
                .len();
            ctx.println(&format!("Periodic:   {total_scanned} records"));
            ctx.println(&format!("I/O Intr:   {io_intr} records"));

            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_db_load_records() -> CommandDef {
    CommandDef::new(
        "dbLoadRecords",
        vec![
            ArgDesc {
                name: "file",
                arg_type: ArgType::String,
                optional: false,
            },
            ArgDesc {
                name: "macros",
                arg_type: ArgType::String,
                optional: true,
            },
        ],
        "dbLoadRecords file [macros] - Load records from a .db/.template file",
        |args: &[ArgValue], ctx: &CommandContext| {
            let path = match &args[0] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };
            let macros_str = match &args[1] {
                ArgValue::String(s) => s.as_str(),
                _ => "",
            };

            let macros = parse_macro_string(macros_str);

            // Build include config from EPICS_DB_INCLUDE_PATH
            let include_paths: Vec<std::path::PathBuf> =
                if let Ok(val) = std::env::var("EPICS_DB_INCLUDE_PATH") {
                    split_db_paths(&val)
                } else {
                    Vec::new()
                };
            let config = db_loader::DbLoadConfig {
                include_paths,
                max_include_depth: 32,
            };

            // Resolve the template file path: check if it exists directly,
            // otherwise search EPICS_DB_INCLUDE_PATH (matching C dbLoadRecords behavior)
            let file_path = {
                let p = std::path::Path::new(path);
                if p.exists() {
                    p.to_path_buf()
                } else if !p.is_absolute() {
                    // Search include paths for relative filenames
                    let mut resolved = None;
                    for dir in &config.include_paths {
                        let candidate = dir.join(p);
                        if candidate.exists() {
                            resolved = Some(candidate);
                            break;
                        }
                    }
                    resolved.unwrap_or_else(|| p.to_path_buf())
                } else {
                    p.to_path_buf()
                }
            };
            let mut defs = db_loader::parse_db_file(&file_path, &macros, &config)
                .map_err(|e| format!("parse error: {e}"))?;

            // DTYP override: if macros contain DTYP, override existing DTYP fields
            if let Some(dtyp) = macros.get("DTYP") {
                db_loader::override_dtyp(&mut defs, dtyp);
            }

            let count = defs.len();

            for def in defs {
                let added: Result<(), String> = ctx.block_on(async {
                    // C-parity (dbLexRoutines.c:1170-1188): the SAME
                    // record name re-loaded with the SAME record_type
                    // merges fields into the existing instance (the
                    // standard ADCore convention — simDetector.template
                    // overrides ColorMode menu choices declared by its
                    // included NDArrayBase.template). A different
                    // record_type is fatal. `dbRecordsOnceOnly` global
                    // is not yet wired; tighten here if/when needed.
                    let existing = if let Some(rec) = ctx.db().get_record(&def.name).await {
                        let r = rec.read().await;
                        let existing_type = r.record.record_type();
                        if existing_type != def.record_type {
                            return Err(format!(
                                "dbLoadRecords: {} record '{}' already exists, can't load {} record",
                                existing_type, def.name, def.record_type
                            ));
                        }
                        drop(r);
                        Some(rec)
                    } else {
                        None
                    };

                    let mut common_fields = Vec::new();
                    let is_merge = existing.is_some();
                    let rec_arc = if let Some(rec_arc) = existing {
                        // Merge: apply field overrides directly to the
                        // existing record instance. Init_record stays
                        // skipped on merge — it was already run during
                        // the first load, and re-running would clobber
                        // state populated by intervening processing.
                        {
                            let mut inst = rec_arc.write().await;
                            if let Err(e) = db_loader::apply_fields(
                                &mut inst.record,
                                &def.fields,
                                &mut common_fields,
                            ) {
                                return Err(format!("{e}"));
                            }
                        }
                        rec_arc
                    } else {
                        let mut record = db_loader::create_record(&def.record_type)
                            .map_err(|e| format!("{e}"))?;
                        if let Err(e) =
                            db_loader::apply_fields(&mut record, &def.fields, &mut common_fields)
                        {
                            return Err(format!("{e}"));
                        }
                        if let Err(e) = ctx.db().add_record(&def.name, record).await {
                            return Err(format!("dbLoadRecords: '{}' rejected: {e}", def.name));
                        }
                        ctx.db().get_record(&def.name).await.ok_or_else(|| {
                            format!(
                                "dbLoadRecords: '{}' vanished between add_record and get_record",
                                def.name
                            )
                        })?
                    };

                    // Register any aliases declared in the record body
                    // (epics-base PR #336). Failures are reported but
                    // don't abort the load — the record is already in.
                    // For a merge, aliases declared in the new block
                    // are also registered (C parser appends).
                    for alias in &def.aliases {
                        if let Err(e) = ctx.db().add_alias(alias, &def.name).await {
                            eprintln!(
                                "dbLoadRecords: alias '{alias}' for '{}' rejected: {e}",
                                def.name
                            );
                        }
                    }

                    {
                        let mut instance = rec_arc.write().await;
                        // info(key, value) directives — last write
                        // wins. Populated before common-field application
                        // so device support seeing `init_record` can
                        // observe info tags.
                        for (k, v) in &def.info_tags {
                            instance.set_info(k, v);
                        }
                        for (name, value) in common_fields {
                            use crate::server::record::CommonFieldPutResult;
                            match instance.put_common_field(&name, value) {
                                Ok(CommonFieldPutResult::ScanChanged {
                                    old_scan,
                                    new_scan,
                                    phas,
                                }) => {
                                    drop(instance);
                                    ctx.db()
                                        .update_scan_index(
                                            &def.name, old_scan, new_scan, phas, phas,
                                        )
                                        .await;
                                    instance = rec_arc.write().await;
                                }
                                Ok(CommonFieldPutResult::PhasChanged {
                                    scan,
                                    old_phas,
                                    new_phas,
                                }) => {
                                    drop(instance);
                                    ctx.db()
                                        .update_scan_index(
                                            &def.name, scan, scan, old_phas, new_phas,
                                        )
                                        .await;
                                    instance = rec_arc.write().await;
                                }
                                Ok(CommonFieldPutResult::NoChange) => {}
                                Err(e) => {
                                    eprintln!(
                                        "put_common_field({name}) failed for {}: {e}",
                                        def.name
                                    );
                                }
                            }
                        }
                        // TODO: refactor to global two-pass if inter-record init dependencies arise.
                        // C `iocInit` calls init_record once per record AFTER
                        // all dbLoadRecords blocks, so init_record always
                        // sees the final merged field set. Rust shortcuts by
                        // running init_record inline at dbLoadRecords; on a
                        // merge we re-run it so the new field values
                        // (LINR / ESLO / ZRST / ...) take effect in
                        // convert routines and post-init derived state.
                        // The cost: stateful records (compress accum,
                        // first_output_done) get re-initialised. The
                        // alternative (skip init on merge) silently
                        // ignored field overrides that affect init —
                        // worse for typical use.
                        let _ = is_merge;
                        if let Err(e) = instance.record.init_record(0) {
                            eprintln!("init_record(0) failed for {}: {e}", def.name);
                        }
                        if let Err(e) = instance.record.init_record(1) {
                            eprintln!("init_record(1) failed for {}: {e}", def.name);
                        }
                    }
                    Ok(())
                });
                if let Err(e) = added {
                    // epics-base 144f975: propagate the failure to the
                    // iocsh script chain (equivalent of `iocshSetError`)
                    // so a startup script returns non-zero on a rejected
                    // record load. The printed message stays for
                    // operator-visible diagnostics; the `Err` return
                    // lets `execute_script` mark its `last_err`.
                    ctx.println(&e);
                    return Err(e);
                }
            }

            ctx.println(&format!("Loaded {count} record(s) from {path}"));
            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_epics_env_set() -> CommandDef {
    CommandDef::new(
        "epicsEnvSet",
        vec![
            ArgDesc {
                name: "name",
                arg_type: ArgType::String,
                optional: false,
            },
            ArgDesc {
                name: "value",
                arg_type: ArgType::String,
                optional: false,
            },
        ],
        "epicsEnvSet name value - Set an environment variable",
        |args: &[ArgValue], _ctx: &CommandContext| {
            let name = match &args[0] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };
            let value = match &args[1] {
                ArgValue::String(s) => s,
                _ => return Err("invalid argument".to_string()),
            };

            // SAFETY: We're single-threaded in the REPL, and this matches C EPICS behavior
            unsafe { std::env::set_var(name, value) };
            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_ioc_init() -> CommandDef {
    CommandDef::new(
        "iocInit",
        vec![],
        "iocInit - Initialize the IOC (handled automatically by IocApplication)",
        |_args: &[ArgValue], ctx: &CommandContext| {
            ctx.println("iocInit: skipped (handled automatically after script execution)");
            Ok(CommandOutcome::Continue)
        },
    )
}

fn cmd_exit() -> CommandDef {
    CommandDef::new(
        "exit",
        vec![],
        "exit - Exit the IOC shell",
        |_args: &[ArgValue], _ctx: &CommandContext| Ok(CommandOutcome::Exit),
    )
}

/// C-style escape a CHAR-array buffer for `dbgf` output (epics-base
/// dc70dfd6). Printable ASCII passes through; well-known C escapes
/// (`\n`, `\t`, `\r`, `\\`, `\"`, `\a`, `\b`, `\f`, `\v`) get their
/// short form; everything else is rendered as `\xNN`. Mirrors
/// `epicsStrnEscapedFromRaw` exactly enough for the dbgf use case —
/// the surrounding quote pair is added by the caller.
fn escape_char_array_for_dbgf(buf: &[u8]) -> String {
    let mut out = String::with_capacity(buf.len());
    for &b in buf {
        match b {
            b'\n' => out.push_str("\\n"),
            b'\t' => out.push_str("\\t"),
            b'\r' => out.push_str("\\r"),
            b'\\' => out.push_str("\\\\"),
            b'"' => out.push_str("\\\""),
            0x07 => out.push_str("\\a"),
            0x08 => out.push_str("\\b"),
            0x0c => out.push_str("\\f"),
            0x0b => out.push_str("\\v"),
            0x20..=0x7e => out.push(b as char),
            _ => out.push_str(&format!("\\x{b:02x}")),
        }
    }
    out
}

/// Parse a macro string like "P=IOC:,R=TEMP" into a HashMap.
/// Macro values may reference environment variables via `$(ENVVAR)`.
pub(super) fn parse_macro_string(s: &str) -> HashMap<String, String> {
    let mut macros = HashMap::new();
    if s.is_empty() {
        return macros;
    }
    for pair in s.split(',') {
        if let Some((k, v)) = pair.split_once('=') {
            macros.insert(
                k.trim().to_string(),
                super::registry::substitute_env_vars(v.trim()),
            );
        }
    }
    macros
}

#[cfg(test)]
mod field_suggestion_tests {
    use super::edit_distance_short;

    #[test]
    fn edit_distance_recognises_simple_typos() {
        // Substitution within budget.
        assert!(edit_distance_short("DSEC", "DESC") <= 2);
        assert!(edit_distance_short("EGUU", "EGU") <= 2);
        // Deletion.
        assert!(edit_distance_short("DESCR", "DESC") <= 2);
        // Long-distance — must exceed 2 so suggester rejects.
        assert!(edit_distance_short("HELLO", "DESC") > 2);
    }

    #[test]
    fn edit_distance_handles_empty_inputs() {
        assert_eq!(edit_distance_short("", ""), 0);
        assert_eq!(edit_distance_short("ABC", ""), 3);
        assert_eq!(edit_distance_short("", "XYZ"), 3);
    }
}

#[cfg(test)]
mod dbgf_escape_tests {
    use super::escape_char_array_for_dbgf;

    /// epics-base dc70dfd6 — printable ASCII passes through unchanged.
    #[test]
    fn printable_ascii_passes_through() {
        assert_eq!(escape_char_array_for_dbgf(b"hello"), "hello");
        assert_eq!(escape_char_array_for_dbgf(b"a b c"), "a b c");
    }

    /// Common C escapes get their short form.
    #[test]
    fn common_c_escapes() {
        assert_eq!(escape_char_array_for_dbgf(b"a\nb"), "a\\nb");
        assert_eq!(escape_char_array_for_dbgf(b"a\tb"), "a\\tb");
        assert_eq!(escape_char_array_for_dbgf(b"a\rb"), "a\\rb");
        assert_eq!(escape_char_array_for_dbgf(b"a\\b"), "a\\\\b");
        assert_eq!(escape_char_array_for_dbgf(b"a\"b"), "a\\\"b");
        assert_eq!(escape_char_array_for_dbgf(b"a\x07b"), "a\\ab");
        assert_eq!(escape_char_array_for_dbgf(b"a\x08b"), "a\\bb");
        assert_eq!(escape_char_array_for_dbgf(b"a\x0cb"), "a\\fb");
        assert_eq!(escape_char_array_for_dbgf(b"a\x0bb"), "a\\vb");
    }

    /// Other non-printable bytes (and any high-bit byte) become `\xNN`.
    #[test]
    fn other_bytes_use_hex_escape() {
        assert_eq!(escape_char_array_for_dbgf(&[0x01, 0xff]), "\\x01\\xff");
        // DEL (0x7f) is non-printable per the C convention.
        assert_eq!(escape_char_array_for_dbgf(&[0x7f]), "\\x7f");
        // Empty buffer stays empty.
        assert_eq!(escape_char_array_for_dbgf(&[]), "");
    }
}

/// Suggest a field name close to `typo` that actually exists on
/// the record `record_name`. Returns `None` when no candidate is
/// within edit-distance ≤ 2 (Damerau-Levenshtein subset). Mirrors
/// epics-base PR #689 — "did you mean" hint on field-not-found
/// errors. Uppercase comparison so `desc` ≈ `DESC` matches.
async fn suggest_field_name(
    db: &std::sync::Arc<crate::server::database::PvDatabase>,
    record_name: &str,
    typo: &str,
) -> Option<String> {
    let typo_uc = typo.to_ascii_uppercase();
    let rec = db.get_record(record_name).await?;
    let inst = rec.read().await;
    let mut candidates: Vec<&str> = inst.record.field_list().iter().map(|d| d.name).collect();
    // Common dbCommon fields are also valid PUT targets.
    candidates.extend([
        "VAL", "DESC", "EGU", "SCAN", "PINI", "DTYP", "INP", "OUT", "FLNK", "NAME", "RTYP", "PHAS",
        "PRIO", "DISA", "DISV", "DISS", "DISP", "PROC", "ASG", "TPRO", "TSE", "TSEL", "UDF",
        "SEVR", "STAT", "AMSG",
    ]);
    let mut best: Option<(usize, &str)> = None;
    for cand in &candidates {
        let dist = edit_distance_short(&typo_uc, cand);
        if dist > 2 {
            continue;
        }
        match best {
            None => best = Some((dist, cand)),
            Some((d, _)) if dist < d => best = Some((dist, cand)),
            _ => {}
        }
    }
    best.map(|(_, name)| name.to_string())
}

/// Bounded Damerau-Levenshtein for short ASCII strings used by
/// `suggest_field_name`. Returns the edit distance; cap at
/// `a.len() + b.len()` so the loop never blows up.
fn edit_distance_short(a: &str, b: &str) -> usize {
    if a == b {
        return 0;
    }
    let a: Vec<u8> = a.bytes().collect();
    let b: Vec<u8> = b.bytes().collect();
    if a.is_empty() || b.is_empty() {
        return a.len().max(b.len());
    }
    let mut prev = (0..=b.len()).collect::<Vec<usize>>();
    let mut curr = vec![0; b.len() + 1];
    for (i, ai) in a.iter().enumerate() {
        curr[0] = i + 1;
        for (j, bj) in b.iter().enumerate() {
            let cost = if ai == bj { 0 } else { 1 };
            curr[j + 1] = (curr[j] + 1).min(prev[j + 1] + 1).min(prev[j] + cost);
            // Damerau transposition.
            if i > 0 && j > 0 && a[i] == b[j - 1] && a[i - 1] == b[j] {
                // prev2 not tracked; skip the pure-Damerau optimization
                // and rely on the Levenshtein floor — we only care that
                // small typos like "DSEC"↔"DESC" are within ≤2.
            }
            let _ = cost;
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[b.len()]
}

/// Get a display name for the DBF type of a value.
fn dbf_type_name(val: &EpicsValue) -> &'static str {
    match val {
        EpicsValue::String(_) => "DBF_STRING",
        EpicsValue::Short(_) => "DBF_SHORT",
        EpicsValue::Float(_) => "DBF_FLOAT",
        EpicsValue::Enum(_) => "DBF_ENUM",
        EpicsValue::Char(_) => "DBF_CHAR",
        EpicsValue::Long(_) => "DBF_LONG",
        EpicsValue::Double(_) => "DBF_DOUBLE",
        EpicsValue::Int64(_) | EpicsValue::Int64Array(_) => "DBF_INT64",
        EpicsValue::UInt64(_) | EpicsValue::UInt64Array(_) => "DBF_UINT64",
        EpicsValue::ShortArray(_) => "DBF_SHORT",
        EpicsValue::FloatArray(_) => "DBF_FLOAT",
        EpicsValue::EnumArray(_) => "DBF_ENUM",
        EpicsValue::DoubleArray(_) => "DBF_DOUBLE",
        EpicsValue::LongArray(_) => "DBF_LONG",
        EpicsValue::CharArray(_) => "DBF_CHAR",
        EpicsValue::StringArray(_) => "DBF_STRING",
    }
}

/// Split `EPICS_DB_INCLUDE_PATH` into individual paths.
///
/// Supports both `;`-separated (Windows convention) and `:`-separated (Unix convention)
/// path lists. When splitting on `:`, a single ASCII letter followed by `:` is treated
/// as a Windows drive letter and is NOT used as a split point.
fn split_db_paths(val: &str) -> Vec<std::path::PathBuf> {
    if val.contains(';') {
        return val
            .split(';')
            .filter(|s| !s.is_empty())
            .map(std::path::PathBuf::from)
            .collect();
    }
    let mut paths = Vec::new();
    let mut current = String::new();
    for ch in val.chars() {
        if ch == ':' {
            let is_drive = current.len() == 1
                && current
                    .chars()
                    .next()
                    .map(|c| c.is_ascii_alphabetic())
                    .unwrap_or(false);
            if is_drive {
                current.push(':');
            } else {
                if !current.is_empty() {
                    paths.push(std::path::PathBuf::from(&current));
                    current.clear();
                }
            }
        } else {
            current.push(ch);
        }
    }
    if !current.is_empty() {
        paths.push(std::path::PathBuf::from(current));
    }
    paths
}

/// Map common field names to their DBF types.
fn common_field_dbf_type(field: &str) -> Option<crate::types::DbFieldType> {
    use crate::types::DbFieldType;
    match field {
        "SCAN" => Some(DbFieldType::String),
        "DTYP" => Some(DbFieldType::String),
        "INP" | "OUT" | "FLNK" | "ASG" => Some(DbFieldType::String),
        "SEVR" | "STAT" => Some(DbFieldType::Short),
        "UDF" | "PINI" | "TPRO" => Some(DbFieldType::Char),
        "HIHI" | "HIGH" | "LOW" | "LOLO" => Some(DbFieldType::Double),
        "HHSV" | "HSV" | "LSV" | "LLSV" => Some(DbFieldType::Short),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::database::PvDatabase;
    use crate::server::records::ai::AiRecord;
    use crate::types::EpicsValue;
    use std::sync::Arc;

    fn make_ctx() -> (Arc<PvDatabase>, CommandContext) {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let db = Arc::new(PvDatabase::new());
        let handle = rt.handle().clone();
        let ctx = CommandContext::new(db.clone(), handle);
        // Leak the runtime so it stays alive for the test
        std::mem::forget(rt);
        (db, ctx)
    }

    #[test]
    fn test_dbl() {
        let (db, ctx) = make_ctx();
        ctx.block_on(async {
            db.add_record("REC_A", Box::new(AiRecord::new(1.0)))
                .await
                .unwrap();
            db.add_record("REC_B", Box::new(AiRecord::new(2.0)))
                .await
                .unwrap();
        });

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbl").unwrap();
        let args = parse_args(&[], &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(matches!(result, Ok(CommandOutcome::Continue)));
    }

    #[test]
    fn test_dbgf() {
        let (db, ctx) = make_ctx();
        ctx.block_on(async {
            db.add_record("TEMP", Box::new(AiRecord::new(25.0)))
                .await
                .unwrap();
        });

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbgf").unwrap();
        let tokens = vec!["TEMP".to_string()];
        let args = parse_args(&tokens, &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(matches!(result, Ok(CommandOutcome::Continue)));
    }

    #[test]
    fn test_dbgf_not_found() {
        let (_db, ctx) = make_ctx();

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbgf").unwrap();
        let tokens = vec!["NONEXISTENT".to_string()];
        let args = parse_args(&tokens, &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_dbpf_and_readback() {
        let (db, ctx) = make_ctx();
        ctx.block_on(async {
            db.add_record("TEMP", Box::new(AiRecord::new(0.0)))
                .await
                .unwrap();
        });

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);

        // Put a value
        let cmd = registry.get("dbpf").unwrap();
        let tokens = vec!["TEMP".to_string(), "42.0".to_string()];
        let args = parse_args(&tokens, &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(matches!(result, Ok(CommandOutcome::Continue)));

        // Read back
        let val = ctx.block_on(db.get_pv("TEMP")).unwrap();
        match val {
            EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
            other => panic!("expected Double(42.0), got {:?}", other),
        }
    }

    #[test]
    fn test_dbpr_levels() {
        let (db, ctx) = make_ctx();
        ctx.block_on(async {
            db.add_record("TEMP", Box::new(AiRecord::new(25.0)))
                .await
                .unwrap();
        });

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);

        for level in [0, 1, 2] {
            let cmd = registry.get("dbpr").unwrap();
            let tokens = vec!["TEMP".to_string(), level.to_string()];
            let args = parse_args(&tokens, &cmd.args).unwrap();
            let result = cmd.handler.call(&args, &ctx);
            assert!(matches!(result, Ok(CommandOutcome::Continue)));
        }
    }

    #[test]
    fn test_dbl_filter_by_type() {
        let (db, ctx) = make_ctx();
        ctx.block_on(async {
            db.add_record("AI_REC", Box::new(AiRecord::new(1.0)))
                .await
                .unwrap();
            db.add_record(
                "BO_REC",
                Box::new(crate::server::records::bo::BoRecord::new(0)),
            )
            .await
            .unwrap();
        });

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbl").unwrap();
        let tokens = vec!["ai".to_string()];
        let args = parse_args(&tokens, &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(matches!(result, Ok(CommandOutcome::Continue)));
    }

    #[test]
    fn test_exit() {
        let (_db, ctx) = make_ctx();
        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("exit").unwrap();
        let args = parse_args(&[], &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(matches!(result, Ok(CommandOutcome::Exit)));
    }

    /// C `dbLexRoutines.c:1170-1188` parity: dbLoadRecords MUST allow
    /// the same record name to be re-loaded with the SAME record type
    /// and merge fields into the existing instance. ADCore convention
    /// (simDetector.template overriding ColorMode menu from the
    /// included NDArrayBase.template) depends on this.
    #[test]
    fn test_db_load_records_same_type_duplicate_merges_fields() {
        use std::io::Write;
        let (db, ctx) = make_ctx();

        // Write a tiny .db with the duplicate-record pattern: an mbbo
        // declared twice, with the second block overriding ZRST.
        let tmp = tempfile::Builder::new()
            .suffix(".db")
            .tempfile()
            .expect("tempfile");
        writeln!(
            tmp.as_file(),
            r#"
record(mbbo, "DUP:CM") {{
    field(DESC, "first")
    field(ZRST, "Mono")
    field(ONST, "Bayer")
}}

record(mbbo, "DUP:CM") {{
    field(DESC, "second")
    field(ZRST, "Mono-Override")
}}
"#
        )
        .expect("write tempfile");

        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbLoadRecords").unwrap();
        let args = parse_args(&[tmp.path().to_string_lossy().to_string()], &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        assert!(
            matches!(result, Ok(CommandOutcome::Continue)),
            "merge-duplicate must succeed; got Err? {}",
            result.is_err()
        );

        ctx.block_on(async {
            let rec = db
                .get_record("DUP:CM")
                .await
                .expect("DUP:CM must be registered exactly once");
            let inst = rec.read().await;
            // Last-write-wins: DESC + ZRST should reflect the SECOND
            // record block. ONST stays from the FIRST block since
            // the second didn't override it.
            assert_eq!(inst.common.desc, "second", "second block's DESC must win");
            assert_eq!(
                inst.record.get_field("ZRST"),
                Some(crate::types::EpicsValue::String("Mono-Override".into())),
                "second block's ZRST must override the first"
            );
            assert_eq!(
                inst.record.get_field("ONST"),
                Some(crate::types::EpicsValue::String("Bayer".into())),
                "ONST from first block survives (no override)"
            );
        });
    }

    /// Different record type for the same name is fatal — mirrors C
    /// `dbLexRoutines.c:1173-1180` "record '%s' already exists, can't
    /// load %s record".
    #[test]
    fn test_db_load_records_different_type_duplicate_rejected() {
        use std::io::Write;
        let (db, ctx) = make_ctx();
        // Pre-register DUP:CM as an `ai`.
        ctx.block_on(async {
            db.add_record("DUP:CM", Box::new(AiRecord::new(0.0)))
                .await
                .unwrap();
        });
        let tmp = tempfile::Builder::new()
            .suffix(".db")
            .tempfile()
            .expect("tempfile");
        writeln!(
            tmp.as_file(),
            r#"
record(mbbo, "DUP:CM") {{
    field(ZRST, "Mono")
}}
"#
        )
        .expect("write tempfile");
        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let cmd = registry.get("dbLoadRecords").unwrap();
        let args = parse_args(&[tmp.path().to_string_lossy().to_string()], &cmd.args).unwrap();
        let result = cmd.handler.call(&args, &ctx);
        match result {
            Err(e) => assert!(
                e.contains("already exists, can't load mbbo"),
                "expected type-mismatch error; got {e}"
            ),
            Ok(_) => panic!("different-type duplicate must error, but call succeeded"),
        }
    }

    #[test]
    fn test_help_registered() {
        let mut registry = CommandRegistry::new();
        register_builtins(&mut registry);
        let names = registry.list();
        assert!(names.contains(&"help"));
        assert!(names.contains(&"dbl"));
        assert!(names.contains(&"dbgf"));
        assert!(names.contains(&"dbpf"));
        assert!(names.contains(&"dbpr"));
        assert!(names.contains(&"dbLoadRecords"));
        assert!(names.contains(&"epicsEnvSet"));
        assert!(names.contains(&"exit"));
    }

    #[test]
    fn test_split_db_paths_unix() {
        let paths = split_db_paths("/opt/epics/db:/home/user/db");
        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0], std::path::PathBuf::from("/opt/epics/db"));
        assert_eq!(paths[1], std::path::PathBuf::from("/home/user/db"));
    }

    #[test]
    fn test_split_db_paths_windows_semicolon() {
        let paths = split_db_paths(r"C:\epics\db;D:\user\db");
        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0], std::path::PathBuf::from(r"C:\epics\db"));
        assert_eq!(paths[1], std::path::PathBuf::from(r"D:\user\db"));
    }

    #[test]
    fn test_split_db_paths_windows_colon_separator() {
        // st.cmd uses ':' separator even on Windows — must not split inside drive letter
        let paths = split_db_paths(r"C:\epics\db:D:\user\db");
        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0], std::path::PathBuf::from(r"C:\epics\db"));
        assert_eq!(paths[1], std::path::PathBuf::from(r"D:\user\db"));
    }

    #[test]
    fn test_split_db_paths_single() {
        let paths = split_db_paths("/opt/epics/db");
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], std::path::PathBuf::from("/opt/epics/db"));
    }

    #[test]
    fn test_split_db_paths_empty() {
        let paths = split_db_paths("");
        assert!(paths.is_empty());
    }

    #[test]
    fn test_parse_macro_string() {
        let macros = parse_macro_string("P=IOC:,R=TEMP");
        assert_eq!(macros.get("P").unwrap(), "IOC:");
        assert_eq!(macros.get("R").unwrap(), "TEMP");

        let empty = parse_macro_string("");
        assert!(empty.is_empty());
    }
}