selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
//! Telemetry & Observability
//!
//! Provides structured logging and tracing for agent operations.
//! Features:
//! - Tool execution spans with timing
//! - Agent state transition logging
//! - Success/failure recording
//! - Configurable log levels via RUST_LOG
//! - Configurable sampling rate for non-error events
//! - Log rotation with configurable entry limits

use metrics_exporter_prometheus::PrometheusBuilder;
use regex::Regex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;
use tracing::Instrument;
use tracing::{error, info, info_span, Span};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

/// Maximum number of in-memory log entries before rotation.
/// When this limit is reached, `rotate_if_needed()` will discard the oldest half.
pub const MAX_LOG_ENTRIES: usize = 100_000;

/// Global telemetry sampling rate stored as fixed-point (rate * 1_000_000).
/// Defaults to 1_000_000 (= 1.0 = 100%). When set below 1.0, only a fraction
/// of non-error events are logged.
static SAMPLING_RATE_MICRO: AtomicU64 = AtomicU64::new(1_000_000);

/// Simple counter for deterministic sampling when rand is not desired.
static SAMPLE_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Set the telemetry sampling rate. `rate` must be in `0.0..=1.0`.
/// A rate of 1.0 means all events are logged; 0.5 means ~50% of non-error
/// events are logged.
pub fn set_sampling_rate(rate: f64) {
    let clamped = rate.clamp(0.0, 1.0);
    SAMPLING_RATE_MICRO.store((clamped * 1_000_000.0) as u64, Ordering::Relaxed);
}

/// Get the current telemetry sampling rate as a float in `0.0..=1.0`.
pub fn sampling_rate() -> f64 {
    SAMPLING_RATE_MICRO.load(Ordering::Relaxed) as f64 / 1_000_000.0
}

/// Returns `true` if the current non-error event should be sampled (logged).
/// Always returns `true` when the rate is 1.0. Uses a simple counter-based
/// approach that is deterministic and does not require the `rand` crate at
/// this call site.
pub fn should_sample() -> bool {
    let rate_micro = SAMPLING_RATE_MICRO.load(Ordering::Relaxed);
    if rate_micro >= 1_000_000 {
        return true;
    }
    if rate_micro == 0 {
        return false;
    }
    // Counter-based: sample if (counter % 1_000_000) < rate_micro
    let count = SAMPLE_COUNTER.fetch_add(1, Ordering::Relaxed);
    (count % 1_000_000) < rate_micro
}

/// Guard for the non-blocking tracing writer's background thread.
/// Stored here instead of being leaked so it can be dropped for clean shutdown.
static TRACING_GUARD: OnceLock<Mutex<Option<tracing_appender::non_blocking::WorkerGuard>>> =
    OnceLock::new();

/// In-memory log entry buffer for rotation tracking.
static LOG_ENTRY_COUNT: AtomicUsize = AtomicUsize::new(0);

/// Increment the in-memory log entry counter and return the new count.
pub fn increment_log_count() -> usize {
    LOG_ENTRY_COUNT.fetch_add(1, Ordering::Relaxed) + 1
}

/// Get current log entry count.
pub fn log_entry_count() -> usize {
    LOG_ENTRY_COUNT.load(Ordering::Relaxed)
}

/// Check if log rotation is needed and perform it.
/// Returns `true` if rotation was triggered (i.e., entries exceeded `MAX_LOG_ENTRIES`).
/// In the in-memory case this resets the counter to simulate discarding old entries.
/// Callers that maintain their own log buffers should drain old entries when this
/// returns `true`.
pub fn rotate_if_needed() -> bool {
    let mut count = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
    loop {
        if count >= MAX_LOG_ENTRIES {
            match LOG_ENTRY_COUNT.compare_exchange_weak(
                count,
                count / 2,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    info!(
                        "Telemetry log rotation triggered: {} entries exceeded limit, reset to {}",
                        count,
                        count / 2
                    );
                    return true;
                }
                Err(actual) => count = actual,
            }
        } else {
            return false;
        }
    }
}

/// Sanitize a string for safe log output by escaping control characters.
/// Prevents log injection where attackers embed newlines to forge log entries.
pub fn sanitize_for_log(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\x0b' => out.push_str("\\v"),
            '\x0c' => out.push_str("\\f"),
            '\x1b' => out.push_str("\\e"),
            '\x00' => out.push_str("\\0"),
            c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
            _ => out.push(c),
        }
    }
    out
}

/// Compiled regex patterns for secret redaction.
static SECRET_PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();

fn secret_patterns() -> &'static Vec<Regex> {
    SECRET_PATTERNS.get_or_init(|| {
        vec![
            // API keys: sk-..., key-..., token-... followed by alphanumeric chars
            Regex::new(r"(?i)(sk-|key-|token-)[A-Za-z0-9_\-]{8,}").expect("invalid secret regex"),
            // Bearer tokens in Authorization headers
            Regex::new(r"(?i)Bearer\s+[A-Za-z0-9_\-\.]{8,}").expect("invalid bearer regex"),
            // Passwords in connection strings: password=..., passwd=..., pwd=...
            Regex::new(r"(?i)(password|passwd|pwd)\s*=\s*\S+").expect("invalid password regex"),
        ]
    })
}

/// Redact sensitive data patterns from a string before logging.
///
/// Matches API keys (`sk-`, `key-`, `token-` prefixed), Bearer tokens,
/// and passwords in connection strings, replacing them with `[REDACTED]`.
pub fn redact_secrets(input: &str) -> String {
    let mut result = input.to_string();
    for pattern in secret_patterns() {
        result = pattern.replace_all(&result, "[REDACTED]").to_string();
    }
    result
}

/// Initialize global tracing subscriber with configurable output
/// By default, only enables tracing if RUST_LOG is explicitly set
pub fn init_tracing() {
    // Initialize tracing if RUST_LOG or SELFWARE_LOG_LEVEL is set.
    // SELFWARE_LOG_LEVEL serves as a project-specific fallback.
    let filter = std::env::var("RUST_LOG").or_else(|_| std::env::var("SELFWARE_LOG_LEVEL"));
    if let Ok(f) = filter {
        init_tracing_with_filter(&f);
    }
}

/// Initialize tracing only for debug/verbose mode
pub fn init_tracing_verbose() {
    init_tracing_with_filter("info")
}

