padzapp 1.5.0

An ergonomic, context-aware scratch pad library with plain text storage
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
//! # Pad Identifiers: UUID vs Display Index
//!
//! Pads need to be referenced by ID. Since padz is a CLI tool, the primary interface is text.
//! While UUIDs are the correct technical choice for unique identification, they are cumbersome to type.
//!
//! Sequential IDs are the logical user-facing choice. However, naive sequential indexing
//! (numbering the current output list 1..N) creates ambiguity and "index drift".
//!
//! ## The Dual-Identifier Solution
//!
//! Padz uses a dual-identifier system:
//!
//! 1. **UUID (Internal)**: Immutable, canonical, globally unique.
//! 2. **Display Index (External)**: A stable integer generated from a canonical ordering.
//!
//! ## Canonical Ordering
//!
//! Even when filtering or searching, the ID assigned to a pad remains consistent with its
//! position in the full, unfiltered list. This ensures `padz delete 2` always targets the
//! same pad regardless of the current view.
//!
//! **Ordering Logic**:
//! - Active/archived/deleted pads sorted by the configured [`OrderingKey`] descending
//!   (either `created_at` or `updated_at`; newest = 1)
//! - Pinned pads get an additional `p1`, `p2`... index (appear in both pinned and regular lists)
//! - Deleted pads: Separate bucket `d1`, `d2`...
//!
//! ## Pinned Pads Have Two Indexes
//!
//! A pinned pad appears **twice** in the indexed list:
//! - Once with a `Pinned` index (`p1`, `p2`, etc.)
//! - Once with its canonical `Regular` index (`1`, `2`, etc.)
//!
//! This ensures stability when a pad is unpinned—the regular index remains the same.
//!
//! ## Implementation
//!
//! - [`index_pads`]: Assigns canonical display indexes to a list of pads
//! - [`DisplayIndex`]: The user-facing index enum (`Regular`, `Pinned`, `Deleted`)
//! - [`DisplayPad`]: Connects a `Pad` with its `DisplayIndex`
//! - [`parse_index_or_range`]: Parses user input like `"1-3"` into `Vec<DisplayIndex>`
//!
//! **Developer Note**: When implementing list/view commands, always use [`index_pads`].
//! Never manually enumerate a list of pads, as you will break the canonical ID association.
//!
//! For input resolution (mapping indexes to UUIDs), see the [`crate::api`] module.

use crate::config::OrderingKey;
use crate::model::Pad;
use serde::Serialize;
use std::cell::Cell;
use std::collections::HashMap;
use std::str::FromStr;
use uuid::Uuid;

thread_local! {
    /// The currently active ordering key for this thread. Set once by the CLI
    /// entry point (or by tests that need non-default ordering) and read by
    /// [`current_ordering_key`] whenever an ordering decision is made without
    /// an explicit argument (e.g. inside [`crate::commands::helpers::indexed_pads`]).
    ///
    /// The choice of a thread-local (rather than a global/`OnceLock`) is
    /// deliberate: the test harness reuses threads across tests, but
    /// a) every test that cares about ordering sets this explicitly, and
    /// b) callers that want a guaranteed value pass [`OrderingKey`] directly to
    ///    [`index_pads`]. This cell only affects the implicit default path.
    static CURRENT_ORDERING: Cell<OrderingKey> = const { Cell::new(OrderingKey::CreatedAt) };
}

/// Set the current thread's ordering key. Called once from the CLI entry point
/// after config load. Tests can call this to exercise non-default orderings.
pub fn set_ordering_key(key: OrderingKey) {
    CURRENT_ORDERING.with(|c| c.set(key));
}

/// Read the current thread's ordering key. Defaults to [`OrderingKey::CreatedAt`]
/// when no one has called [`set_ordering_key`] on this thread.
pub fn current_ordering_key() -> OrderingKey {
    CURRENT_ORDERING.with(|c| c.get())
}

/// A segment of text in a search match, either plain text or a matched term.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "type", content = "text")]
pub enum MatchSegment {
    Plain(String),
    Match(String),
}

/// A line containing a search match.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SearchMatch {
    pub line_number: usize, // 0 for title, 1+ for content lines
    pub segments: Vec<MatchSegment>,
}

/// A user-facing index for a pad.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum DisplayIndex {
    Pinned(usize),
    Regular(usize),
    Archived(usize),
    Deleted(usize),
}

impl std::fmt::Display for DisplayIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DisplayIndex::Pinned(i) => write!(f, "p{}", i),
            DisplayIndex::Regular(i) => write!(f, "{}", i),
            DisplayIndex::Archived(i) => write!(f, "ar{}", i),
            DisplayIndex::Deleted(i) => write!(f, "d{}", i),
        }
    }
}

/// A user input to select a pad, either by its index, UUID, or a search term for its title.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PadSelector {
    Path(Vec<DisplayIndex>),
    Range(Vec<DisplayIndex>, Vec<DisplayIndex>), // Start Path, End Path
    Uuid(Uuid),
    /// A hex prefix of a UUID (e.g. "766d5dab" from `padz list --short-uuid`).
    /// Resolved by prefix-matching against pad UUIDs.
    ShortUuid(String),
    Title(String),
}

