asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Task inspection and debugging for runtime diagnostics.
//!
//! This module provides task-state inspection for runtime diagnostics,
//! including checkpoint-based idle-time heuristics, wake-pending state,
//! obligation ownership, and deterministic wire snapshots.
//!
//! # Example
//!
//! ```ignore
//! use asupersync::observability::{TaskInspector, TaskInspectorConfig};
//! use std::time::Duration;
//!
//! let inspector = TaskInspector::new(state.clone(), console);
//! let summary = inspector.summary();
//! println!("Total tasks: {}, Running: {}", summary.total_tasks, summary.running);
//!
//! // Find stuck tasks (not polled recently)
//! let stuck = inspector.find_stuck_tasks(Duration::from_secs(30));
//! for task in &stuck {
//!     println!("Stuck: {:?}", task.id);
//! }
//! ```

use crate::console::Console;
use crate::cx::Cx;
use crate::record::task::{TaskPhase, TaskRecord, TaskState};
use crate::runtime::state::RuntimeState;
use crate::time::TimerDriverHandle;
use crate::tracing_compat::{debug, info, trace, warn};
use crate::types::{ObligationId, Outcome, RegionId, TaskId, Time};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::time::Duration;

/// Configuration for the task inspector.
#[derive(Debug, Clone)]
pub struct TaskInspectorConfig {
    /// Age threshold for stuck task warnings (default: 30s).
    pub stuck_task_threshold: Duration,
    /// Whether to include obligations in task details.
    pub show_obligations: bool,
    /// Whether to highlight stuck tasks in output.
    pub highlight_stuck_tasks: bool,
}

impl Default for TaskInspectorConfig {
    fn default() -> Self {
        Self {
            stuck_task_threshold: Duration::from_secs(30),
            show_obligations: true,
            highlight_stuck_tasks: true,
        }
    }
}

impl TaskInspectorConfig {
    /// Create a new configuration with the specified stuck threshold.
    #[must_use]
    pub fn with_stuck_threshold(mut self, threshold: Duration) -> Self {
        self.stuck_task_threshold = threshold;
        self
    }

    /// Enable or disable obligation display.
    #[must_use]
    pub fn with_show_obligations(mut self, show: bool) -> Self {
        self.show_obligations = show;
        self
    }

    /// Enable or disable stuck task highlighting.
    #[must_use]
    pub fn with_highlight_stuck_tasks(mut self, highlight: bool) -> Self {
        self.highlight_stuck_tasks = highlight;
        self
    }
}

/// Detailed information about a task's current state.
#[derive(Debug, Clone)]
pub struct TaskDetails {
    /// Task identifier.
    pub id: TaskId,
    /// Owning region.
    pub region_id: RegionId,
    /// Current lifecycle state.
    pub state: TaskStateInfo,
    /// Atomic phase (cross-thread safe snapshot).
    pub phase: TaskPhase,
    /// Total number of polls executed.
    pub poll_count: u64,
    /// Polls remaining in budget.
    pub polls_remaining: u32,
    /// Logical time when created.
    pub created_at: Time,
    /// Time since creation.
    pub age: Duration,
    /// Time since the last explicit progress checkpoint / idle-time sample.
    pub time_since_last_poll: Option<Duration>,
    /// Whether a wake is pending.
    pub wake_pending: bool,
    /// Pending obligations still held by this task.
    pub obligations: Vec<ObligationId>,
    /// Tasks waiting for this one to complete.
    pub waiters: Vec<TaskId>,
}

impl TaskDetails {
    /// Returns true if the task is in a terminal state.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        matches!(self.state, TaskStateInfo::Completed { .. })
    }

    /// Returns true if the task is currently running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        matches!(self.state, TaskStateInfo::Running)
    }

    /// Returns true if the task is being cancelled.
    #[must_use]
    pub fn is_cancelling(&self) -> bool {
        matches!(
            self.state,
            TaskStateInfo::CancelRequested { .. }
                | TaskStateInfo::Cancelling { .. }
                | TaskStateInfo::Finalizing { .. }
        )
    }

    /// Returns true if the task matches the inspector's stuck-task heuristic.
    ///
    /// Prefer explicit idle-time metadata when it is available. Today the
    /// inspector derives this from task progress checkpoints. When no explicit
    /// idle-time sample exists yet, only classify old tasks that have never
    /// been polled as potentially stuck so long-lived waiting tasks are not
    /// misreported just because they are old.
    #[must_use]
    pub fn is_potentially_stuck(&self, age_threshold: Duration) -> bool {
        if self.is_terminal() || self.wake_pending {
            return false;
        }

        self.time_since_last_poll.map_or_else(
            || self.age > age_threshold && self.poll_count == 0,
            |idle_for| idle_for > age_threshold,
        )
    }
}

/// Simplified task state for inspection (matches TaskState but serializable).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskStateInfo {
    /// Initial state after spawn.
    Created,
    /// Actively being polled.
    Running,
    /// Cancel requested but not acknowledged.
    CancelRequested {
        /// Reason for cancellation.
        reason: String,
    },
    /// Task running cleanup code.
    Cancelling {
        /// Reason for cancellation.
        reason: String,
    },
    /// Task running finalizers.
    Finalizing {
        /// Reason for cancellation.
        reason: String,
    },
    /// Terminal state.
    Completed {
        /// Outcome kind.
        outcome: String,
    },
}

/// Stable schema identifier for task-inspector wire snapshots.
pub const TASK_CONSOLE_WIRE_SCHEMA_V1: &str = "asupersync.task_console_wire.v1";

/// Deterministic wire payload for task-inspector snapshots.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskConsoleWireSnapshot {
    /// Schema version identifier.
    pub schema_version: String,
    /// Logical timestamp of snapshot capture.
    pub generated_at: Time,
    /// Aggregate task-state counters.
    pub summary: TaskSummaryWire,
    /// Task-level records sorted by `TaskId`.
    pub tasks: Vec<TaskDetailsWire>,
}