/// Initialize with custom filter string, file log rotation, and OpenTelemetry
pub fn init_tracing_with_filter(filter: &str) {
    // Skip if already initialized
    use std::sync::Once;
    static INIT: Once = Once::new();

    INIT.call_once(|| {
        let filter_layer = EnvFilter::try_new(filter).unwrap_or_else(|_| EnvFilter::new("warn"));

        let fmt_layer = tracing_subscriber::fmt::layer()
            .with_target(false)
            .with_thread_ids(false)
            .with_thread_names(false)
            .with_file(false)
            .with_line_number(false)
            .with_level(true)
            .compact()
            .with_writer(std::io::stderr); // Write to stderr, not stdout

        // Implement Log Rotation with daily rolling
        let log_dir = dirs::data_local_dir()
            .unwrap_or_else(|| std::path::PathBuf::from("."))
            .join("selfware")
            .join("logs");
        let _ = std::fs::create_dir_all(&log_dir);
        let file_appender = tracing_appender::rolling::daily(log_dir, "selfware.log");
        let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
        // Store the guard so the background thread stays alive; drop via shutdown_tracing()
        let _ = TRACING_GUARD.set(Mutex::new(Some(guard)));

        let file_layer = tracing_subscriber::fmt::layer()
            .with_writer(non_blocking)
            .with_ansi(false)
            .with_file(true)
            .with_line_number(true);

        // OpenTelemetry setup (if endpoint provided via env)
        let subscriber = tracing_subscriber::registry()
            .with(filter_layer)
            .with(fmt_layer)
            .with(file_layer);

        if let Ok(endpoint) = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT") {
            use opentelemetry_otlp::WithExportConfig;
            if let Ok(tracer) = opentelemetry_otlp::new_pipeline()
                .tracing()
                .with_exporter(
                    opentelemetry_otlp::new_exporter()
                        .tonic()
                        .with_endpoint(endpoint),
                )
                .install_batch(opentelemetry_sdk::runtime::Tokio)
            {
                let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
                let _ = subscriber.with(telemetry).try_init();
                return; // Early return to avoid double init
            }
        }

        let _ = subscriber.try_init();
    });
}

/// Flush and shut down the tracing background writer.
/// Call this during graceful shutdown to ensure all logs are flushed.
pub fn shutdown_tracing() {
    if let Some(guard_slot) = TRACING_GUARD.get() {
        if let Ok(mut slot) = guard_slot.lock() {
            drop(slot.take()); // Drop the guard, flushing the writer
        }
    }
}

/// Application-wide metrics counters
pub struct Metrics {
    pub api_requests: AtomicU64,
    pub api_errors: AtomicU64,
    pub tool_executions: AtomicU64,
    pub tool_errors: AtomicU64,
    pub tokens_processed: AtomicU64,
}

static METRICS: Metrics = Metrics {
    api_requests: AtomicU64::new(0),
    api_errors: AtomicU64::new(0),
    tool_executions: AtomicU64::new(0),
    tool_errors: AtomicU64::new(0),
    tokens_processed: AtomicU64::new(0),
};

pub fn increment_api_requests() {
    METRICS.api_requests.fetch_add(1, Ordering::Relaxed);
    metrics::increment_counter!("selfware_api_requests_total");
}
pub fn increment_api_errors() {
    METRICS.api_errors.fetch_add(1, Ordering::Relaxed);
    metrics::increment_counter!("selfware_api_errors_total");
}
pub fn increment_tool_executions() {
    METRICS.tool_executions.fetch_add(1, Ordering::Relaxed);
    metrics::increment_counter!("selfware_tool_executions_total");
}
pub fn increment_tool_errors() {
    METRICS.tool_errors.fetch_add(1, Ordering::Relaxed);
    metrics::increment_counter!("selfware_tool_errors_total");
}
pub fn add_tokens_processed(count: u64) {
    METRICS.tokens_processed.fetch_add(count, Ordering::Relaxed);
    metrics::counter!("selfware_tokens_processed_total", count);
}
pub fn get_metrics() -> &'static Metrics {
    &METRICS
}

/// Start Prometheus Metrics Exporter (if in daemon mode).
///
/// Installs the `metrics-exporter-prometheus` global recorder and binds an
/// HTTP endpoint at `bind_addr` that serves metrics in Prometheus text format.
/// After installation, every call to `increment_api_requests()` etc. is
/// automatically captured and exported.
pub fn start_prometheus_exporter(bind_addr: std::net::SocketAddr) -> anyhow::Result<()> {
    PrometheusBuilder::new()
        .with_http_listener(bind_addr)
        .install()
        .map_err(|e| anyhow::anyhow!("Failed to start Prometheus exporter: {}", e))?;

    // Register metric descriptions so Prometheus shows HELP text.
    metrics::describe_counter!(
        "selfware_api_requests_total",
        "Total number of LLM API requests made"
    );
    metrics::describe_counter!(
        "selfware_api_errors_total",
        "Total number of LLM API errors"
    );
    metrics::describe_counter!(
        "selfware_tool_executions_total",
        "Total number of tool executions"
    );
    metrics::describe_counter!(
        "selfware_tool_errors_total",
        "Total number of tool execution errors"
    );
    metrics::describe_counter!(
        "selfware_tokens_processed_total",
        "Total number of tokens processed"
    );

    Ok(())
}

/// Create a span for tracking tool execution with automatic duration and outcome logging
#[macro_export]
macro_rules! tool_span {
    ($tool_name:expr) => {
        tracing::info_span!(
            "tool_execution",
            tool_name = $tool_name,
            duration_ms = tracing::field::Empty,
            success = tracing::field::Empty,
            error = tracing::field::Empty,
        )
    };
}

/// Middleware for tracking tool execution with full observability
pub async fn track_tool_execution<F, Fut, T, E>(tool_name: &str, f: F) -> Result<T, E>
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = Result<T, E>>,
    E: std::fmt::Display,
{
    let start = Instant::now();
    let safe_name = redact_secrets(&sanitize_for_log(tool_name));
    let span = info_span!(
        "tool.execute",
        tool_name = safe_name.as_str(),
        duration_ms = tracing::field::Empty,
        success = tracing::field::Empty,
        error = tracing::field::Empty,
    );

    increment_tool_executions();

    async {
        info!("Starting tool execution");

        match f().await {
            Ok(result) => {
                let duration = start.elapsed().as_millis() as u64;
                span.record("duration_ms", duration);
                span.record("success", true);
                info!(
                    duration_ms = duration,
                    "Tool execution completed successfully"
                );
                Ok(result)
            }
            Err(e) => {
                increment_tool_errors();
                let duration = start.elapsed().as_millis() as u64;
                let safe_err = redact_secrets(&sanitize_for_log(&e.to_string()));
                span.record("duration_ms", duration);
                span.record("success", false);
                span.record("error", safe_err.as_str());
                error!(
                    duration_ms = duration,
                    error = safe_err.as_str(),
                    "Tool execution failed"
                );
                Err(e)
            }
        }
    }
    .instrument(span.clone())
    .await
}