impl std::fmt::Display for PadSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PadSelector::Path(path) => {
                let s: Vec<String> = path.iter().map(|idx| idx.to_string()).collect();
                write!(f, "{}", s.join("."))
            }
            PadSelector::Range(start, end) => {
                let s_start: Vec<String> = start.iter().map(|idx| idx.to_string()).collect();
                let s_end: Vec<String> = end.iter().map(|idx| idx.to_string()).collect();
                write!(f, "{}-{}", s_start.join("."), s_end.join("."))
            }
            PadSelector::Uuid(uuid) => write!(f, "{}", uuid),
            PadSelector::ShortUuid(hex) => write!(f, "{}", hex),
            PadSelector::Title(t) => write!(f, "\"{}\"", t),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct DisplayPad {
    pub pad: Pad,
    pub index: DisplayIndex,
    pub matches: Option<Vec<SearchMatch>>,
    pub children: Vec<DisplayPad>,
}

/// Internal tag for which bucket a pad belongs to during indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IndexBucket {
    Active,
    Archived,
    Deleted,
}

/// A pad tagged with its bucket membership for indexing purposes.
#[derive(Debug, Clone)]
struct TaggedPad {
    pad: Pad,
    bucket: IndexBucket,
}

/// Assigns canonical display indexes to pads from three lifecycle buckets,
/// building a tree structure.
///
/// **Per-parent bucketing**: The same pinned/regular/archived/deleted indexing logic
/// is applied recursively at each nesting level. Each parent maintains its own index namespace:
/// - Root level: `p1`, `1`, `2`, `ar1`, `d1`
/// - Children of pad 1: `1.p1`, `1.1`, `1.2`, `1.ar1`, `1.d1`
///
/// **Dual indexing**: Pinned active pads appear **twice** at each level—once with a `Pinned`
/// index and once with a `Regular` index. This ensures stability when unpinning.
///
/// The returned list is ordered: pinned, regular, archived, deleted.
/// Each entry's `children` vector follows the same ordering recursively.
///
/// `ordering` controls the sort key applied within each bucket and at each nesting level.
pub fn index_pads(
    active: Vec<Pad>,
    archived: Vec<Pad>,
    deleted: Vec<Pad>,
    ordering: OrderingKey,
) -> Vec<DisplayPad> {
    // Tag each pad with its bucket
    let mut all_tagged: Vec<TaggedPad> = Vec::new();
    for pad in active {
        all_tagged.push(TaggedPad {
            pad,
            bucket: IndexBucket::Active,
        });
    }
    for pad in archived {
        all_tagged.push(TaggedPad {
            pad,
            bucket: IndexBucket::Archived,
        });
    }
    for pad in deleted {
        all_tagged.push(TaggedPad {
            pad,
            bucket: IndexBucket::Deleted,
        });
    }

    // Group by parent_id
    let mut parent_map: HashMap<Option<Uuid>, Vec<TaggedPad>> = HashMap::new();
    for tagged in all_tagged {
        parent_map
            .entry(tagged.pad.metadata.parent_id)
            .or_default()
            .push(tagged);
    }

    // Process roots (parent_id = None), recursively indexing their children
    let root_pads = parent_map.remove(&None).unwrap_or_default();
    index_level(root_pads, &parent_map, ordering)
}

/// Maximum `updated_at` across a pad's subtree, used as the effective sort key
/// under [`OrderingKey::UpdatedAt`].
///
/// This is computed at index time rather than persisted on ancestor pads:
/// `metadata.updated_at` is reserved as the file-mtime proxy used by store
/// reconciliation, and writing a bubbled timestamp onto an ancestor at edit
/// time risks masking external edits that haven't been reconciled yet.
fn effective_updated_at(
    id: Uuid,
    parent_map: &HashMap<Option<Uuid>, Vec<TaggedPad>>,
) -> chrono::DateTime<chrono::Utc> {
    let mut max = chrono::DateTime::<chrono::Utc>::MIN_UTC;
    if let Some(children) = parent_map.get(&Some(id)) {
        for child in children {
            let child_self = child.pad.metadata.updated_at;
            let child_subtree = effective_updated_at(child.pad.metadata.id, parent_map);
            let m = child_self.max(child_subtree);
            if m > max {
                max = m;
            }
        }
    }
    max
}