impl TaskConsoleWireSnapshot {
    /// Build a wire snapshot with deterministic task ordering.
    #[must_use]
    pub fn new(
        generated_at: Time,
        summary: TaskSummaryWire,
        mut tasks: Vec<TaskDetailsWire>,
    ) -> Self {
        tasks.sort_unstable_by_key(|record| record.id);
        Self {
            schema_version: TASK_CONSOLE_WIRE_SCHEMA_V1.to_string(),
            generated_at,
            summary,
            tasks,
        }
    }

    /// Returns true when the payload schema matches the expected version.
    #[must_use]
    pub fn has_expected_schema(&self) -> bool {
        self.schema_version == TASK_CONSOLE_WIRE_SCHEMA_V1
    }

    /// Encode snapshot as compact JSON.
    ///
    /// # Errors
    ///
    /// Returns `serde_json::Error` when serialization fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Encode snapshot as pretty JSON.
    ///
    /// # Errors
    ///
    /// Returns `serde_json::Error` when serialization fails.
    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Decode snapshot from JSON.
    ///
    /// # Errors
    ///
    /// Returns `serde_json::Error` when parsing fails.
    pub fn from_json(payload: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(payload)
    }
}

/// Region-level task count in wire payloads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskRegionCountWire {
    /// Region identifier.
    pub region_id: RegionId,
    /// Number of tasks currently owned by this region.
    pub task_count: usize,
}

/// Summary section for task-inspector wire snapshots.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskSummaryWire {
    /// Total number of tasks.
    pub total_tasks: usize,
    /// Tasks in `Created`.
    pub created: usize,
    /// Tasks in `Running`.
    pub running: usize,
    /// Tasks in any cancellation phase.
    pub cancelling: usize,
    /// Completed tasks.
    pub completed: usize,
    /// Number of tasks classified as potentially stuck.
    pub stuck_count: usize,
    /// Region distribution, sorted by `RegionId`.
    pub by_region: Vec<TaskRegionCountWire>,
}

impl From<TaskSummary> for TaskSummaryWire {
    fn from(summary: TaskSummary) -> Self {
        let by_region = summary
            .by_region
            .into_iter()
            .map(|(region_id, task_count)| TaskRegionCountWire {
                region_id,
                task_count,
            })
            .collect();
        Self {
            total_tasks: summary.total_tasks,
            created: summary.created,
            running: summary.running,
            cancelling: summary.cancelling,
            completed: summary.completed,
            stuck_count: summary.stuck_count,
            by_region,
        }
    }
}

/// Task-level section for task-inspector wire snapshots.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskDetailsWire {
    /// Task identifier.
    pub id: TaskId,
    /// Owning region.
    pub region_id: RegionId,
    /// High-level task state.
    pub state: TaskStateInfo,
    /// Coarse-grained atomic phase.
    pub phase: String,
    /// Poll count since task creation.
    pub poll_count: u64,
    /// Remaining poll budget.
    pub polls_remaining: u32,
    /// Task creation logical timestamp.
    pub created_at: Time,
    /// Task age in nanoseconds.
    pub age_nanos: u64,
    /// Time since last poll in nanoseconds when available.
    pub time_since_last_poll_nanos: Option<u64>,
    /// Whether a wake is pending.
    pub wake_pending: bool,
    /// Held obligations sorted by `ObligationId`.
    pub obligations: Vec<ObligationId>,
    /// Waiting tasks sorted by `TaskId`.
    pub waiters: Vec<TaskId>,
}

impl From<TaskDetails> for TaskDetailsWire {
    fn from(task: TaskDetails) -> Self {
        let mut obligations = task.obligations;
        obligations.sort_unstable();
        let mut waiters = task.waiters;
        waiters.sort_unstable();
        Self {
            id: task.id,
            region_id: task.region_id,
            state: task.state,
            phase: phase_name(task.phase).to_string(),
            poll_count: task.poll_count,
            polls_remaining: task.polls_remaining,
            created_at: task.created_at,
            age_nanos: duration_to_nanos(task.age),
            time_since_last_poll_nanos: task.time_since_last_poll.map(duration_to_nanos),
            wake_pending: task.wake_pending,
            obligations,
            waiters,
        }
    }
}

fn duration_to_nanos(duration: Duration) -> u64 {
    duration.as_nanos().min(u128::from(u64::MAX)) as u64
}

fn phase_name(phase: TaskPhase) -> &'static str {
    match phase {
        TaskPhase::Created => "Created",
        TaskPhase::Running => "Running",
        TaskPhase::CancelRequested => "CancelRequested",
        TaskPhase::Cancelling => "Cancelling",
        TaskPhase::Finalizing => "Finalizing",
        TaskPhase::Completed => "Completed",
    }
}

impl TaskStateInfo {
    /// Returns a short name for the state.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Created => "Created",
            Self::Running => "Running",
            Self::CancelRequested { .. } => "CancelRequested",
            Self::Cancelling { .. } => "Cancelling",
            Self::Finalizing { .. } => "Finalizing",
            Self::Completed { .. } => "Completed",
        }
    }
}

impl From<&TaskState> for TaskStateInfo {
    fn from(state: &TaskState) -> Self {
        match state {
            TaskState::Created => Self::Created,
            TaskState::Running => Self::Running,
            TaskState::CancelRequested { reason, .. } => Self::CancelRequested {
                reason: format!("{:?}", reason.kind),
            },
            TaskState::Cancelling { reason, .. } => Self::Cancelling {
                reason: format!("{:?}", reason.kind),
            },
            TaskState::Finalizing { reason, .. } => Self::Finalizing {
                reason: format!("{:?}", reason.kind),
            },
            TaskState::Completed(outcome) => Self::Completed {
                outcome: match outcome {
                    Outcome::Ok(()) => "Ok".to_string(),
                    Outcome::Err(e) => format!("Err({:?})", e.kind()),
                    Outcome::Cancelled(r) => format!("Cancelled({:?})", r.kind),
                    Outcome::Panicked(_) => "Panicked".to_string(),
                },
            },
        }
    }
}