/// Helper to record success in current span
pub fn record_success() {
    Span::current().record("success", true);
    if should_sample() {
        info!("Operation completed successfully");
    }
    increment_log_count();
}

/// Helper to record failure in current span with error details
pub fn record_failure(error: &str) {
    let safe_err = redact_secrets(&sanitize_for_log(error));
    Span::current().record("success", false);
    Span::current().record("error", safe_err.as_str());
    error!(error = safe_err.as_str(), "Operation failed");
}

/// Span guard for agent loop steps
pub fn enter_agent_step(state: &str, step: usize) -> tracing::span::Span {
    let safe_state = sanitize_for_log(state);
    let span = info_span!("agent.step", state = safe_state.as_str(), step = step,);
    span
}

/// Record agent state transition
pub fn record_state_transition(from: &str, to: &str) {
    let safe_from = sanitize_for_log(from);
    let safe_to = sanitize_for_log(to);
    if should_sample() {
        info!(
            from = safe_from.as_str(),
            to = safe_to.as_str(),
            "Agent state transition"
        );
    }
    increment_log_count();
}

/// Initialize tracing for tests with a simple subscriber
#[cfg(test)]
pub fn init_test_tracing() {
    let _ = tracing_subscriber::fmt()
        .with_test_writer()
        .with_max_level(tracing::Level::DEBUG)
        .try_init();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    fn sampling_test_guard() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .expect("sampling test lock poisoned")
    }

    /// Guard for tests that manipulate LOG_ENTRY_COUNT to prevent concurrent conflicts.
    fn rotation_test_guard() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[test]
    fn test_record_state_transition_does_not_panic() {
        // Just ensure the function doesn't panic
        record_state_transition("Planning", "Executing");
    }

    #[test]
    fn test_enter_agent_step_returns_span() {
        // Ensure enter_agent_step creates a valid span
        let span = enter_agent_step("Executing", 1);
        let _guard = span.enter();
        // Span should be created without panic
    }

    #[test]
    fn test_record_success_does_not_panic() {
        // Just ensure the function doesn't panic
        record_success();
    }

    #[test]
    fn test_record_failure_does_not_panic() {
        // Just ensure the function doesn't panic
        record_failure("test error");
    }

    #[tokio::test]
    async fn test_track_tool_execution_success() {
        let result: Result<i32, &str> =
            track_tool_execution("test_tool", || async { Ok(42) }).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn test_track_tool_execution_failure() {
        let result: Result<i32, &str> =
            track_tool_execution("test_tool", || async { Err("test error") }).await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "test error");
    }

    #[test]
    fn test_init_test_tracing_does_not_panic() {
        // This can be called multiple times safely
        init_test_tracing();
    }

    #[test]
    fn test_tool_span_macro() {
        let span = tool_span!("my_tool");
        let _guard = span.enter();
        // Should create valid span
    }

    #[test]
    fn test_enter_agent_step_different_states() {
        let states = ["Planning", "Executing", "WaitingForTool", "Completed"];
        for (i, state) in states.iter().enumerate() {
            let span = enter_agent_step(state, i);
            let _guard = span.enter();
        }
    }

    #[test]
    fn test_record_state_transition_various() {
        let transitions = [
            ("Idle", "Planning"),
            ("Planning", "Executing"),
            ("Executing", "WaitingForTool"),
            ("WaitingForTool", "Executing"),
            ("Executing", "Completed"),
        ];
        for (from, to) in transitions {
            record_state_transition(from, to);
        }
    }

    #[tokio::test]
    async fn test_track_tool_execution_with_delay() {
        let result: Result<u64, &str> = track_tool_execution("slow_tool", || async {
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            Ok(100u64)
        })
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 100);
    }

    #[test]
    fn test_nested_spans() {
        let outer = enter_agent_step("Outer", 0);
        let _outer_guard = outer.enter();

        let inner = enter_agent_step("Inner", 1);
        let _inner_guard = inner.enter();

        record_success();
    }

    #[test]
    fn test_record_failure_with_various_errors() {
        let errors = [
            "Connection timeout",
            "File not found",
            "Permission denied",
            "",
            "Error with special chars: <>&\"'",
        ];
        for error in errors {
            record_failure(error);
        }
    }

    #[tokio::test]
    async fn test_track_tool_execution_with_string_error() {
        let result: Result<(), String> = track_tool_execution("string_error_tool", || async {
            Err("Custom error message".to_string())
        })
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Custom error message");
    }

    #[test]
    fn test_multiple_init_test_tracing_calls() {
        // Multiple calls should be safe
        init_test_tracing();
        init_test_tracing();
        init_test_tracing();
    }

    #[tokio::test]
    async fn test_track_tool_execution_returns_correct_value() {
        let result: Result<Vec<i32>, &str> =
            track_tool_execution("vec_tool", || async { Ok(vec![1, 2, 3, 4, 5]) }).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![1, 2, 3, 4, 5]);
    }

    #[tokio::test]
    async fn test_track_tool_execution_with_complex_type() {
        #[derive(Debug, PartialEq)]
        struct ComplexResult {
            value: i32,
            name: String,
        }

        let result: Result<ComplexResult, &str> = track_tool_execution("complex_tool", || async {
            Ok(ComplexResult {
                value: 42,
                name: "test".to_string(),
            })
        })
        .await;

        assert!(result.is_ok());
        let res = result.unwrap();
        assert_eq!(res.value, 42);
        assert_eq!(res.name, "test");
    }

    #[tokio::test]
    async fn test_track_tool_execution_error_message_preserved() {
        let error_msg = "Very specific error: code 123";
        let result: Result<(), String> =
            track_tool_execution("error_tool", || async { Err(error_msg.to_string()) }).await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), error_msg);
    }

    #[test]
    fn test_enter_agent_step_high_step_numbers() {
        let span = enter_agent_step("Testing", 999999);
        let _guard = span.enter();
        record_success();
    }

    #[test]
    fn test_enter_agent_step_zero_step() {
        let span = enter_agent_step("Start", 0);
        let _guard = span.enter();
        record_success();
    }

    #[test]
    fn test_record_state_transition_same_state() {
        record_state_transition("Running", "Running");
    }

    #[test]
    fn test_record_state_transition_empty_states() {
        record_state_transition("", "");
    }

    #[test]
    fn test_record_failure_unicode() {
        record_failure("错误: 连接失败 🔥");
        record_failure("Ошибка подключения");
        record_failure("エラー: 接続に失敗しました");
    }

    #[test]
    fn test_record_success_multiple_calls() {
        for _ in 0..10 {
            record_success();
        }
    }

    #[test]
    fn test_record_failure_multiple_calls() {
        for i in 0..10 {
            record_failure(&format!("Error {}", i));
        }
    }

    #[test]
    fn test_tool_span_various_names() {
        let tool_names = [
            "file_read",
            "shell_exec",
            "cargo_build",
            "git_commit",
            "http_request",
            "database_query",
            "cache_lookup",
            "",
            "tool-with-dashes",
            "tool.with.dots",
            "tool_with_unicode_名前",
        ];
        for name in tool_names {
            let span = tool_span!(name);
            let _guard = span.enter();
        }
    }

    #[test]
    fn test_enter_agent_step_long_state_name() {
        let long_state = "A".repeat(1000);
        let span = enter_agent_step(&long_state, 0);
        let _guard = span.enter();
    }

    #[test]
    fn test_record_failure_long_error() {
        let long_error = "Error: ".to_string() + &"x".repeat(10000);
        record_failure(&long_error);
    }

    #[tokio::test]
    async fn test_track_tool_execution_unit_result() {
        let result: Result<(), &str> = track_tool_execution("void_tool", || async { Ok(()) }).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_track_tool_execution_bool_result() {
        let result: Result<bool, &str> =
            track_tool_execution("bool_tool", || async { Ok(true) }).await;

        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_track_tool_execution_option_in_ok() {
        let result: Result<Option<i32>, &str> =
            track_tool_execution("option_tool", || async { Ok(Some(42)) }).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some(42));
    }

    #[tokio::test]
    async fn test_track_tool_execution_none_in_ok() {
        let result: Result<Option<i32>, &str> =
            track_tool_execution("none_tool", || async { Ok(None) }).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn test_span_hierarchy() {
        let span1 = enter_agent_step("Level1", 0);
        let _g1 = span1.enter();

        let span2 = enter_agent_step("Level2", 1);
        let _g2 = span2.enter();

        let span3 = enter_agent_step("Level3", 2);
        let _g3 = span3.enter();

        record_success();
    }

    #[tokio::test]
    async fn test_track_tool_execution_with_computation() {
        let result: Result<i32, &str> = track_tool_execution("compute_tool", || async {
            let mut sum = 0;
            for i in 0..100 {
                sum += i;
            }
            Ok(sum)
        })
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 4950);
    }

    #[test]
    fn test_record_state_transition_special_chars() {
        record_state_transition("State<A>", "State<B>");
        record_state_transition("State[1]", "State[2]");
        record_state_transition("State{x}", "State{y}");
    }

    #[tokio::test]
    async fn test_multiple_sequential_tool_executions() {
        for i in 0..5 {
            let result: Result<i32, &str> =
                track_tool_execution(&format!("sequential_tool_{}", i), || async move { Ok(i) })
                    .await;
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), i);
        }
    }

    #[tokio::test]
    async fn test_track_tool_execution_string_return() {
        let result: Result<String, &str> =
            track_tool_execution("string_tool", || async { Ok("Hello, World!".to_string()) }).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Hello, World!");
    }

    #[test]
    fn test_tool_span_record_fields() {
        let span = tool_span!("recordable_tool");
        span.record("success", true);
        span.record("duration_ms", 100u64);
        let _guard = span.enter();
    }

    #[test]
    fn test_enter_agent_step_returned_span() {
        let span = enter_agent_step("ValidSpan", 42);
        // Span should be created without panic and be usable
        let _guard = span.enter();
        // If we got here, the span is valid enough for use
    }

    #[test]
    fn test_concurrent_spans() {
        use std::thread;

        let handles: Vec<_> = (0..4)
            .map(|i| {
                thread::spawn(move || {
                    let span = enter_agent_step(&format!("Thread{}", i), i);
                    let _guard = span.enter();
                    record_success();
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_sanitize_for_log_basic() {
        assert_eq!(sanitize_for_log("hello world"), "hello world");
    }

    #[test]
    fn test_sanitize_for_log_newlines() {
        assert_eq!(
            sanitize_for_log("line1\nline2\r\nline3"),
            "line1\\nline2\\r\\nline3"
        );
    }

    #[test]
    fn test_sanitize_for_log_control_chars() {
        assert_eq!(sanitize_for_log("a\x00b\x1bc"), "a\\0b\\ec");
    }

    #[test]
    fn test_sanitize_for_log_preserves_unicode() {
        assert_eq!(sanitize_for_log("hello 世界"), "hello 世界");
    }

    #[test]
    fn test_redact_secrets_api_key() {
        let input = "Using api key sk-abc12345defghijk";
        let result = redact_secrets(input);
        assert!(!result.contains("sk-abc12345defghijk"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_bearer_token() {
        let input = "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.test";
        let result = redact_secrets(input);
        assert!(!result.contains("eyJhbGciOiJIUzI1NiJ9"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_password_in_connection() {
        let input = "postgres://user:password=mysecret@localhost/db";
        let result = redact_secrets(input);
        assert!(!result.contains("mysecret"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_preserves_normal_text() {
        let input = "This is a normal log message with no secrets";
        let result = redact_secrets(input);
        assert_eq!(result, input);
    }

    #[test]
    fn test_redact_secrets_token_prefix() {
        let input = "token-abcdefghijklmnop is being used";
        let result = redact_secrets(input);
        assert!(!result.contains("token-abcdefghijklmnop"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_set_and_get_sampling_rate() {
        let _guard = sampling_test_guard();
        // Save original and restore after test
        let original = sampling_rate();
        set_sampling_rate(0.5);
        let rate = sampling_rate();
        assert!((rate - 0.5).abs() < 0.01);

        set_sampling_rate(0.0);
        assert!((sampling_rate()).abs() < 0.01);

        set_sampling_rate(1.0);
        assert!((sampling_rate() - 1.0).abs() < 0.01);

        // Clamp out-of-range values
        set_sampling_rate(2.0);
        assert!((sampling_rate() - 1.0).abs() < 0.01);
        set_sampling_rate(-1.0);
        assert!((sampling_rate()).abs() < 0.01);

        // Restore
        set_sampling_rate(original);
    }

    #[test]
    fn test_should_sample_full_rate() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();
        set_sampling_rate(1.0);
        // At full rate, should always sample
        for _ in 0..100 {
            assert!(should_sample());
        }
        set_sampling_rate(original);
    }

    #[test]
    fn test_should_sample_zero_rate() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();
        set_sampling_rate(0.0);
        // At zero rate, should never sample
        for _ in 0..100 {
            assert!(!should_sample());
        }
        set_sampling_rate(original);
    }

    #[test]
    fn test_log_entry_count_and_increment() {
        let before = log_entry_count();
        let after = increment_log_count();
        assert_eq!(after, before + 1);
    }

    #[test]
    fn test_rotate_if_needed_below_limit() {
        let _guard = rotation_test_guard();
        // Save and reset to a known state below the limit
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        LOG_ENTRY_COUNT.store(0, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(!rotated);

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    #[test]
    fn test_max_log_entries_constant() {
        assert_eq!(MAX_LOG_ENTRIES, 100_000);
    }

    #[test]
    fn test_increment_functions_update_metrics() {
        let before_api = METRICS.api_requests.load(Ordering::Relaxed);
        increment_api_requests();
        assert_eq!(METRICS.api_requests.load(Ordering::Relaxed), before_api + 1);

        let before_errors = METRICS.api_errors.load(Ordering::Relaxed);
        increment_api_errors();
        assert_eq!(
            METRICS.api_errors.load(Ordering::Relaxed),
            before_errors + 1
        );

        let before_tool = METRICS.tool_executions.load(Ordering::Relaxed);
        increment_tool_executions();
        assert_eq!(
            METRICS.tool_executions.load(Ordering::Relaxed),
            before_tool + 1
        );

        let before_tool_err = METRICS.tool_errors.load(Ordering::Relaxed);
        increment_tool_errors();
        assert_eq!(
            METRICS.tool_errors.load(Ordering::Relaxed),
            before_tool_err + 1
        );

        let before_tokens = METRICS.tokens_processed.load(Ordering::Relaxed);
        add_tokens_processed(42);
        assert_eq!(
            METRICS.tokens_processed.load(Ordering::Relaxed),
            before_tokens + 42
        );
    }

    // -----------------------------------------------------------------------
    // Additional tests targeting uncovered lines
    // -----------------------------------------------------------------------

    // --- sanitize_for_log: tab, vertical tab, form feed, generic control ---

    #[test]
    fn test_sanitize_for_log_tab() {
        // Covers the '\t' => "\\t" branch (line 120)
        assert_eq!(sanitize_for_log("before\tafter"), "before\\tafter");
        assert_eq!(sanitize_for_log("\t"), "\\t");
        assert_eq!(sanitize_for_log("\t\t\t"), "\\t\\t\\t");
    }

    #[test]
    fn test_sanitize_for_log_vertical_tab() {
        // Covers the '\x0b' => "\\v" branch (line 121)
        assert_eq!(sanitize_for_log("a\x0bb"), "a\\vb");
        assert_eq!(sanitize_for_log("\x0b"), "\\v");
    }

    #[test]
    fn test_sanitize_for_log_form_feed() {
        // Covers the '\x0c' => "\\f" branch (line 122)
        assert_eq!(sanitize_for_log("a\x0cb"), "a\\fb");
        assert_eq!(sanitize_for_log("\x0c"), "\\f");
    }

    #[test]
    fn test_sanitize_for_log_escape_char() {
        // Covers the '\x1b' => "\\e" branch (line 123)
        assert_eq!(sanitize_for_log("a\x1bb"), "a\\eb");
        assert_eq!(sanitize_for_log("\x1b[31m"), "\\e[31m");
    }

    #[test]
    fn test_sanitize_for_log_null() {
        // Covers the '\x00' => "\\0" branch (line 124)
        assert_eq!(sanitize_for_log("a\x00b"), "a\\0b");
        assert_eq!(sanitize_for_log("\x00"), "\\0");
    }

    #[test]
    fn test_sanitize_for_log_generic_control_char() {
        // Covers the generic control char fallback: c if c.is_control() => \\u{XXXX} (line 125)
        // \x01 (SOH) is a control char not handled by explicit branches
        assert_eq!(sanitize_for_log("a\x01b"), "a\\u0001b");
        // \x02 (STX)
        assert_eq!(sanitize_for_log("x\x02y"), "x\\u0002y");
        // \x03 (ETX)
        assert_eq!(sanitize_for_log("\x03"), "\\u0003");
        // \x04 (EOT)
        assert_eq!(sanitize_for_log("\x04"), "\\u0004");
        // \x05 (ENQ)
        assert_eq!(sanitize_for_log("\x05"), "\\u0005");
        // \x06 (ACK)
        assert_eq!(sanitize_for_log("\x06"), "\\u0006");
        // \x07 (BEL)
        assert_eq!(sanitize_for_log("\x07"), "\\u0007");
        // \x0e (SO) - Shift Out
        assert_eq!(sanitize_for_log("\x0e"), "\\u000e");
        // \x7f (DEL) - also a control char
        assert_eq!(sanitize_for_log("\x7f"), "\\u007f");
    }

    #[test]
    fn test_sanitize_for_log_all_special_chars_combined() {
        // Exercises every branch in one call
        let input = "normal\n\r\t\x0b\x0c\x1b\x00\x01text";
        let expected = "normal\\n\\r\\t\\v\\f\\e\\0\\u0001text";
        assert_eq!(sanitize_for_log(input), expected);
    }

    #[test]
    fn test_sanitize_for_log_empty_string() {
        assert_eq!(sanitize_for_log(""), "");
    }

    #[test]
    fn test_sanitize_for_log_only_control_chars() {
        assert_eq!(
            sanitize_for_log("\x00\x01\x02\x03"),
            "\\0\\u0001\\u0002\\u0003"
        );
    }

    // --- redact_secrets: key- prefix, passwd=, pwd= variants, case insensitivity ---

    #[test]
    fn test_redact_secrets_key_prefix() {
        // Covers the key-... pattern (line 139)
        let input = "Using key-abcdefghijklmnop for auth";
        let result = redact_secrets(input);
        assert!(!result.contains("key-abcdefghijklmnop"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_passwd_variant() {
        // Covers the passwd= pattern (line 143)
        let input = "config passwd=secretvalue123 host=localhost";
        let result = redact_secrets(input);
        assert!(!result.contains("secretvalue123"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_pwd_variant() {
        // Covers the pwd= pattern (line 143)
        let input = "connection pwd=mypassword host=db.example.com";
        let result = redact_secrets(input);
        assert!(!result.contains("mypassword"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_case_insensitive_sk() {
        // Case insensitive match (?i)
        let input = "SK-ABCDEFGHIJKLMNOP";
        let result = redact_secrets(input);
        assert!(!result.contains("SK-ABCDEFGHIJKLMNOP"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_case_insensitive_bearer() {
        let input = "BEARER AbCdEfGhIjKlMnOp";
        let result = redact_secrets(input);
        assert!(!result.contains("AbCdEfGhIjKlMnOp"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_case_insensitive_password() {
        let input = "PASSWORD=SuperSecret123";
        let result = redact_secrets(input);
        assert!(!result.contains("SuperSecret123"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_multiple_secrets_in_one_string() {
        let input = "sk-key123456789 and token-abcdefghij and password=secret";
        let result = redact_secrets(input);
        assert!(!result.contains("sk-key123456789"));
        assert!(!result.contains("token-abcdefghij"));
        // Should have multiple [REDACTED]
        assert!(result.matches("[REDACTED]").count() >= 2);
    }

    #[test]
    fn test_redact_secrets_short_key_not_redacted() {
        // Keys shorter than 8 chars after the prefix should NOT be redacted
        let input = "sk-abc is too short";
        let result = redact_secrets(input);
        assert_eq!(result, input);
    }

    #[test]
    fn test_redact_secrets_password_with_spaces_around_equals() {
        let input = "password = mysecretpassword";
        let result = redact_secrets(input);
        assert!(!result.contains("mysecretpassword"));
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn test_redact_secrets_empty_string() {
        assert_eq!(redact_secrets(""), "");
    }

    #[test]
    fn test_redact_secrets_key_prefix_with_dashes_and_underscores() {
        let input = "key-abc_def-ghi_jkl";
        let result = redact_secrets(input);
        assert!(!result.contains("key-abc_def-ghi_jkl"));
        assert!(result.contains("[REDACTED]"));
    }

    // --- should_sample: partial rate counter-based path ---

    #[test]
    fn test_should_sample_partial_rate_exercises_counter_path() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        // Set rate to 0.5 (50%) to exercise the counter-based path
        // (lines 59-60): the code enters the branch where rate_micro is
        // between 0 and 1_000_000 and uses the counter modulo approach.
        set_sampling_rate(0.5);

        // Call should_sample many times to exercise the counter-based path.
        // We cannot predict exact results because the global counter is
        // shared across tests, but the function should not panic.
        let mut sampled = 0;
        let total = 2_000_000; // Enough to wrap around the modulo at least once
        for _ in 0..total {
            if should_sample() {
                sampled += 1;
            }
        }

        // At 50% rate over 2M calls, roughly 1M should be sampled
        assert!(
            sampled > 0,
            "At 50% rate over 2M calls, at least some events should be sampled"
        );
        assert!(
            sampled < total as i64 as usize,
            "At 50% rate over 2M calls, not all events should be sampled"
        );

        set_sampling_rate(original);
    }

    #[test]
    fn test_should_sample_low_rate_exercises_counter_path() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        // Set a very low rate to verify counter path returns false for most calls
        set_sampling_rate(0.001);

        // Exercise the path; we just verify it doesn't panic and
        // returns a mix of true/false over enough iterations
        for _ in 0..1000 {
            let _ = should_sample();
        }

        set_sampling_rate(original);
    }

    // --- rotate_if_needed: actual rotation path ---

    #[test]
    fn test_rotate_if_needed_triggers_rotation() {
        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);

        // Set count to just above MAX_LOG_ENTRIES
        LOG_ENTRY_COUNT.store(MAX_LOG_ENTRIES + 10, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(
            rotated,
            "Should trigger rotation when count >= MAX_LOG_ENTRIES"
        );

        // After rotation, count should be halved
        let after = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        assert_eq!(after, (MAX_LOG_ENTRIES + 10) / 2);

        // Restore
        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    #[test]
    fn test_rotate_if_needed_exactly_at_limit() {
        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);

        // Set count to exactly MAX_LOG_ENTRIES
        LOG_ENTRY_COUNT.store(MAX_LOG_ENTRIES, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(
            rotated,
            "Should trigger rotation when count == MAX_LOG_ENTRIES"
        );

        let after = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        assert_eq!(after, MAX_LOG_ENTRIES / 2);

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    #[test]
    fn test_rotate_if_needed_just_below_limit() {
        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);

        LOG_ENTRY_COUNT.store(MAX_LOG_ENTRIES - 1, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(!rotated, "Should not rotate when count < MAX_LOG_ENTRIES");

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    #[test]
    fn test_rotate_if_needed_at_zero() {
        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);

        LOG_ENTRY_COUNT.store(0, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(!rotated, "Should not rotate when count is 0");

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    #[test]
    fn test_rotate_if_needed_double_rotation() {
        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);

        // Set count well above limit
        LOG_ENTRY_COUNT.store(MAX_LOG_ENTRIES * 2, Ordering::Relaxed);

        let rotated = rotate_if_needed();
        assert!(rotated);
        let after_first = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        assert_eq!(after_first, MAX_LOG_ENTRIES); // 200_000 / 2 = 100_000

        // Still at MAX_LOG_ENTRIES, so rotating again should work
        let rotated2 = rotate_if_needed();
        assert!(rotated2);
        let after_second = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        assert_eq!(after_second, MAX_LOG_ENTRIES / 2); // 100_000 / 2 = 50_000

        // Now below limit, should not rotate
        let rotated3 = rotate_if_needed();
        assert!(!rotated3);

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    // --- get_metrics: returns reference to global METRICS ---

    #[test]
    fn test_get_metrics_returns_static_ref() {
        let m = get_metrics();
        // Should be the same static METRICS
        let before = m.api_requests.load(Ordering::Relaxed);
        increment_api_requests();
        let after = m.api_requests.load(Ordering::Relaxed);
        assert_eq!(after, before + 1);
    }

    #[test]
    fn test_get_metrics_all_fields_accessible() {
        let m = get_metrics();
        // All fields should be readable without panic
        let _ = m.api_requests.load(Ordering::Relaxed);
        let _ = m.api_errors.load(Ordering::Relaxed);
        let _ = m.tool_executions.load(Ordering::Relaxed);
        let _ = m.tool_errors.load(Ordering::Relaxed);
        let _ = m.tokens_processed.load(Ordering::Relaxed);
    }

    // --- add_tokens_processed edge cases ---

    #[test]
    fn test_add_tokens_processed_zero() {
        let before = METRICS.tokens_processed.load(Ordering::Relaxed);
        add_tokens_processed(0);
        let after = METRICS.tokens_processed.load(Ordering::Relaxed);
        // Adding 0 should not decrease the count; other tests may concurrently
        // increment, so we only assert it's >= before.
        assert!(after >= before);
    }

    #[test]
    fn test_add_tokens_processed_large_value() {
        let before = METRICS.tokens_processed.load(Ordering::Relaxed);
        add_tokens_processed(1_000_000);
        let after = METRICS.tokens_processed.load(Ordering::Relaxed);
        // Other parallel tests may also add tokens, so just verify our
        // contribution was applied (after should be at least before + 1M).
        assert!(after >= before + 1_000_000);
    }

    #[test]
    fn test_add_tokens_processed_multiple_adds() {
        let before = METRICS.tokens_processed.load(Ordering::Relaxed);
        add_tokens_processed(10);
        add_tokens_processed(20);
        add_tokens_processed(30);
        let after = METRICS.tokens_processed.load(Ordering::Relaxed);
        // At minimum our 60 tokens should be reflected; other tests may add more.
        assert!(after >= before + 60);
    }

    // --- increment_log_count: verify atomicity ---

    #[test]
    fn test_increment_log_count_sequential() {
        let before = log_entry_count();
        let r1 = increment_log_count();
        let r2 = increment_log_count();
        let r3 = increment_log_count();
        // Each call returns the new count after incrementing
        assert_eq!(r1, before + 1);
        assert_eq!(r2, before + 2);
        assert_eq!(r3, before + 3);
    }

    #[test]
    fn test_log_entry_count_matches_after_increments() {
        let before = log_entry_count();
        for _ in 0..5 {
            increment_log_count();
        }
        let after = log_entry_count();
        assert_eq!(after, before + 5);
    }

    // --- shutdown_tracing: safe to call even when not initialized ---

    #[test]
    fn test_shutdown_tracing_no_panic_when_not_initialized() {
        // TRACING_GUARD may or may not be initialized; shutdown should be safe either way
        shutdown_tracing();
    }

    #[test]
    fn test_shutdown_tracing_idempotent() {
        // Calling shutdown multiple times should be safe
        shutdown_tracing();
        shutdown_tracing();
        shutdown_tracing();
    }

    // --- init_tracing: when RUST_LOG is not set ---

    #[test]
    fn test_init_tracing_no_rust_log() {
        // When RUST_LOG is not set, init_tracing should be a no-op without panic.
        // We just verify it does not panic.
        init_tracing();
    }

    // --- record_failure with secrets in error message ---

    #[test]
    fn test_record_failure_redacts_secrets() {
        // Exercise the redact_secrets + sanitize_for_log pipeline inside record_failure
        record_failure("Connection failed with sk-supersecretkey123456");
        record_failure("Auth error: Bearer eyJhbGciOiJIUzI1NiJ9.payload");
        record_failure("DB error: password=mysecretpass");
    }

    // --- record_state_transition with control characters ---

    #[test]
    fn test_record_state_transition_with_control_chars() {
        // Exercise sanitize_for_log inside record_state_transition
        record_state_transition("State\nA", "State\tB");
        record_state_transition("From\x00", "To\x1b");
        record_state_transition("From\x0b", "To\x0c");
    }

    // --- enter_agent_step with special characters ---

    #[test]
    fn test_enter_agent_step_with_control_chars() {
        // Exercise sanitize_for_log inside enter_agent_step
        let span = enter_agent_step("State\n\r\t\x00\x1b", 0);
        let _guard = span.enter();
    }

    // --- track_tool_execution with secrets in tool name ---

    #[tokio::test]
    async fn test_track_tool_execution_redacts_tool_name() {
        // Tool name containing a secret should be redacted
        let result: Result<i32, &str> =
            track_tool_execution("tool_with_sk-secretkeyvalue123", || async { Ok(1) }).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_track_tool_execution_sanitizes_tool_name() {
        // Tool name with control characters should be sanitized
        let result: Result<i32, &str> =
            track_tool_execution("tool\nwith\nnewlines", || async { Ok(1) }).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_track_tool_execution_error_with_secrets() {
        // Error message containing secrets should be redacted in spans
        let result: Result<i32, String> = track_tool_execution("secure_tool", || async {
            Err("Failed with password=secret123".to_string())
        })
        .await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Failed with password=secret123");
    }

    // --- secret_patterns: ensure lazy init works ---

    #[test]
    fn test_secret_patterns_initialized() {
        // Calling redact_secrets forces secret_patterns() init
        let _ = redact_secrets("test");
        // Calling again uses the cached patterns
        let _ = redact_secrets("another test");
    }

    // --- sampling_rate: precision and edge cases ---

    #[test]
    fn test_sampling_rate_precision() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        set_sampling_rate(0.123456);
        let rate = sampling_rate();
        // Should be close to 0.123456 within fixed-point precision
        assert!((rate - 0.123456).abs() < 0.000002);

        set_sampling_rate(0.999999);
        let rate = sampling_rate();
        assert!((rate - 0.999999).abs() < 0.000002);

        set_sampling_rate(0.000001);
        let rate = sampling_rate();
        assert!((rate - 0.000001).abs() < 0.000002);

        set_sampling_rate(original);
    }

    // --- Metrics concurrent access ---

    #[test]
    fn test_metrics_concurrent_increments() {
        use std::thread;

        let before_api = METRICS.api_requests.load(Ordering::Relaxed);
        let before_tool = METRICS.tool_executions.load(Ordering::Relaxed);

        let handles: Vec<_> = (0..10)
            .map(|i| {
                thread::spawn(move || {
                    for _ in 0..100 {
                        if i % 2 == 0 {
                            increment_api_requests();
                        } else {
                            increment_tool_executions();
                        }
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        let after_api = METRICS.api_requests.load(Ordering::Relaxed);
        let after_tool = METRICS.tool_executions.load(Ordering::Relaxed);

        // 5 threads doing api_requests * 100 each = 500
        assert_eq!(after_api - before_api, 500);
        // 5 threads doing tool_executions * 100 each = 500
        assert_eq!(after_tool - before_tool, 500);
    }

    // --- sanitize_for_log: injection prevention ---

    #[test]
    fn test_sanitize_for_log_injection_attempt() {
        // Simulates a log injection attack: attacker inserts newline + fake log entry
        let malicious = "normal input\n[ERROR] Fake admin alert: system compromised";
        let sanitized = sanitize_for_log(malicious);
        // Newline should be escaped, preventing the fake log entry from appearing on its own line
        assert!(!sanitized.contains('\n'));
        assert!(sanitized.contains("\\n"));
        assert!(sanitized.contains("[ERROR] Fake admin alert: system compromised"));
    }

    #[test]
    fn test_sanitize_for_log_carriage_return_injection() {
        let malicious = "first line\r[INFO] spoofed log entry";
        let sanitized = sanitize_for_log(malicious);
        assert!(!sanitized.contains('\r'));
        assert!(sanitized.contains("\\r"));
    }

    // --- redact_secrets: bearer with dots (JWT-style) ---

    #[test]
    fn test_redact_secrets_bearer_jwt_style() {
        let input = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0";
        let result = redact_secrets(input);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"));
    }

    #[test]
    fn test_redact_secrets_token_with_underscores() {
        let input = "token-abc_def_ghi_jkl_mno";
        let result = redact_secrets(input);
        assert!(!result.contains("token-abc_def_ghi_jkl_mno"));
        assert!(result.contains("[REDACTED]"));
    }

    // --- Combined sanitize + redact (as used in record_failure / track_tool_execution) ---

    #[test]
    fn test_sanitize_then_redact_pipeline() {
        // This is the exact pipeline used in record_failure and track_tool_execution
        let input = "Error: sk-secretkey12345678\nNew line injection";
        let sanitized = sanitize_for_log(input);
        let redacted = redact_secrets(&sanitized);

        // No raw newlines
        assert!(!redacted.contains('\n'));
        // Secret redacted
        assert!(!redacted.contains("sk-secretkey12345678"));
        assert!(redacted.contains("[REDACTED]"));
        assert!(redacted.contains("\\n"));
    }

    #[test]
    fn test_redact_then_sanitize_order_independence() {
        let input = "password=secret123\ttab_separated";
        let s_then_r = redact_secrets(&sanitize_for_log(input));
        // Both sanitization and redaction should have occurred
        assert!(!s_then_r.contains('\t'));
    }

    // --- Metrics: verify get_metrics returns same instance ---

    #[test]
    fn test_get_metrics_is_same_as_static() {
        let m = get_metrics();
        // Increment via the function
        let before = m.tool_errors.load(Ordering::Relaxed);
        increment_tool_errors();
        // Should reflect on the same reference
        assert_eq!(m.tool_errors.load(Ordering::Relaxed), before + 1);
    }

    // --- increment functions: verify both atomic and metrics crate counters ---

    #[test]
    fn test_increment_api_requests_multiple() {
        let before = METRICS.api_requests.load(Ordering::Relaxed);
        for _ in 0..5 {
            increment_api_requests();
        }
        assert_eq!(METRICS.api_requests.load(Ordering::Relaxed), before + 5);
    }

    #[test]
    fn test_increment_api_errors_multiple() {
        let before = METRICS.api_errors.load(Ordering::Relaxed);
        for _ in 0..3 {
            increment_api_errors();
        }
        assert_eq!(METRICS.api_errors.load(Ordering::Relaxed), before + 3);
    }

    #[test]
    fn test_increment_tool_executions_multiple() {
        let before = METRICS.tool_executions.load(Ordering::Relaxed);
        for _ in 0..7 {
            increment_tool_executions();
        }
        assert_eq!(METRICS.tool_executions.load(Ordering::Relaxed), before + 7);
    }

    #[test]
    fn test_increment_tool_errors_multiple() {
        let before = METRICS.tool_errors.load(Ordering::Relaxed);
        for _ in 0..4 {
            increment_tool_errors();
        }
        assert_eq!(METRICS.tool_errors.load(Ordering::Relaxed), before + 4);
    }

    // --- Concurrent log rotation ---

    #[test]
    fn test_rotate_if_needed_concurrent() {
        use std::thread;

        let _guard = rotation_test_guard();
        let saved = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        LOG_ENTRY_COUNT.store(MAX_LOG_ENTRIES + 100, Ordering::Relaxed);

        let handles: Vec<_> = (0..4).map(|_| thread::spawn(rotate_if_needed)).collect();

        let mut any_rotated = false;
        for h in handles {
            if h.join().unwrap() {
                any_rotated = true;
            }
        }

        assert!(
            any_rotated,
            "At least one thread should have triggered rotation"
        );

        // After concurrent rotation, count should be less than the original
        let final_count = LOG_ENTRY_COUNT.load(Ordering::Relaxed);
        assert!(
            final_count < MAX_LOG_ENTRIES + 100,
            "Count should have been reduced from the original"
        );

        LOG_ENTRY_COUNT.store(saved, Ordering::Relaxed);
    }

    // --- init_tracing_verbose: safe to call ---

    #[test]
    fn test_init_tracing_verbose_no_panic() {
        // init_tracing_verbose delegates to init_tracing_with_filter("info")
        // which uses a Once guard, so safe to call even if already initialized
        init_tracing_verbose();
    }

    // --- init_tracing_with_filter: invalid filter string ---

    #[test]
    fn test_init_tracing_with_filter_invalid_fallback() {
        // An invalid filter string should fall back to "warn" without panicking
        // The Once guard will skip if already initialized
        init_tracing_with_filter("this is not a valid filter!!!@@@");
    }

    // --- sampling rate: boundary values ---

    #[test]
    fn test_sampling_rate_boundary_zero() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        set_sampling_rate(0.0);
        assert_eq!(sampling_rate(), 0.0);

        set_sampling_rate(original);
    }

    #[test]
    fn test_sampling_rate_boundary_one() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        set_sampling_rate(1.0);
        assert_eq!(sampling_rate(), 1.0);

        set_sampling_rate(original);
    }

    #[test]
    fn test_sampling_rate_clamp_negative() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        set_sampling_rate(-100.0);
        assert_eq!(sampling_rate(), 0.0);

        set_sampling_rate(original);
    }

    #[test]
    fn test_sampling_rate_clamp_large_positive() {
        let _guard = sampling_test_guard();
        let original = sampling_rate();

        set_sampling_rate(999.0);
        assert_eq!(sampling_rate(), 1.0);

        set_sampling_rate(original);
    }
}