/// Indexes a single level of the tree (siblings with the same parent).
///
/// Applies four-pass indexing at this level:
/// 1. **Pinned pass**: `Pinned(1)`, `Pinned(2)`, etc. for pinned active pads
/// 2. **Regular pass**: `Regular(1)`, `Regular(2)`, etc. for ALL active pads
/// 3. **Archived pass**: `Archived(1)`, `Archived(2)`, etc. for archived pads
/// 4. **Deleted pass**: `Deleted(1)`, `Deleted(2)`, etc. for deleted pads
///
/// Note: Pinned active pads get entries in BOTH the pinned and regular passes (dual indexing).
/// This is recursive—each pad's children are indexed the same way.
///
/// Under [`OrderingKey::UpdatedAt`], a pad's effective sort key is the maximum
/// `updated_at` across the pad and its descendants — computed lazily here, never
/// persisted to the pad's stored `updated_at`. That field is reserved as the
/// content-mtime proxy used by [`crate::store`] reconciliation; mutating it on
/// ancestors at write time would mask not-yet-synced external edits.
fn index_level(
    mut pads: Vec<TaggedPad>,
    parent_map: &HashMap<Option<Uuid>, Vec<TaggedPad>>,
    ordering: OrderingKey,
) -> Vec<DisplayPad> {
    // Sort descending (newest first) within this level, keyed per config.
    // Tie-breakers (in order) keep DI assignment deterministic when timestamps match,
    // which is common under UpdatedAt because nested edits propagate identical values.
    pads.sort_by(|a, b| match ordering {
        OrderingKey::CreatedAt => b
            .pad
            .metadata
            .created_at
            .cmp(&a.pad.metadata.created_at)
            .then_with(|| b.pad.metadata.updated_at.cmp(&a.pad.metadata.updated_at))
            .then_with(|| a.pad.metadata.id.cmp(&b.pad.metadata.id)),
        OrderingKey::UpdatedAt => effective_updated_at(b.pad.metadata.id, parent_map)
            .max(b.pad.metadata.updated_at)
            .cmp(
                &effective_updated_at(a.pad.metadata.id, parent_map).max(a.pad.metadata.updated_at),
            )
            .then_with(|| b.pad.metadata.created_at.cmp(&a.pad.metadata.created_at))
            .then_with(|| a.pad.metadata.id.cmp(&b.pad.metadata.id)),
    });

    let mut results = Vec::new();

    // Helper closure to build DisplayPad and recurse
    let mut add_pad = |tagged: TaggedPad, index: DisplayIndex| {
        let children = parent_map
            .get(&Some(tagged.pad.metadata.id))
            .cloned()
            .unwrap_or_default();

        // Recurse for children
        let indexed_children = index_level(children, parent_map, ordering);

        results.push(DisplayPad {
            pad: tagged.pad,
            index,
            matches: None,
            children: indexed_children,
        });
    };

    // First pass: Pinned (active + pinned)
    let mut pinned_idx = 1;
    for tagged in &pads {
        if tagged.bucket == IndexBucket::Active && tagged.pad.metadata.is_pinned {
            add_pad(tagged.clone(), DisplayIndex::Pinned(pinned_idx));
            pinned_idx += 1;
        }
    }

    // Second pass: Regular (all active)
    let mut regular_idx = 1;
    for tagged in &pads {
        if tagged.bucket == IndexBucket::Active {
            add_pad(tagged.clone(), DisplayIndex::Regular(regular_idx));
            regular_idx += 1;
        }
    }

    // Third pass: Archived
    let mut archived_idx = 1;
    for tagged in &pads {
        if tagged.bucket == IndexBucket::Archived {
            add_pad(tagged.clone(), DisplayIndex::Archived(archived_idx));
            archived_idx += 1;
        }
    }

    // Fourth pass: Deleted
    let mut deleted_idx = 1;
    for tagged in &pads {
        if tagged.bucket == IndexBucket::Deleted {
            add_pad(tagged.clone(), DisplayIndex::Deleted(deleted_idx));
            deleted_idx += 1;
        }
    }

    results
}

impl std::str::FromStr for DisplayIndex {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Check "ar" before single-char prefixes to avoid ambiguity
        if let Some(rest) = s.strip_prefix("ar") {
            if let Ok(n) = rest.parse() {
                return Ok(DisplayIndex::Archived(n));
            }
        }
        if let Some(rest) = s.strip_prefix('p') {
            if let Ok(n) = rest.parse() {
                return Ok(DisplayIndex::Pinned(n));
            }
        }
        if let Some(rest) = s.strip_prefix('d') {
            if let Ok(n) = rest.parse() {
                return Ok(DisplayIndex::Deleted(n));
            }
        }
        if let Ok(n) = s.parse() {
            return Ok(DisplayIndex::Regular(n));
        }
        Err(format!("Invalid index format: {}", s))
    }
}

/// Parses a single input string that may be either a path or a range of paths.
///
/// Supports formats:
/// - Path: "3", "3.1", "p1", "d2.1"
/// - Range: "1-3", "1.1-1.3", "1.2-2.1"
pub fn parse_index_or_range(s: &str) -> Result<PadSelector, String> {
    // Try UUID first — UUIDs contain hyphens that would confuse the range parser.
    // Uuid::parse_str is strict and won't match any DI format (1, p1, 1-3, etc.)
    if let Ok(uuid) = Uuid::parse_str(s) {
        return Ok(PadSelector::Uuid(uuid));
    }

    // Check if it's a range (contains '-' but not at the start for negative numbers)
    // We need to be careful: "p1-p3" has '-' in the middle
    if let Some(dash_pos) = s.find('-') {
        // Don't treat leading '-' as a range separator
        if dash_pos > 0 {
            let start_str = &s[..dash_pos];
            let end_str = &s[dash_pos + 1..];

            // Parse endpoints as paths
            let start_path = parse_path(start_str)?;
            let end_path = parse_path(end_str)?;

            return Ok(PadSelector::Range(start_path, end_path));
        }
    }

    // Not a range — try as a DI path first, fall back to short UUID hex prefix
    match parse_path(s) {
        Ok(path) => Ok(PadSelector::Path(path)),
        Err(_) if is_hex_string(s) => Ok(PadSelector::ShortUuid(s.to_lowercase())),
        Err(e) => Err(e),
    }
}