/// Summary of all tasks in the runtime.
#[derive(Debug, Clone, Default)]
pub struct TaskSummary {
    /// Total number of tasks.
    pub total_tasks: usize,
    /// Tasks in Created state.
    pub created: usize,
    /// Tasks in Running state.
    pub running: usize,
    /// Tasks being cancelled (any cancellation state).
    pub cancelling: usize,
    /// Completed tasks.
    pub completed: usize,
    /// Tasks grouped by region.
    pub by_region: BTreeMap<RegionId, usize>,
    /// Number of potentially stuck tasks.
    pub stuck_count: usize,
}

/// Real-time task inspector for runtime diagnostics.
#[derive(Debug)]
pub struct TaskInspector {
    state: Arc<RuntimeState>,
    config: TaskInspectorConfig,
    console: Option<Console>,
}

impl TaskInspector {
    /// Create a new task inspector.
    #[must_use]
    pub fn new(state: Arc<RuntimeState>, console: Option<Console>) -> Self {
        Self::with_config(state, console, TaskInspectorConfig::default())
    }

    /// Create a new task inspector with custom configuration.
    #[must_use]
    pub fn with_config(
        state: Arc<RuntimeState>,
        console: Option<Console>,
        config: TaskInspectorConfig,
    ) -> Self {
        debug!(
            stuck_threshold_secs = config.stuck_task_threshold.as_secs(),
            show_obligations = config.show_obligations,
            "task inspector created"
        );
        Self {
            state,
            config,
            console,
        }
    }

    /// Get the current runtime time for observability.
    ///
    /// Live runtimes advance time through the timer driver, while timerless
    /// runtimes and many direct tests only move `RuntimeState::now`.
    /// Prefer the timer driver when present and fall back to the logical state
    /// clock otherwise so task ages remain meaningful in both modes.
    fn current_time(&self) -> Time {
        self.state
            .timer_driver()
            .map_or(self.state.now, TimerDriverHandle::now)
    }

    /// Get the current checkpoint time when it shares the task's checkpoint clock.
    ///
    /// `Cx::checkpoint()` records time using the task-local timer driver handle
    /// captured in the `Cx`. If a task was created before the runtime attached a
    /// timer driver, later switching `RuntimeState` to timer-driver time does
    /// not retroactively update that `Cx`; the task will keep recording wall
    /// clock checkpoints. The inspector therefore has to consult the task's own
    /// `Cx` handle instead of the runtime-global timer driver to avoid mixing
    /// clock domains after late driver attachment.
    fn current_checkpoint_time_for_task(task: &TaskRecord) -> Option<Time> {
        task.cx
            .as_ref()
            .and_then(Cx::timer_driver)
            .map(|driver| driver.now())
    }

    /// Get detailed information about a specific task.
    #[must_use]
    pub fn inspect_task(&self, task_id: TaskId) -> Option<TaskDetails> {
        trace!(task_id = ?task_id, "inspecting task");

        let task = self.state.task(task_id)?;
        let current_time = self.current_time();
        let age_nanos = current_time.duration_since(task.created_at);
        let age = Duration::from_nanos(age_nanos);

        // Collect obligations held by this task
        let obligations: Vec<ObligationId> = if self.config.show_obligations {
            self.state
                .obligations
                .sorted_pending_ids_for_holder(task_id)
                .into_iter()
                .collect()
        } else {
            Vec::new()
        };

        let time_since_last_poll = Self::current_checkpoint_time_for_task(task).and_then(|now| {
            task.cx_inner.as_ref().and_then(|inner| {
                inner
                    .read()
                    .checkpoint_state
                    .last_checkpoint
                    .map(|last_checkpoint| {
                        Duration::from_nanos(now.duration_since(last_checkpoint))
                    })
            })
        });

        Some(TaskDetails {
            id: task.id,
            region_id: task.owner,
            state: TaskStateInfo::from(&task.state),
            phase: task.phase(),
            poll_count: task.total_polls,
            polls_remaining: task.polls_remaining,
            created_at: task.created_at,
            age,
            time_since_last_poll,
            wake_pending: task.wake_state.is_notified(),
            obligations,
            waiters: task.waiters.to_vec(),
        })
    }

    /// List all tasks with their details.
    #[must_use]
    pub fn list_tasks(&self) -> Vec<TaskDetails> {
        trace!("listing all tasks");
        self.state
            .tasks_iter()
            .filter_map(|(_, task)| self.inspect_task(task.id))
            .collect()
    }

    /// List non-terminal tasks only.
    #[must_use]
    pub fn list_active_tasks(&self) -> Vec<TaskDetails> {
        self.list_tasks()
            .into_iter()
            .filter(|t| !t.is_terminal())
            .collect()
    }

    /// Get tasks in a specific region.
    #[must_use]
    pub fn by_region(&self, region_id: RegionId) -> Vec<TaskDetails> {
        trace!(region_id = ?region_id, "filtering tasks by region");
        self.list_tasks()
            .into_iter()
            .filter(|t| t.region_id == region_id)
            .collect()
    }

    /// Get tasks in a specific state.
    #[must_use]
    pub fn by_state(&self, state_name: &str) -> Vec<TaskDetails> {
        trace!(state_name = %state_name, "filtering tasks by state");
        self.list_tasks()
            .into_iter()
            .filter(|t| t.state.name() == state_name)
            .collect()
    }

    /// Find tasks that haven't reported progress recently (potentially stuck).
    ///
    /// Note: This is heuristic-based because explicit idle-time metadata is not
    /// always available. When no checkpoint-derived idle time exists yet, the
    /// inspector only flags aged tasks that have never been polled, avoiding
    /// false positives for long-lived waiting tasks.
    #[must_use]
    pub fn find_stuck_tasks(&self, age_threshold: Duration) -> Vec<TaskDetails> {
        debug!(
            threshold_secs = age_threshold.as_secs(),
            "checking for stuck tasks"
        );

        let stuck: Vec<_> = self
            .list_active_tasks()
            .into_iter()
            .filter(|task| task.is_potentially_stuck(age_threshold))
            .collect();

        if !stuck.is_empty() {
            warn!(
                count = stuck.len(),
                threshold_secs = age_threshold.as_secs(),
                "potential stuck tasks detected"
            );
            for task in &stuck {
                // When tracing is compiled out, ensure `task` is still considered "used".
                let _ = task;
                info!(
                    task_id = ?task.id,
                    region_id = ?task.region_id,
                    age_secs = task.age.as_secs(),
                    poll_count = task.poll_count,
                    state = task.state.name(),
                    "potential stuck task"
                );
            }
        }

        stuck
    }

    /// Find stuck tasks using the configured threshold.
    #[must_use]
    pub fn find_stuck_tasks_default(&self) -> Vec<TaskDetails> {
        self.find_stuck_tasks(self.config.stuck_task_threshold)
    }

    fn summarize_tasks(tasks: &[TaskDetails], stuck_threshold: Duration) -> TaskSummary {
        let mut by_region: BTreeMap<RegionId, usize> = BTreeMap::new();
        let mut created = 0;
        let mut running = 0;
        let mut cancelling = 0;
        let mut completed = 0;
        let mut stuck_count = 0;

        for task in tasks {
            *by_region.entry(task.region_id).or_insert(0) += 1;

            match &task.state {
                TaskStateInfo::Created => created += 1,
                TaskStateInfo::Running => running += 1,
                TaskStateInfo::CancelRequested { .. }
                | TaskStateInfo::Cancelling { .. }
                | TaskStateInfo::Finalizing { .. } => cancelling += 1,
                TaskStateInfo::Completed { .. } => completed += 1,
            }

            if task.is_potentially_stuck(stuck_threshold) {
                stuck_count += 1;
            }
        }

        TaskSummary {
            total_tasks: tasks.len(),
            created,
            running,
            cancelling,
            completed,
            by_region,
            stuck_count,
        }
    }

    /// Get a summary of all tasks.
    #[must_use]
    pub fn summary(&self) -> TaskSummary {
        let tasks = self.list_tasks();
        let summary = Self::summarize_tasks(&tasks, self.config.stuck_task_threshold);

        debug!(
            total = summary.total_tasks,
            created = summary.created,
            running = summary.running,
            cancelling = summary.cancelling,
            completed = summary.completed,
            stuck = summary.stuck_count,
            "task summary computed"
        );

        summary
    }

    /// Build a deterministic wire snapshot suitable for console or dashboard consumers.
    #[must_use]
    pub fn wire_snapshot(&self) -> TaskConsoleWireSnapshot {
        let tasks = self.list_tasks();
        let summary = Self::summarize_tasks(&tasks, self.config.stuck_task_threshold);
        let wire_tasks = tasks.into_iter().map(TaskDetailsWire::from).collect();
        TaskConsoleWireSnapshot::new(
            self.current_time(),
            TaskSummaryWire::from(summary),
            wire_tasks,
        )
    }

    /// Serialize a wire snapshot as compact JSON.
    ///
    /// # Errors
    ///
    /// Returns `serde_json::Error` when serialization fails.
    pub fn wire_snapshot_json(&self) -> Result<String, serde_json::Error> {
        self.wire_snapshot().to_json()
    }

    /// Serialize a wire snapshot as pretty JSON.
    ///
    /// # Errors
    ///
    /// Returns `serde_json::Error` when serialization fails.
    pub fn wire_snapshot_pretty_json(&self) -> Result<String, serde_json::Error> {
        self.wire_snapshot().to_pretty_json()
    }

    fn format_summary_output(
        summary: &TaskSummary,
        stuck: &[TaskDetails],
        highlight_stuck_tasks: bool,
    ) -> String {
        let mut output = String::new();
        writeln!(&mut output, "Task Inspector").expect("expected");
        writeln!(
            &mut output,
            "Total: {}  |  Running: {}  |  Cancelling: {}  |  Completed: {}  |  Stuck: {}",
            summary.total_tasks,
            summary.running,
            summary.cancelling,
            summary.completed,
            summary.stuck_count
        )
        .expect("expected");
        output.push_str(&"-".repeat(70));
        output.push('\n');

        output.push_str("By Region:\n");
        for (region_id, count) in &summary.by_region {
            writeln!(&mut output, "  {region_id:?}: {count} tasks").expect("expected");
        }

        if highlight_stuck_tasks && !stuck.is_empty() {
            output.push_str(&"-".repeat(70));
            output.push('\n');
            output.push_str("POTENTIAL STUCK TASKS:\n");
            for stuck_task in stuck {
                let id = stuck_task.id;
                let region_id = stuck_task.region_id;
                let state = stuck_task.state.name();
                let age_secs = stuck_task.age.as_secs_f64();
                let poll_count = stuck_task.poll_count;
                writeln!(
                    &mut output,
                    "  {id:?} in {region_id:?} - {state} for {age_secs:.1}s, {poll_count} polls"
                )
                .expect("expected");
            }
        }

        output
    }

    /// Render task summary to console (if available).
    pub fn render_summary(&self) -> std::io::Result<()> {
        let Some(console) = &self.console else {
            return Ok(());
        };

        let summary = self.summary();
        let stuck = self.find_stuck_tasks_default();
        let output =
            Self::format_summary_output(&summary, &stuck, self.config.highlight_stuck_tasks);

        console.print(&RawText(&output))
    }