/// Returns true if the string is a non-empty hex string (0-9, a-f, case-insensitive).
fn is_hex_string(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_ascii_hexdigit())
}

/// Parses a dot-separated path string into a vector of DisplayIndex.
/// e.g. "1.2" -> [Regular(1), Regular(2)]
/// "p1" -> [Pinned(1)]
fn parse_path(s: &str) -> Result<Vec<DisplayIndex>, String> {
    s.split('.').map(DisplayIndex::from_str).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_pad(title: &str, pinned: bool) -> Pad {
        let mut p = Pad::new(title.to_string(), "".to_string());
        p.metadata.is_pinned = pinned;
        p
    }

    #[test]
    fn test_indexing_buckets() {
        let p1 = make_pad("Regular 1", false);
        let p2 = make_pad("Pinned 1", true);
        let p3 = make_pad("Deleted 1", false);
        let p4 = make_pad("Regular 2", false);

        let active = vec![p1, p2, p4];
        let deleted = vec![p3];
        let indexed = index_pads(active, vec![], deleted, OrderingKey::CreatedAt);

        // With the canonical indexing (newest first), pinned pads appear in BOTH
        // the pinned list AND the regular list.
        // Active creation order: Regular 1, Pinned 1, Regular 2
        // Active reverse chronological: Regular 2, Pinned 1, Regular 1
        // Expected entries:
        // - p1: Pinned 1 (only pinned active pad)
        // - 1: Regular 2 (newest active)
        // - 2: Pinned 1 (second newest active)
        // - 3: Regular 1 (oldest active)
        // - d1: Deleted 1

        // Check pinned index
        let pinned_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Pinned(_)))
            .collect();
        assert_eq!(pinned_entries.len(), 1);
        assert_eq!(pinned_entries[0].pad.metadata.title, "Pinned 1");
        assert_eq!(pinned_entries[0].index, DisplayIndex::Pinned(1));

        // Check regular indexes - should include ALL active pads (newest first)
        let regular_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Regular(_)))
            .collect();
        assert_eq!(regular_entries.len(), 3);
        assert_eq!(regular_entries[0].pad.metadata.title, "Regular 2"); // newest = 1
        assert_eq!(regular_entries[0].index, DisplayIndex::Regular(1));
        assert_eq!(regular_entries[2].pad.metadata.title, "Regular 1"); // oldest = 3
        assert_eq!(regular_entries[2].index, DisplayIndex::Regular(3));

        // Check deleted index
        let deleted_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Deleted(_)))
            .collect();
        assert_eq!(deleted_entries.len(), 1);
        assert_eq!(deleted_entries[0].pad.metadata.title, "Deleted 1");
    }

    #[test]
    fn test_pinned_pad_has_both_indexes() {
        let p1 = make_pad("Note A", false);
        let p2 = make_pad("Note B", true); // pinned
        let p3 = make_pad("Note C", false);

        let indexed = index_pads(vec![p1, p2, p3], vec![], vec![], OrderingKey::CreatedAt);

        // Creation order: Note A, Note B, Note C
        // Reverse chronological: Note C (1), Note B (2), Note A (3)
        // Note B should appear twice: as p1 and as regular index 2
        let note_b_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| dp.pad.metadata.title == "Note B")
            .collect();
        assert_eq!(note_b_entries.len(), 2);

        // One should be Pinned(1)
        assert!(note_b_entries
            .iter()
            .any(|dp| dp.index == DisplayIndex::Pinned(1)));
        // One should be Regular(2) - it's the second newest pad
        assert!(note_b_entries
            .iter()
            .any(|dp| dp.index == DisplayIndex::Regular(2)));
    }

    #[test]
    fn test_parsing() {
        use std::str::FromStr;

        assert_eq!(DisplayIndex::from_str("1"), Ok(DisplayIndex::Regular(1)));
        assert_eq!(DisplayIndex::from_str("42"), Ok(DisplayIndex::Regular(42)));
        assert_eq!(DisplayIndex::from_str("p1"), Ok(DisplayIndex::Pinned(1)));
        assert_eq!(DisplayIndex::from_str("p99"), Ok(DisplayIndex::Pinned(99)));
        assert_eq!(DisplayIndex::from_str("d1"), Ok(DisplayIndex::Deleted(1)));
        assert_eq!(DisplayIndex::from_str("d5"), Ok(DisplayIndex::Deleted(5)));
        assert_eq!(DisplayIndex::from_str("ar1"), Ok(DisplayIndex::Archived(1)));
        assert_eq!(
            DisplayIndex::from_str("ar99"),
            Ok(DisplayIndex::Archived(99))
        );

        assert!(DisplayIndex::from_str("").is_err());
        assert!(DisplayIndex::from_str("abc").is_err());
        assert!(DisplayIndex::from_str("p").is_err());
        assert!(DisplayIndex::from_str("d").is_err());
        assert!(DisplayIndex::from_str("ar").is_err());
        assert!(DisplayIndex::from_str("12a").is_err());
        assert!(DisplayIndex::from_str("p1a").is_err());
    }

    #[test]
    fn test_parse_single_index() {
        // Single indexes should return a vec with one element
        assert_eq!(
            parse_index_or_range("3"),
            Ok(PadSelector::Path(vec![DisplayIndex::Regular(3)]))
        );
        assert_eq!(
            parse_index_or_range("p2"),
            Ok(PadSelector::Path(vec![DisplayIndex::Pinned(2)]))
        );
        assert_eq!(
            parse_index_or_range("d1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Deleted(1)]))
        );
        assert_eq!(
            parse_index_or_range("ar3"),
            Ok(PadSelector::Path(vec![DisplayIndex::Archived(3)]))
        );
    }

    #[test]
    fn test_parse_regular_range() {
        assert_eq!(
            parse_index_or_range("3-5"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Regular(3)],
                vec![DisplayIndex::Regular(5)]
            ))
        );

        // Single element range (start == end)
        assert_eq!(
            parse_index_or_range("3-3"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Regular(3)],
                vec![DisplayIndex::Regular(3)]
            ))
        );
    }

    #[test]
    fn test_parse_pinned_range() {
        assert_eq!(
            parse_index_or_range("p1-p3"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Pinned(1)],
                vec![DisplayIndex::Pinned(3)]
            ))
        );
    }

    #[test]
    fn test_parse_deleted_range() {
        assert_eq!(
            parse_index_or_range("d2-d4"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Deleted(2)],
                vec![DisplayIndex::Deleted(4)]
            ))
        );
    }

    #[test]
    fn test_parse_archived_range() {
        assert_eq!(
            parse_index_or_range("ar1-ar5"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Archived(1)],
                vec![DisplayIndex::Archived(5)]
            ))
        );
    }

    #[test]
    fn test_parse_range_invalid_format() {
        // Invalid start
        let result = parse_index_or_range("abc-5");
        assert!(result.is_err());

        // Invalid end
        let result = parse_index_or_range("3-xyz");
        assert!(result.is_err());

        // Empty parts
        let result = parse_index_or_range("-5");
        assert!(result.is_err());

        let result = parse_index_or_range("3-");
        assert!(result.is_err());
    }

    // ==================== Tree-specific tests ====================

    #[test]
    fn test_parse_nested_path() {
        // Path notation: 1.2.3 means child 3 of child 2 of root 1
        assert_eq!(
            parse_index_or_range("1.2"),
            Ok(PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(2)
            ]))
        );
        assert_eq!(
            parse_index_or_range("1.2.3"),
            Ok(PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(2),
                DisplayIndex::Regular(3)
            ]))
        );
    }

    #[test]
    fn test_parse_nested_pinned_path() {
        // Pinned child of root 1: 1.p1
        assert_eq!(
            parse_index_or_range("1.p1"),
            Ok(PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Pinned(1)
            ]))
        );
        // Deeply nested pinned: 1.2.p1
        assert_eq!(
            parse_index_or_range("1.2.p1"),
            Ok(PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(2),
                DisplayIndex::Pinned(1)
            ]))
        );
    }

    #[test]
    fn test_parse_nested_range() {
        // Range within a tree: 1.1-1.3
        assert_eq!(
            parse_index_or_range("1.1-1.3"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Regular(1), DisplayIndex::Regular(1)],
                vec![DisplayIndex::Regular(1), DisplayIndex::Regular(3)]
            ))
        );
        // Cross-parent range: 1.2-2.1
        assert_eq!(
            parse_index_or_range("1.2-2.1"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Regular(1), DisplayIndex::Regular(2)],
                vec![DisplayIndex::Regular(2), DisplayIndex::Regular(1)]
            ))
        );
    }

    #[test]
    fn test_tree_with_nested_children() {
        // Build a tree: Root -> Child -> Grandchild (all active)
        let mut grandchild = make_pad("Grandchild", false);
        let mut child = make_pad("Child", false);
        let root = make_pad("Root", false);

        // Set up parent relationships
        child.metadata.parent_id = Some(root.metadata.id);
        grandchild.metadata.parent_id = Some(child.metadata.id);

        let indexed = index_pads(
            vec![root, child, grandchild],
            vec![],
            vec![],
            OrderingKey::CreatedAt,
        );

        // Should have 1 root
        assert_eq!(indexed.len(), 1);
        assert_eq!(indexed[0].pad.metadata.title, "Root");
        assert_eq!(indexed[0].index, DisplayIndex::Regular(1));

        // Root should have 1 child
        assert_eq!(indexed[0].children.len(), 1);
        assert_eq!(indexed[0].children[0].pad.metadata.title, "Child");
        assert_eq!(indexed[0].children[0].index, DisplayIndex::Regular(1));

        // Child should have 1 grandchild
        assert_eq!(indexed[0].children[0].children.len(), 1);
        assert_eq!(
            indexed[0].children[0].children[0].pad.metadata.title,
            "Grandchild"
        );
        assert_eq!(
            indexed[0].children[0].children[0].index,
            DisplayIndex::Regular(1)
        );
    }

    #[test]
    fn test_tree_pinned_child_has_dual_index() {
        // Root with a pinned child - child should appear twice in children
        let mut child = make_pad("Pinned Child", true);
        let root = make_pad("Root", false);

        child.metadata.parent_id = Some(root.metadata.id);

        let indexed = index_pads(vec![root, child], vec![], vec![], OrderingKey::CreatedAt);

        // Root's children should have 2 entries for the pinned child
        assert_eq!(indexed[0].children.len(), 2);

        // One as Pinned(1)
        let pinned_child = indexed[0]
            .children
            .iter()
            .find(|c| matches!(c.index, DisplayIndex::Pinned(_)));
        assert!(pinned_child.is_some());
        assert_eq!(pinned_child.unwrap().index, DisplayIndex::Pinned(1));

        // One as Regular(1)
        let regular_child = indexed[0]
            .children
            .iter()
            .find(|c| matches!(c.index, DisplayIndex::Regular(_)));
        assert!(regular_child.is_some());
        assert_eq!(regular_child.unwrap().index, DisplayIndex::Regular(1));
    }

    #[test]
    fn test_tree_deep_nesting_four_levels() {
        // Create 4-level deep tree: L1 -> L2 -> L3 -> L4 (all active)
        let mut l4 = make_pad("Level 4", false);
        let mut l3 = make_pad("Level 3", false);
        let mut l2 = make_pad("Level 2", false);
        let l1 = make_pad("Level 1", false);

        l2.metadata.parent_id = Some(l1.metadata.id);
        l3.metadata.parent_id = Some(l2.metadata.id);
        l4.metadata.parent_id = Some(l3.metadata.id);

        let indexed = index_pads(vec![l1, l2, l3, l4], vec![], vec![], OrderingKey::CreatedAt);

        // Navigate to L4: indexed[0].children[0].children[0].children[0]
        assert_eq!(indexed[0].pad.metadata.title, "Level 1");
        assert_eq!(indexed[0].children[0].pad.metadata.title, "Level 2");
        assert_eq!(
            indexed[0].children[0].children[0].pad.metadata.title,
            "Level 3"
        );
        assert_eq!(
            indexed[0].children[0].children[0].children[0]
                .pad
                .metadata
                .title,
            "Level 4"
        );

        // Each level should have index Regular(1) within its parent
        assert_eq!(indexed[0].index, DisplayIndex::Regular(1));
        assert_eq!(indexed[0].children[0].index, DisplayIndex::Regular(1));
        assert_eq!(
            indexed[0].children[0].children[0].index,
            DisplayIndex::Regular(1)
        );
        assert_eq!(
            indexed[0].children[0].children[0].children[0].index,
            DisplayIndex::Regular(1)
        );
    }

    #[test]
    fn test_archived_pads_get_archived_index() {
        let p1 = make_pad("Active 1", false);
        let p2 = make_pad("Archived 1", false);
        let p3 = make_pad("Archived 2", false);

        let indexed = index_pads(vec![p1], vec![p2, p3], vec![], OrderingKey::CreatedAt);

        let archived_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Archived(_)))
            .collect();
        assert_eq!(archived_entries.len(), 2);

        let regular_entries: Vec<_> = indexed
            .iter()
            .filter(|dp| matches!(dp.index, DisplayIndex::Regular(_)))
            .collect();
        assert_eq!(regular_entries.len(), 1);
    }

    #[test]
    fn test_parse_uuid() {
        let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
        let uuid = Uuid::parse_str(uuid_str).unwrap();
        assert_eq!(parse_index_or_range(uuid_str), Ok(PadSelector::Uuid(uuid)));
    }

    #[test]
    fn test_parse_uuid_does_not_interfere_with_indexes() {
        // Regular indexes should still parse correctly
        assert_eq!(
            parse_index_or_range("1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Regular(1)]))
        );
        assert_eq!(
            parse_index_or_range("p1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Pinned(1)]))
        );
        assert_eq!(
            parse_index_or_range("d1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Deleted(1)]))
        );
        assert_eq!(
            parse_index_or_range("ar1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Archived(1)]))
        );
        // Ranges should still work
        assert_eq!(
            parse_index_or_range("1-3"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Regular(1)],
                vec![DisplayIndex::Regular(3)]
            ))
        );
        assert_eq!(
            parse_index_or_range("p1-p3"),
            Ok(PadSelector::Range(
                vec![DisplayIndex::Pinned(1)],
                vec![DisplayIndex::Pinned(3)]
            ))
        );
    }

    #[test]
    fn test_parse_uuid_display() {
        let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
        let uuid = Uuid::parse_str(uuid_str).unwrap();
        let selector = PadSelector::Uuid(uuid);
        assert_eq!(format!("{}", selector), uuid_str);
    }

    // ==================== Short UUID parsing tests ====================

    #[test]
    fn test_parse_short_uuid_hex_prefix() {
        // 8-char hex string (like --short-uuid output) should parse as ShortUuid
        assert_eq!(
            parse_index_or_range("766d5dab"),
            Ok(PadSelector::ShortUuid("766d5dab".to_string()))
        );
        assert_eq!(
            parse_index_or_range("4e704ff3"),
            Ok(PadSelector::ShortUuid("4e704ff3".to_string()))
        );
    }

    #[test]
    fn test_parse_short_uuid_various_lengths() {
        // Shorter hex prefixes
        assert_eq!(
            parse_index_or_range("abcd"),
            Ok(PadSelector::ShortUuid("abcd".to_string()))
        );
        // Longer hex prefix (but not a full UUID)
        assert_eq!(
            parse_index_or_range("550e8400e29b"),
            Ok(PadSelector::ShortUuid("550e8400e29b".to_string()))
        );
    }

    #[test]
    fn test_parse_short_uuid_case_insensitive() {
        // Upper-case hex should be normalized to lowercase
        assert_eq!(
            parse_index_or_range("ABCDEF01"),
            Ok(PadSelector::ShortUuid("abcdef01".to_string()))
        );
        assert_eq!(
            parse_index_or_range("AbCd"),
            Ok(PadSelector::ShortUuid("abcd".to_string()))
        );
    }

    #[test]
    fn test_di_takes_priority_over_short_uuid() {
        // "d3" is valid as Deleted(3) — DI wins
        assert_eq!(
            parse_index_or_range("d3"),
            Ok(PadSelector::Path(vec![DisplayIndex::Deleted(3)]))
        );
        // Pure numbers remain Regular DIs, not hex
        assert_eq!(
            parse_index_or_range("123"),
            Ok(PadSelector::Path(vec![DisplayIndex::Regular(123)]))
        );
        // "p1" is Pinned(1), not hex (p isn't hex anyway)
        assert_eq!(
            parse_index_or_range("p1"),
            Ok(PadSelector::Path(vec![DisplayIndex::Pinned(1)]))
        );
    }

    #[test]
    fn test_hex_with_non_di_chars_becomes_short_uuid() {
        // "d3f" can't be a DI (d + "3f" isn't a number), so falls to ShortUuid
        assert_eq!(
            parse_index_or_range("d3f"),
            Ok(PadSelector::ShortUuid("d3f".to_string()))
        );
        // "1a" isn't a valid DI either
        assert_eq!(
            parse_index_or_range("1a"),
            Ok(PadSelector::ShortUuid("1a".to_string()))
        );
    }

    #[test]
    fn test_non_hex_strings_still_error() {
        // Strings with non-hex characters should still fail
        assert!(parse_index_or_range("xyz").is_err());
        assert!(parse_index_or_range("meeting").is_err());
        assert!(parse_index_or_range("hello").is_err());
    }

    #[test]
    fn test_short_uuid_display() {
        let selector = PadSelector::ShortUuid("766d5dab".to_string());
        assert_eq!(format!("{}", selector), "766d5dab");
    }

    #[test]
    fn test_all_three_buckets() {
        let active = make_pad("Active", false);
        let archived = make_pad("Archived", false);
        let deleted = make_pad("Deleted", false);

        let indexed = index_pads(
            vec![active],
            vec![archived],
            vec![deleted],
            OrderingKey::CreatedAt,
        );

        assert_eq!(indexed.len(), 3);

        assert!(indexed
            .iter()
            .any(|dp| matches!(dp.index, DisplayIndex::Regular(_))));
        assert!(indexed
            .iter()
            .any(|dp| matches!(dp.index, DisplayIndex::Archived(_))));
        assert!(indexed
            .iter()
            .any(|dp| matches!(dp.index, DisplayIndex::Deleted(_))));
    }

    // ==================== Ordering key tests ====================

    /// Build a pad with explicit created_at/updated_at for ordering tests.
    fn pad_with_times(
        title: &str,
        created_at: chrono::DateTime<chrono::Utc>,
        updated_at: chrono::DateTime<chrono::Utc>,
    ) -> Pad {
        let mut p = make_pad(title, false);
        p.metadata.created_at = created_at;
        p.metadata.updated_at = updated_at;
        p
    }

    #[test]
    fn test_ordering_created_at_uses_creation_time() {
        use chrono::TimeZone;
        let t1 = chrono::Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let t2 = chrono::Utc.with_ymd_and_hms(2024, 1, 2, 0, 0, 0).unwrap();
        let t3 = chrono::Utc.with_ymd_and_hms(2024, 1, 3, 0, 0, 0).unwrap();
        // A was created first, B second, C third. But A was modified most recently.
        let a = pad_with_times("A", t1, t3);
        let b = pad_with_times("B", t2, t2);
        let c = pad_with_times("C", t3, t1);

        let indexed = index_pads(vec![a, b, c], vec![], vec![], OrderingKey::CreatedAt);
        let regulars: Vec<&str> = indexed
            .iter()
            .filter_map(|dp| match dp.index {
                DisplayIndex::Regular(_) => Some(dp.pad.metadata.title.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(regulars, vec!["C", "B", "A"]);
    }

    #[test]
    fn test_ordering_updated_at_uses_modification_time() {
        use chrono::TimeZone;
        let t1 = chrono::Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let t2 = chrono::Utc.with_ymd_and_hms(2024, 1, 2, 0, 0, 0).unwrap();
        let t3 = chrono::Utc.with_ymd_and_hms(2024, 1, 3, 0, 0, 0).unwrap();
        // Same setup as above: A created first but modified last.
        let a = pad_with_times("A", t1, t3);
        let b = pad_with_times("B", t2, t2);
        let c = pad_with_times("C", t3, t1);

        let indexed = index_pads(vec![a, b, c], vec![], vec![], OrderingKey::UpdatedAt);
        let regulars: Vec<&str> = indexed
            .iter()
            .filter_map(|dp| match dp.index {
                DisplayIndex::Regular(_) => Some(dp.pad.metadata.title.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(regulars, vec!["A", "B", "C"]);
    }

    #[test]
    fn test_ordering_updated_at_surfaces_parent_via_descendant_edit() {
        // Setup: two roots. RootA has an old updated_at but a child that's recent.
        // RootB has a more recent updated_at than RootA itself, but older than A's child.
        // Under UpdatedAt ordering, RootA should still lead because its subtree max
        // (the child's updated_at) wins — without ever mutating RootA's stored updated_at.
        use chrono::TimeZone;
        let t_old = chrono::Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let t_mid = chrono::Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap();
        let t_new = chrono::Utc.with_ymd_and_hms(2024, 1, 10, 0, 0, 0).unwrap();

        let mut root_a = make_pad("Root A", false);
        root_a.metadata.created_at = t_old;
        root_a.metadata.updated_at = t_old;

        let mut child_of_a = make_pad("Child of A", false);
        child_of_a.metadata.created_at = t_old;
        child_of_a.metadata.updated_at = t_new; // most recent overall
        child_of_a.metadata.parent_id = Some(root_a.metadata.id);

        let mut root_b = make_pad("Root B", false);
        root_b.metadata.created_at = t_mid;
        root_b.metadata.updated_at = t_mid;

        let indexed = index_pads(
            vec![root_a.clone(), child_of_a, root_b],
            vec![],
            vec![],
            OrderingKey::UpdatedAt,
        );

        let regulars: Vec<&str> = indexed
            .iter()
            .filter_map(|dp| match dp.index {
                DisplayIndex::Regular(_) => Some(dp.pad.metadata.title.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            regulars,
            vec!["Root A", "Root B"],
            "Root A should lead because its subtree max wins, even though its own updated_at is older than Root B's"
        );

        // And critically: Root A's stored updated_at must not have been mutated.
        let root_a_in_results = indexed
            .iter()
            .find(|dp| dp.pad.metadata.title == "Root A")
            .unwrap();
        assert_eq!(
            root_a_in_results.pad.metadata.updated_at, t_old,
            "stored updated_at must remain the pad's own content mtime"
        );
    }

    #[test]
    fn test_ordering_tie_break_is_deterministic() {
        // Two pads with identical timestamps must always sort the same way.
        // We use UUID-based tie-breaking, so the pad with the lexicographically
        // smaller UUID wins regardless of input order.
        use chrono::TimeZone;
        let t = chrono::Utc.with_ymd_and_hms(2024, 6, 1, 0, 0, 0).unwrap();
        let id_low = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
        let id_hi = Uuid::parse_str("ffffffff-ffff-ffff-ffff-fffffffffffe").unwrap();

        let mut pad_low = Pad::new("Low".to_string(), "".to_string());
        pad_low.metadata.id = id_low;
        pad_low.metadata.created_at = t;
        pad_low.metadata.updated_at = t;

        let mut pad_hi = Pad::new("Hi".to_string(), "".to_string());
        pad_hi.metadata.id = id_hi;
        pad_hi.metadata.created_at = t;
        pad_hi.metadata.updated_at = t;

        // Try both input orders — output should be stable.
        for order in [
            vec![pad_low.clone(), pad_hi.clone()],
            vec![pad_hi.clone(), pad_low.clone()],
        ] {
            let indexed = index_pads(order, vec![], vec![], OrderingKey::CreatedAt);
            let titles: Vec<&str> = indexed
                .iter()
                .filter_map(|dp| match dp.index {
                    DisplayIndex::Regular(_) => Some(dp.pad.metadata.title.as_str()),
                    _ => None,
                })
                .collect();
            assert_eq!(
                titles,
                vec!["Low", "Hi"],
                "tie-break should be deterministic"
            );
        }
    }

    #[test]
    fn test_ordering_applies_recursively_to_children() {
        use chrono::TimeZone;
        let t1 = chrono::Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let t2 = chrono::Utc.with_ymd_and_hms(2024, 1, 2, 0, 0, 0).unwrap();
        let t3 = chrono::Utc.with_ymd_and_hms(2024, 1, 3, 0, 0, 0).unwrap();

        let parent = pad_with_times("Parent", t1, t1);
        let mut c_oldest_update = pad_with_times("Child A", t3, t1);
        let mut c_middle_update = pad_with_times("Child B", t2, t2);
        let mut c_newest_update = pad_with_times("Child C", t1, t3);
        c_oldest_update.metadata.parent_id = Some(parent.metadata.id);
        c_middle_update.metadata.parent_id = Some(parent.metadata.id);
        c_newest_update.metadata.parent_id = Some(parent.metadata.id);

        let indexed = index_pads(
            vec![parent, c_oldest_update, c_middle_update, c_newest_update],
            vec![],
            vec![],
            OrderingKey::UpdatedAt,
        );

        let children: Vec<&str> = indexed[0]
            .children
            .iter()
            .filter_map(|dp| match dp.index {
                DisplayIndex::Regular(_) => Some(dp.pad.metadata.title.as_str()),
                _ => None,
            })
            .collect();
        // Child C has newest updated_at, then B, then A.
        assert_eq!(children, vec!["Child C", "Child B", "Child A"]);
    }
}