    /// Render detailed task information to console.
    pub fn render_task_details(&self, task_id: TaskId) -> std::io::Result<()> {
        let Some(console) = &self.console else {
            return Ok(());
        };

        let Some(task) = self.inspect_task(task_id) else {
            let mut output = String::new();
            writeln!(&mut output, "Task {task_id:?} not found").expect("expected");
            return console.print(&RawText(&output));
        };

        let mut output = String::new();
        writeln!(&mut output, "Task Inspector: {task_id:?}").expect("expected");
        output.push_str(&"-".repeat(50));
        output.push('\n');
        writeln!(&mut output, "State:         {}", task.state.name()).expect("expected");
        writeln!(&mut output, "Phase:         {:?}", task.phase).expect("expected");
        writeln!(&mut output, "Region:        {:?}", task.region_id).expect("expected");
        writeln!(&mut output, "Age:           {:.3}s", task.age.as_secs_f64()).expect("expected");
        writeln!(&mut output, "Poll count:    {}", task.poll_count).expect("expected");
        writeln!(&mut output, "Polls left:    {}", task.polls_remaining)
            .expect("write should not fail on String");
        writeln!(&mut output, "Wake pending:  {}", task.wake_pending).expect("expected");

        if !task.obligations.is_empty() {
            output.push_str(&"-".repeat(50));
            output.push('\n');
            output.push_str("Obligations:\n");
            for ob_id in &task.obligations {
                writeln!(&mut output, "  {ob_id:?}").expect("write should not fail on String");
            }
        }

        if !task.waiters.is_empty() {
            output.push_str(&"-".repeat(50));
            output.push('\n');
            output.push_str("Waiters:\n");
            for waiter_id in &task.waiters {
                writeln!(&mut output, "  {waiter_id:?}").expect("write should not fail on String");
            }
        }

        console.print(&RawText(&output))
    }
}

/// Simple wrapper for rendering raw text.
struct RawText<'a>(&'a str);

impl crate::console::Render for RawText<'_> {
    fn render(
        &self,
        out: &mut String,
        _caps: &crate::console::Capabilities,
        _mode: crate::console::ColorMode,
    ) {
        out.push_str(self.0);
    }
}

#[cfg(test)]
#[allow(clippy::arc_with_non_send_sync)]
mod tests {
    use super::*;
    use crate::Budget;
    use crate::time::{TimerDriverHandle, VirtualClock};

    #[test]
    fn test_task_state_info_name() {
        assert_eq!(TaskStateInfo::Created.name(), "Created");
        assert_eq!(TaskStateInfo::Running.name(), "Running");
        assert_eq!(
            TaskStateInfo::CancelRequested {
                reason: "test".to_string()
            }
            .name(),
            "CancelRequested"
        );
        assert_eq!(
            TaskStateInfo::Cancelling {
                reason: "test".to_string()
            }
            .name(),
            "Cancelling"
        );
        assert_eq!(
            TaskStateInfo::Finalizing {
                reason: "test".to_string()
            }
            .name(),
            "Finalizing"
        );
        assert_eq!(
            TaskStateInfo::Completed {
                outcome: "Ok".to_string()
            }
            .name(),
            "Completed"
        );
    }

    #[test]
    fn test_config_defaults() {
        let config = TaskInspectorConfig::default();
        assert_eq!(config.stuck_task_threshold, Duration::from_secs(30));
        assert!(config.show_obligations);
        assert!(config.highlight_stuck_tasks);
    }

    #[test]
    fn test_config_builder() {
        let config = TaskInspectorConfig::default()
            .with_stuck_threshold(Duration::from_secs(60))
            .with_show_obligations(false)
            .with_highlight_stuck_tasks(false);

        assert_eq!(config.stuck_task_threshold, Duration::from_secs(60));
        assert!(!config.show_obligations);
        assert!(!config.highlight_stuck_tasks);
    }

    #[test]
    fn test_summary_default() {
        let summary = TaskSummary::default();
        assert_eq!(summary.total_tasks, 0);
        assert_eq!(summary.created, 0);
        assert_eq!(summary.running, 0);
        assert_eq!(summary.cancelling, 0);
        assert_eq!(summary.completed, 0);
        assert_eq!(summary.stuck_count, 0);
        assert!(summary.by_region.is_empty());
    }

    #[test]
    fn test_task_details_is_terminal() {
        let created_details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Created,
            phase: TaskPhase::Created,
            poll_count: 0,
            polls_remaining: 100,
            created_at: Time::ZERO,
            age: Duration::ZERO,
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };
        assert!(!created_details.is_terminal());

        let completed_details = TaskDetails {
            state: TaskStateInfo::Completed {
                outcome: "Ok".to_string(),
            },
            ..created_details
        };
        assert!(completed_details.is_terminal());
    }

    #[test]
    fn test_task_details_is_running() {
        let running_details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 5,
            polls_remaining: 95,
            created_at: Time::ZERO,
            age: Duration::from_secs(1),
            time_since_last_poll: None,
            wake_pending: true,
            obligations: vec![],
            waiters: vec![],
        };
        assert!(running_details.is_running());
        assert!(!running_details.is_terminal());
        assert!(!running_details.is_cancelling());
    }

    #[test]
    fn test_task_details_is_cancelling() {
        let cancel_requested = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::CancelRequested {
                reason: "Timeout".to_string(),
            },
            phase: TaskPhase::CancelRequested,
            poll_count: 10,
            polls_remaining: 50,
            created_at: Time::ZERO,
            age: Duration::from_secs(5),
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };
        assert!(cancel_requested.is_cancelling());

        let cancelling = TaskDetails {
            state: TaskStateInfo::Cancelling {
                reason: "Timeout".to_string(),
            },
            phase: TaskPhase::Cancelling,
            ..cancel_requested.clone()
        };
        assert!(cancelling.is_cancelling());

        let finalizing = TaskDetails {
            state: TaskStateInfo::Finalizing {
                reason: "Timeout".to_string(),
            },
            phase: TaskPhase::Finalizing,
            ..cancel_requested
        };
        assert!(finalizing.is_cancelling());
    }

    // Pure data-type tests (wave 18 – CyanBarn)

    #[test]
    fn config_debug_clone() {
        let cfg = TaskInspectorConfig::default();
        let cfg2 = cfg;
        assert!(format!("{cfg2:?}").contains("TaskInspectorConfig"));
    }

    #[test]
    fn task_state_info_debug_clone() {
        let s = TaskStateInfo::Running;
        let s2 = s;
        assert!(format!("{s2:?}").contains("Running"));
    }

    #[test]
    fn task_state_info_all_variants_debug() {
        let variants: Vec<TaskStateInfo> = vec![
            TaskStateInfo::Created,
            TaskStateInfo::Running,
            TaskStateInfo::CancelRequested {
                reason: "timeout".into(),
            },
            TaskStateInfo::Cancelling {
                reason: "timeout".into(),
            },
            TaskStateInfo::Finalizing {
                reason: "timeout".into(),
            },
            TaskStateInfo::Completed {
                outcome: "Ok".into(),
            },
        ];
        for v in &variants {
            assert!(!format!("{v:?}").is_empty());
            assert!(!v.name().is_empty());
        }
    }

    #[test]
    fn task_details_debug_clone() {
        let details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Created,
            phase: TaskPhase::Created,
            poll_count: 0,
            polls_remaining: 100,
            created_at: Time::ZERO,
            age: Duration::ZERO,
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };
        let details2 = details;
        assert!(format!("{details2:?}").contains("TaskDetails"));
    }

    #[test]
    fn task_summary_debug_clone_default() {
        let summary = TaskSummary::default();
        let summary2 = summary;
        assert_eq!(summary2.total_tasks, 0);
        assert!(format!("{summary2:?}").contains("TaskSummary"));
    }

    #[test]
    fn task_summary_with_data() {
        let mut summary = TaskSummary {
            total_tasks: 10,
            running: 5,
            completed: 3,
            cancelling: 2,
            stuck_count: 1,
            ..TaskSummary::default()
        };
        summary.by_region.insert(RegionId::testing_default(), 10);
        assert_eq!(summary.by_region.len(), 1);
    }

    #[test]
    fn task_details_with_obligations_and_waiters() {
        let details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 42,
            polls_remaining: 58,
            created_at: Time::ZERO,
            age: Duration::from_secs(10),
            time_since_last_poll: Some(Duration::from_millis(100)),
            wake_pending: true,
            obligations: vec![ObligationId::new_for_test(1, 0)],
            waiters: vec![TaskId::new_for_test(2, 0)],
        };
        assert!(details.is_running());
        assert!(!details.is_terminal());
        assert!(!details.obligations.is_empty());
        assert!(!details.waiters.is_empty());
    }

    #[test]
    fn task_details_stuck_heuristic_ignores_old_polled_task_without_idle_metadata() {
        let details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 3,
            polls_remaining: 97,
            created_at: Time::ZERO,
            age: Duration::from_secs(90),
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };

        assert!(!details.is_potentially_stuck(Duration::from_secs(30)));
    }

    #[test]
    fn task_details_stuck_heuristic_uses_idle_metadata_when_available() {
        let details = TaskDetails {
            id: TaskId::testing_default(),
            region_id: RegionId::testing_default(),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 3,
            polls_remaining: 97,
            created_at: Time::ZERO,
            age: Duration::from_secs(90),
            time_since_last_poll: Some(Duration::from_secs(45)),
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };

        assert!(details.is_potentially_stuck(Duration::from_secs(30)));
    }

    #[test]
    fn wire_snapshot_round_trip_and_schema() {
        let summary = TaskSummaryWire {
            total_tasks: 2,
            created: 0,
            running: 1,
            cancelling: 1,
            completed: 0,
            stuck_count: 0,
            by_region: vec![TaskRegionCountWire {
                region_id: RegionId::new_for_test(1, 0),
                task_count: 2,
            }],
        };
        let first = TaskDetailsWire {
            id: TaskId::new_for_test(1, 0),
            region_id: RegionId::new_for_test(1, 0),
            state: TaskStateInfo::Running,
            phase: "Running".to_string(),
            poll_count: 4,
            polls_remaining: 10,
            created_at: Time::from_nanos(100),
            age_nanos: 200,
            time_since_last_poll_nanos: Some(30),
            wake_pending: true,
            obligations: vec![ObligationId::new_for_test(2, 0)],
            waiters: vec![TaskId::new_for_test(3, 0)],
        };
        let second = TaskDetailsWire {
            id: TaskId::new_for_test(5, 0),
            region_id: RegionId::new_for_test(1, 0),
            state: TaskStateInfo::CancelRequested {
                reason: "Timeout".to_string(),
            },
            phase: "CancelRequested".to_string(),
            poll_count: 2,
            polls_remaining: 3,
            created_at: Time::from_nanos(80),
            age_nanos: 220,
            time_since_last_poll_nanos: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        };

        let snapshot =
            TaskConsoleWireSnapshot::new(Time::from_nanos(999), summary, vec![second, first]);
        assert!(snapshot.has_expected_schema());
        assert_eq!(snapshot.schema_version, TASK_CONSOLE_WIRE_SCHEMA_V1);
        assert_eq!(snapshot.tasks[0].id, TaskId::new_for_test(1, 0));
        assert_eq!(snapshot.tasks[1].id, TaskId::new_for_test(5, 0));

        let encoded = snapshot.to_json().expect("wire snapshot must encode");
        let decoded =
            TaskConsoleWireSnapshot::from_json(&encoded).expect("wire snapshot must decode");
        assert_eq!(decoded, snapshot);
    }

    #[test]
    fn details_wire_normalizes_collections_and_phase_name() {
        let details = TaskDetails {
            id: TaskId::new_for_test(10, 0),
            region_id: RegionId::new_for_test(1, 0),
            state: TaskStateInfo::Finalizing {
                reason: "Shutdown".to_string(),
            },
            phase: TaskPhase::Finalizing,
            poll_count: 7,
            polls_remaining: 9,
            created_at: Time::from_nanos(10),
            age: Duration::from_nanos(99),
            time_since_last_poll: Some(Duration::from_nanos(7)),
            wake_pending: false,
            obligations: vec![
                ObligationId::new_for_test(3, 0),
                ObligationId::new_for_test(1, 0),
            ],
            waiters: vec![TaskId::new_for_test(8, 0), TaskId::new_for_test(2, 0)],
        };

        let wire = TaskDetailsWire::from(details);
        assert_eq!(wire.phase, "Finalizing");
        assert_eq!(wire.age_nanos, 99);
        assert_eq!(wire.time_since_last_poll_nanos, Some(7));
        assert_eq!(wire.obligations[0], ObligationId::new_for_test(1, 0));
        assert_eq!(wire.obligations[1], ObligationId::new_for_test(3, 0));
        assert_eq!(wire.waiters[0], TaskId::new_for_test(2, 0));
        assert_eq!(wire.waiters[1], TaskId::new_for_test(8, 0));
    }

    fn scrub_task_inspector_snapshot(
        snapshot: &str,
        regions: &[(RegionId, &str)],
        tasks: &[(TaskId, &str)],
        obligations: &[(ObligationId, &str)],
    ) -> String {
        let mut scrubbed = snapshot.to_string();
        for (region_id, label) in regions {
            scrubbed = scrubbed.replace(&format!("{region_id:?}"), label);
            scrubbed = scrubbed.replace(
                &serde_json::to_string_pretty(region_id).expect("region id should encode"),
                &format!("\"{label}\""),
            );
        }
        for (task_id, label) in tasks {
            scrubbed = scrubbed.replace(&format!("{task_id:?}"), label);
            scrubbed = scrubbed.replace(
                &serde_json::to_string_pretty(task_id).expect("task id should encode"),
                &format!("\"{label}\""),
            );
        }
        for (obligation_id, label) in obligations {
            scrubbed = scrubbed.replace(&format!("{obligation_id:?}"), label);
            scrubbed = scrubbed.replace(
                &serde_json::to_string_pretty(obligation_id).expect("obligation id should encode"),
                &format!("\"{label}\""),
            );
        }
        scrubbed
    }

    #[test]
    fn task_inspector_introspection_output_mixed_states_snapshot() {
        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_secs(5)));
        state.now = Time::from_secs(5);
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(Arc::clone(&clock)));

        let root = state.create_root_region(Budget::INFINITE);
        let child = state
            .create_child_region(root, Budget::INFINITE)
            .expect("create child region");

        let (created_id, _created_handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create created task");
        let (running_id, _running_handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create running task");
        let (cancel_requested_id, _cancel_handle) = state
            .create_task(child, Budget::INFINITE, async {})
            .expect("create cancelling task");
        let (completed_id, _completed_handle) = state
            .create_task(child, Budget::INFINITE, async {})
            .expect("create completed task");
        let (waiter_id, _waiter_handle) = state
            .create_task(child, Budget::INFINITE, async {})
            .expect("create waiter task");

        {
            let created = state.task_mut(created_id).expect("created task record");
            created.polls_remaining = 12;
        }

        let running_cx = {
            let running = state.task_mut(running_id).expect("running task record");
            running.state = TaskState::Running;
            running.phase.store(TaskPhase::Running);
            running.polls_remaining = 6;
            running.increment_polls();
            running.increment_polls();
            running.waiters.push(waiter_id);
            running.wake_state.notify();
            running.cx.as_ref().expect("running task cx").clone()
        };

        {
            let cancel_requested = state
                .task_mut(cancel_requested_id)
                .expect("cancel requested task record");
            cancel_requested.polls_remaining = 4;
            cancel_requested.increment_polls();
            assert!(cancel_requested.request_cancel(crate::types::CancelReason::timeout()));
        }

        {
            let completed = state.task_mut(completed_id).expect("completed task record");
            completed.state = TaskState::Running;
            completed.phase.store(TaskPhase::Running);
            completed.polls_remaining = 0;
            completed.increment_polls();
            assert!(completed.complete(Outcome::Ok(())));
        }

        {
            let waiter = state.task_mut(waiter_id).expect("waiter task record");
            waiter.state = TaskState::Running;
            waiter.phase.store(TaskPhase::Running);
            waiter.polls_remaining = 9;
            waiter.increment_polls();
        }

        let pending_obligation = state
            .create_obligation(crate::record::ObligationKind::IoOp, running_id, root, None)
            .expect("create pending obligation");

        clock.advance_to(Time::from_secs(35));
        running_cx.checkpoint().expect("checkpoint");
        clock.advance_to(Time::from_secs(45));

        let inspector = TaskInspector::with_config(
            Arc::new(state),
            None,
            TaskInspectorConfig::default().with_stuck_threshold(Duration::from_secs(20)),
        );
        let summary = inspector.summary();
        let stuck = inspector.find_stuck_tasks_default();
        assert_eq!(
            stuck.iter().map(|task| task.id).collect::<Vec<_>>(),
            vec![created_id]
        );

        let rendered = TaskInspector::format_summary_output(&summary, &stuck, true);
        let wire = inspector
            .wire_snapshot_pretty_json()
            .expect("wire snapshot should encode");
        let scrubbed = scrub_task_inspector_snapshot(
            &format!("== Summary ==\n{rendered}\n== Wire ==\n{wire}\n"),
            &[(root, "<region-root>"), (child, "<region-child>")],
            &[
                (created_id, "<task-created>"),
                (running_id, "<task-running>"),
                (cancel_requested_id, "<task-cancel-requested>"),
                (completed_id, "<task-completed>"),
                (waiter_id, "<task-waiter>"),
            ],
            &[(pending_obligation, "<obligation-pending>")],
        );

        insta::assert_snapshot!("task_inspector_introspection_output_mixed_states", scrubbed);
    }

    #[test]
    fn format_summary_output_hides_stuck_section_when_highlight_disabled() {
        let mut summary = TaskSummary {
            total_tasks: 1,
            running: 1,
            stuck_count: 1,
            ..TaskSummary::default()
        };
        summary.by_region.insert(RegionId::new_for_test(7, 0), 1);
        let stuck = vec![TaskDetails {
            id: TaskId::new_for_test(11, 0),
            region_id: RegionId::new_for_test(7, 0),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 0,
            polls_remaining: 10,
            created_at: Time::ZERO,
            age: Duration::from_secs(90),
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        }];
        let task_label = format!("{:?}", stuck[0].id);

        let output = TaskInspector::format_summary_output(&summary, &stuck, false);
        assert!(output.contains("Stuck: 1"));
        assert!(!output.contains("POTENTIAL STUCK TASKS:"));
        assert!(!output.contains(&task_label));
    }

    #[test]
    fn format_summary_output_shows_stuck_section_when_highlight_enabled() {
        let mut summary = TaskSummary {
            total_tasks: 1,
            running: 1,
            stuck_count: 1,
            ..TaskSummary::default()
        };
        summary.by_region.insert(RegionId::new_for_test(7, 0), 1);
        let stuck = vec![TaskDetails {
            id: TaskId::new_for_test(11, 0),
            region_id: RegionId::new_for_test(7, 0),
            state: TaskStateInfo::Running,
            phase: TaskPhase::Running,
            poll_count: 0,
            polls_remaining: 10,
            created_at: Time::ZERO,
            age: Duration::from_secs(90),
            time_since_last_poll: None,
            wake_pending: false,
            obligations: vec![],
            waiters: vec![],
        }];
        let task_label = format!("{:?}", stuck[0].id);

        let output = TaskInspector::format_summary_output(&summary, &stuck, true);
        assert!(output.contains("POTENTIAL STUCK TASKS:"));
        assert!(output.contains(&task_label));
    }

    #[test]
    fn inspector_uses_runtime_logical_time_without_timer_driver() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        state.now = Time::from_secs(65);

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.age, Duration::from_secs(65));

        let summary = inspector.summary();
        assert_eq!(summary.stuck_count, 1);

        let wire = inspector.wire_snapshot();
        assert_eq!(wire.generated_at, Time::from_secs(65));
    }

    #[test]
    fn inspector_does_not_flag_old_polled_tasks_without_last_poll_duration() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let task = state.task_mut(task_id).expect("task record");
        task.state = TaskState::Running;
        task.increment_polls();
        state.now = Time::from_secs(65);

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.poll_count, 1);
        assert!(!details.is_potentially_stuck(Duration::from_secs(30)));
        assert!(inspector.find_stuck_tasks_default().is_empty());
        assert_eq!(inspector.summary().stuck_count, 0);
    }

    #[test]
    fn inspector_prefers_timer_driver_when_available() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        state.now = Time::from_secs(5);
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(Arc::new(
            VirtualClock::starting_at(Time::from_secs(8)),
        )));

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.age, Duration::from_secs(8));

        let wire = inspector.wire_snapshot();
        assert_eq!(wire.generated_at, Time::from_secs(8));
    }

    #[test]
    fn inspector_reports_checkpoint_idle_time_from_timer_driver() {
        let mut state = RuntimeState::new();
        let clock = Arc::new(VirtualClock::starting_at(Time::from_secs(3)));
        state.now = Time::from_secs(3);
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(Arc::clone(&clock)));
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let cx = {
            let task = state.task_mut(task_id).expect("task record");
            task.state = TaskState::Running;
            task.increment_polls();
            task.cx.as_ref().expect("task cx").clone()
        };
        cx.checkpoint().expect("checkpoint");
        clock.advance_to(Time::from_secs(8));

        let inspector = TaskInspector::with_config(
            Arc::new(state),
            None,
            TaskInspectorConfig::default().with_stuck_threshold(Duration::from_secs(4)),
        );
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.time_since_last_poll, Some(Duration::from_secs(5)));
        assert!(details.is_potentially_stuck(Duration::from_secs(4)));
        assert_eq!(inspector.summary().stuck_count, 1);
        assert_eq!(
            inspector.wire_snapshot().tasks[0].time_since_last_poll_nanos,
            Some(duration_to_nanos(Duration::from_secs(5)))
        );
    }

    #[test]
    fn inspector_does_not_mix_wall_clock_checkpoint_idle_without_timer_driver() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let task = state.task_mut(task_id).expect("task record");
        task.state = TaskState::Running;
        task.increment_polls();
        if let Some(inner) = &task.cx_inner {
            inner.write().checkpoint_state.record_at(Time::from_secs(3));
        }
        state.now = Time::from_secs(5);

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.age, Duration::from_secs(5));
        assert_eq!(details.time_since_last_poll, None);
        assert!(!details.is_potentially_stuck(Duration::from_secs(30)));
        assert_eq!(inspector.summary().stuck_count, 0);
        assert_eq!(
            inspector.wire_snapshot().tasks[0].time_since_last_poll_nanos,
            None
        );
    }

    #[test]
    fn inspector_does_not_mix_checkpoint_time_after_late_timer_driver_attachment() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let cx = {
            let task = state.task_mut(task_id).expect("task record");
            task.state = TaskState::Running;
            task.increment_polls();
            task.cx.as_ref().expect("task cx").clone()
        };
        cx.checkpoint().expect("checkpoint");
        state.set_timer_driver(TimerDriverHandle::with_virtual_clock(Arc::new(
            VirtualClock::starting_at(Time::from_secs(60)),
        )));

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.time_since_last_poll, None);
        assert_eq!(inspector.summary().stuck_count, 0);
    }

    #[test]
    fn inspector_only_reports_only_pending_obligations() {
        let mut state = RuntimeState::new();
        let root = state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = state
            .create_task(root, Budget::INFINITE, async {})
            .expect("create task");
        let pending = state
            .create_obligation(crate::record::ObligationKind::IoOp, task_id, root, None)
            .expect("create pending obligation");
        let committed = state
            .create_obligation(crate::record::ObligationKind::Ack, task_id, root, None)
            .expect("create committed obligation");
        state
            .commit_obligation(committed)
            .expect("commit obligation");
        let aborted = state
            .create_obligation(crate::record::ObligationKind::Lease, task_id, root, None)
            .expect("create aborted obligation");
        state
            .abort_obligation(aborted, crate::record::ObligationAbortReason::Cancel)
            .expect("abort obligation");

        let inspector = TaskInspector::new(Arc::new(state), None);
        let details = inspector.inspect_task(task_id).expect("task exists");
        assert_eq!(details.obligations, vec![pending]);
    }
}