faculties 0.11.2

An office suite for AI agents: kanban, wiki, files, messaging, and a GORBIE-backed viewer — all persisted in a TribleSpace pile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
//! Full-featured GORBIE-embeddable compass (kanban) board widget.
//!
//! Renders goals from a triblespace pile's `compass` branch grouped into
//! kanban columns by their latest status (default: todo / doing / blocked
//! / done). The widget holds only UI + cached-query state; the host is
//! responsible for pulling the compass branch and passing the workspace
//! in at render time. Writes go through `Workspace::commit(..)`; pushing
//! is the host's responsibility (e.g. via
//! [`StorageState::push`](crate::widgets::StorageState::push)).
//!
//! Features beyond read-only display:
//!
//! - Composing new goals (title, tags, optional parent, initial status)
//! - Moving a goal to a new status (click a goal card → pick a status)
//! - Adding notes to an expanded goal
//! - Parent/child indentation with a collapse toggle per subtree
//! - Priority arrows: `board::higher` / `board::lower` edges rendered as
//!   `> over <id_prefix>` badges on the card
//! - Tag chips colored via `GORBIE::themes::colorhash::ral_categorical`.
//!
//! ```ignore
//! let mut board = CompassBoard::default();
//! // Inside a GORBIE card, with `compass_ws`:
//! board.render(ctx, compass_ws);
//! ```

use std::collections::{BTreeMap, HashMap, HashSet};

use GORBIE::prelude::CardCtx;
use GORBIE::themes::colorhash;
use triblespace::core::id::{ufoid, ExclusiveId, Id};
use triblespace::core::metadata;
use triblespace::core::repo::pile::Pile;
use triblespace::core::repo::{CommitHandle, Workspace};
use triblespace::core::trible::TribleSet;
use triblespace::core::value::schemas::hash::{Blake3, Handle};
use triblespace::core::value::{TryToValue, Value};
use triblespace::macros::{entity, find, pattern};
use triblespace::prelude::blobschemas::LongString;
use triblespace::prelude::valueschemas::NsTAIInterval;
use triblespace::prelude::View;

use crate::schemas::compass::{
    board as compass, DEFAULT_STATUSES, KIND_GOAL_ID, KIND_NOTE_ID, KIND_PRIORITIZE_ID,
    KIND_STATUS_ID,
};

/// Handle to a long-string blob (titles, notes).
type TextHandle = Value<Handle<Blake3, LongString>>;
/// Interval value (TAI ns lower/upper) used for `metadata::created_at`.
type IntervalValue = Value<NsTAIInterval>;

// ── ID / time helpers ────────────────────────────────────────────────

fn fmt_id_full(id: Id) -> String {
    format!("{id:x}")
}

fn id_prefix(id: Id) -> String {
    let s = fmt_id_full(id);
    if s.len() > 8 {
        s[..8].to_string()
    } else {
        s
    }
}

fn now_tai_ns() -> i128 {
    hifitime::Epoch::now()
        .map(|e| e.to_tai_duration().total_nanoseconds())
        .unwrap_or(0)
}

fn now_epoch() -> hifitime::Epoch {
    hifitime::Epoch::now().unwrap_or_else(|_| hifitime::Epoch::from_gregorian_utc(1970, 1, 1, 0, 0, 0, 0))
}

fn epoch_interval(epoch: hifitime::Epoch) -> IntervalValue {
    (epoch, epoch).try_to_value().unwrap()
}

fn format_age(now_key: i128, maybe_key: Option<i128>) -> String {
    let Some(key) = maybe_key else {
        return "-".to_string();
    };
    let delta_ns = now_key.saturating_sub(key);
    let delta_s = (delta_ns / 1_000_000_000).max(0) as i64;
    if delta_s < 60 {
        format!("{delta_s}s")
    } else if delta_s < 60 * 60 {
        format!("{}m", delta_s / 60)
    } else if delta_s < 24 * 60 * 60 {
        format!("{}h", delta_s / 3600)
    } else {
        format!("{}d", delta_s / 86_400)
    }
}

// ── Color palette (RAL-inspired, matches playground diagnostics) ────

fn color_todo() -> egui::Color32 {
    egui::Color32::from_rgb(0x57, 0xa6, 0x39) // RAL 6018
}
fn color_doing() -> egui::Color32 {
    egui::Color32::from_rgb(0xf7, 0xba, 0x0b) // RAL 1003
}
fn color_blocked() -> egui::Color32 {
    egui::Color32::from_rgb(0xcc, 0x0a, 0x17) // RAL 3020
}
fn color_done() -> egui::Color32 {
    egui::Color32::from_rgb(0x15, 0x4e, 0xa1) // RAL 5005
}
// Theme-adaptive neutrals. The status colors (todo/doing/blocked/
// done) are legible on both light and dark backgrounds, but the
// frame / card / muted colors need to flip with the theme — hard-
// coded dark shades turned into "dark on dark" (body text uses
// egui's theme-aware color, which is dark in light mode).

/// Muted mid-grey for secondary labels, borders, and separators.
fn color_muted(ui: &egui::Ui) -> egui::Color32 {
    if ui.visuals().dark_mode {
        egui::Color32::from_rgb(0x9a, 0x9a, 0x9a)
    } else {
        egui::Color32::from_rgb(0x6a, 0x6a, 0x6a)
    }
}

/// Lane / container background — slightly offset from the notebook
/// panel fill so the lane reads as a distinct region.
fn color_frame(ui: &egui::Ui) -> egui::Color32 {
    if ui.visuals().dark_mode {
        egui::Color32::from_rgb(0x29, 0x32, 0x36) // RAL 7016 (dark)
    } else {
        egui::Color32::from_rgb(0xec, 0xec, 0xec) // near-white grey
    }
}

/// Goal-card background — slightly lighter/darker than the lane so
/// cards pop out of the lane backdrop.
fn card_bg(ui: &egui::Ui) -> egui::Color32 {
    if ui.visuals().dark_mode {
        egui::Color32::from_rgb(0x33, 0x3b, 0x40)
    } else {
        egui::Color32::from_rgb(0xfa, 0xfa, 0xfa)
    }
}

fn status_color(status: &str) -> egui::Color32 {
    match status {
        "todo" => color_todo(),
        "doing" => color_doing(),
        "blocked" => color_blocked(),
        "done" => color_done(),
        // Mid-grey fallback — legible on both light and dark panels
        // without needing a `&Ui` argument.
        _ => egui::Color32::from_rgb(0x80, 0x80, 0x80),
    }
}

/// Deterministic color for a tag string via GORBIE's colorhash palette.
fn tag_color(tag: &str) -> egui::Color32 {
    colorhash::ral_categorical(tag.as_bytes())
}

/// Truncate `s` at char boundary to `max` chars, appending `…` if cut.
/// Char-aware so multibyte sequences don't panic on slice.
fn truncate_inline(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let take: String = s.chars().take(max.saturating_sub(1)).collect();
    format!("{take}")
}

// ── Row structs ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
struct GoalRow {
    id: Id,
    id_prefix: String,
    title: String,
    tags: Vec<String>,
    status: String,
    /// TAI ns of the latest status assignment (sort key within a column).
    status_at: Option<i128>,
    /// TAI ns of the goal's own creation (fallback sort key).
    created_at: Option<i128>,
    note_count: usize,
    parent: Option<Id>,
    /// Goals this one is prioritized over (`board::higher=self, board::lower=x`).
    higher_over: Vec<Id>,
}

impl GoalRow {
    fn sort_key(&self) -> i128 {
        self.status_at.or(self.created_at).unwrap_or(i128::MIN)
    }
}

#[derive(Clone, Debug)]
struct NoteRow {
    at: Option<i128>,
    body: String,
}

// ── Cached compass query state ───────────────────────────────────────

/// Holds a cached fact space for the compass branch plus a head marker.
/// Queries run against `space`; writes take a `&mut Workspace<Pile>` from
/// the host and call `ws.commit(..)`. Push is the host's concern.
struct CompassLive {
    space: TribleSet,
    cached_head: Option<CommitHandle>,
}

impl CompassLive {
    fn refresh(ws: &mut Workspace<Pile<Blake3>>) -> Self {
        let space = ws
            .checkout(..)
            .map(|co| co.into_facts())
            .unwrap_or_else(|e| {
                eprintln!("[compass] checkout: {e:?}");
                TribleSet::new()
            });
        Self {
            space,
            cached_head: ws.head(),
        }
    }

    fn text(&self, ws: &mut Workspace<Pile<Blake3>>, h: TextHandle) -> String {
        ws.get::<View<str>, LongString>(h)
            .map(|v| {
                let s: &str = v.as_ref();
                s.to_string()
            })
            .unwrap_or_default()
    }

    /// Collect every goal with derived current status, tags, note count,
    /// parent, and outgoing priority edges (higher_over).
    fn goals(&self, ws: &mut Workspace<Pile<Blake3>>) -> Vec<GoalRow> {
        let mut by_id: HashMap<Id, GoalRow> = HashMap::new();

        // Title + created_at.
        let title_rows: Vec<(Id, TextHandle, (i128, i128))> = find!(
            (gid: Id, title: TextHandle, ts: (i128, i128)),
            pattern!(&self.space, [{
                ?gid @
                metadata::tag: &KIND_GOAL_ID,
                compass::title: ?title,
                metadata::created_at: ?ts,
            }])
        )
        .collect();

        for (gid, title_handle, ts) in title_rows {
            if by_id.contains_key(&gid) {
                continue;
            }
            let title = self.text(ws, title_handle);
            by_id.insert(
                gid,
                GoalRow {
                    id: gid,
                    id_prefix: id_prefix(gid),
                    title,
                    tags: Vec::new(),
                    status: "todo".to_string(),
                    status_at: None,
                    created_at: Some(ts.0),
                    note_count: 0,
                    parent: None,
                    higher_over: Vec::new(),
                },
            );
        }

        // Tags.
        for (gid, tag) in find!(
            (gid: Id, tag: String),
            pattern!(&self.space, [{
                ?gid @
                metadata::tag: &KIND_GOAL_ID,
                compass::tag: ?tag,
            }])
        ) {
            if let Some(row) = by_id.get_mut(&gid) {
                row.tags.push(tag);
            }
        }

        // Parents.
        for (gid, parent) in find!(
            (gid: Id, parent: Id),
            pattern!(&self.space, [{
                ?gid @
                metadata::tag: &KIND_GOAL_ID,
                compass::parent: ?parent,
            }])
        ) {
            if let Some(row) = by_id.get_mut(&gid) {
                row.parent = Some(parent);
            }
        }

        // Latest status per goal.
        for (gid, status, ts) in find!(
            (gid: Id, status: String, ts: (i128, i128)),
            pattern!(&self.space, [{
                _?event @
                metadata::tag: &KIND_STATUS_ID,
                compass::task: ?gid,
                compass::status: ?status,
                metadata::created_at: ?ts,
            }])
        ) {
            if let Some(row) = by_id.get_mut(&gid) {
                let replace = match row.status_at {
                    None => true,
                    Some(prev) => ts.0 > prev,
                };
                if replace {
                    row.status = status;
                    row.status_at = Some(ts.0);
                }
            }
        }

        // Note counts.
        for gid in find!(
            gid: Id,
            pattern!(&self.space, [{
                _?event @
                metadata::tag: &KIND_NOTE_ID,
                compass::task: ?gid,
            }])
        ) {
            if let Some(row) = by_id.get_mut(&gid) {
                row.note_count += 1;
            }
        }

        // Priority edges: higher > lower. We don't track deprioritize
        // events in the widget — the faculty CLI remains the canonical
        // way to remove relationships — so this is a best-effort view.
        for (higher, lower) in find!(
            (higher: Id, lower: Id),
            pattern!(&self.space, [{
                _?event @
                metadata::tag: &KIND_PRIORITIZE_ID,
                compass::higher: ?higher,
                compass::lower: ?lower,
            }])
        ) {
            if let Some(row) = by_id.get_mut(&higher) {
                if !row.higher_over.contains(&lower) {
                    row.higher_over.push(lower);
                }
            }
        }

        for row in by_id.values_mut() {
            row.tags.sort();
            row.tags.dedup();
        }

        by_id.into_values().collect()
    }

    /// Notes on a specific goal, sorted newest-first.
    fn notes_for(&self, ws: &mut Workspace<Pile<Blake3>>, goal_id: Id) -> Vec<NoteRow> {
        let raw: Vec<(TextHandle, (i128, i128))> = find!(
            (note_handle: TextHandle, ts: (i128, i128)),
            pattern!(&self.space, [{
                _?event @
                metadata::tag: &KIND_NOTE_ID,
                compass::task: &goal_id,
                compass::note: ?note_handle,
                metadata::created_at: ?ts,
            }])
        )
        .collect();

        let mut notes: Vec<NoteRow> = raw
            .into_iter()
            .map(|(h, ts)| NoteRow {
                at: Some(ts.0),
                body: self.text(ws, h),
            })
            .collect();
        notes.sort_by(|a, b| b.at.cmp(&a.at));
        notes
    }

    // ── Write operations (mirror faculty CLI fact shapes) ─────────────
    // The host pushes the workspace after render; see StorageState.

    fn add_goal(
        ws: &mut Workspace<Pile<Blake3>>,
        title: String,
        status: String,
        parent: Option<Id>,
        tags: Vec<String>,
    ) -> Id {
        let task_id: ExclusiveId = ufoid();
        let task_ref: Id = task_id.id;
        let now = epoch_interval(now_epoch());
        let title_handle = ws.put::<LongString, _>(title);

        let mut change = TribleSet::new();
        change += entity! { &task_id @
            metadata::tag: &KIND_GOAL_ID,
            compass::title: title_handle,
            metadata::created_at: now,
            compass::parent?: parent.as_ref(),
            compass::tag*: tags.iter().map(|t| t.as_str()),
        };
        let status_id: ExclusiveId = ufoid();
        change += entity! { &status_id @
            metadata::tag: &KIND_STATUS_ID,
            compass::task: &task_ref,
            compass::status: status.as_str(),
            metadata::created_at: now,
        };

        ws.commit(change, "add goal");
        task_ref
    }

    fn move_status(ws: &mut Workspace<Pile<Blake3>>, task_id: Id, status: String) {
        let now = epoch_interval(now_epoch());
        let status_id: ExclusiveId = ufoid();
        let mut change = TribleSet::new();
        change += entity! { &status_id @
            metadata::tag: &KIND_STATUS_ID,
            compass::task: &task_id,
            compass::status: status.as_str(),
            metadata::created_at: now,
        };
        ws.commit(change, "move goal");
    }

    fn add_note(ws: &mut Workspace<Pile<Blake3>>, task_id: Id, body: String) {
        let now = epoch_interval(now_epoch());
        let note_id: ExclusiveId = ufoid();
        let body_handle = ws.put::<LongString, _>(body);
        let mut change = TribleSet::new();
        change += entity! { &note_id @
            metadata::tag: &KIND_NOTE_ID,
            compass::task: &task_id,
            compass::note: body_handle,
            metadata::created_at: now,
        };
        ws.commit(change, "add goal note");
    }
}

// ── Tree layout ──────────────────────────────────────────────────────

/// Depth-first walk through parent/child forest, yielding (row, depth).
/// Rows that have a parent outside this subset are treated as roots.
fn order_rows(rows: Vec<GoalRow>) -> Vec<(GoalRow, usize)> {
    let mut by_id: HashMap<Id, GoalRow> = HashMap::new();
    for row in rows {
        by_id.insert(row.id, row);
    }
    let ids: HashSet<Id> = by_id.keys().copied().collect();
    let mut children: HashMap<Id, Vec<Id>> = HashMap::new();
    let mut roots = Vec::new();

    for (id, row) in &by_id {
        if let Some(parent) = row.parent {
            if ids.contains(&parent) {
                children.entry(parent).or_default().push(*id);
                continue;
            }
        }
        roots.push(*id);
    }

    let sort_ids = |items: &mut Vec<Id>, by_id: &HashMap<Id, GoalRow>| {
        items.sort_by(|a, b| {
            let a_row = by_id.get(a);
            let b_row = by_id.get(b);
            let a_key = a_row.map(|r| r.sort_key()).unwrap_or(i128::MIN);
            let b_key = b_row.map(|r| r.sort_key()).unwrap_or(i128::MIN);
            b_key
                .cmp(&a_key)
                .then_with(|| {
                    let at = a_row.map(|r| r.title.as_str()).unwrap_or("");
                    let bt = b_row.map(|r| r.title.as_str()).unwrap_or("");
                    at.to_lowercase().cmp(&bt.to_lowercase())
                })
                .then_with(|| a.cmp(b))
        });
    };

    sort_ids(&mut roots, &by_id);
    for kids in children.values_mut() {
        sort_ids(kids, &by_id);
    }

    let mut ordered = Vec::new();
    let mut visited = HashSet::new();

    fn walk(
        id: Id,
        depth: usize,
        by_id: &HashMap<Id, GoalRow>,
        children: &HashMap<Id, Vec<Id>>,
        visited: &mut HashSet<Id>,
        out: &mut Vec<(GoalRow, usize)>,
    ) {
        if !visited.insert(id) {
            return;
        }
        let Some(row) = by_id.get(&id) else {
            return;
        };
        out.push((row.clone(), depth));
        if let Some(kids) = children.get(&id) {
            for kid in kids {
                walk(*kid, depth + 1, by_id, children, visited, out);
            }
        }
    }

    for root in roots {
        walk(root, 0, &by_id, &children, &mut visited, &mut ordered);
    }
    // Any unvisited (e.g. parent-cycle) nodes get a depth-0 fallback.
    let leftovers: Vec<Id> = by_id.keys().copied().filter(|id| !visited.contains(id)).collect();
    for id in leftovers {
        walk(id, 0, &by_id, &children, &mut visited, &mut ordered);
    }
    ordered
}

// ── Compose form state ───────────────────────────────────────────────

/// Inline "+ Add" form bound to a specific column (status).
#[derive(Default)]
struct ComposeForm {
    open: bool,
    title: String,
    tags: String,
    /// Hex-prefix for a parent goal; resolved against `goals` when
    /// submitting (ambiguous or unknown = none).
    parent_prefix: String,
}

// ── Widget ───────────────────────────────────────────────────────────

/// GORBIE-embeddable kanban-style compass board.
///
/// Full-featured: supports composing goals, moving status, adding notes,
/// parent/child nesting with per-subtree collapse, priority arrow badges,
/// and colorhashed tag chips. See the module docs for details.
///
/// ```ignore
/// let mut board = CompassBoard::default();
/// // Inside a GORBIE card, with `compass_ws`:
/// board.render(ctx, compass_ws);
/// ```
pub struct CompassBoard {
    /// Rebuilt when the workspace's head advances.
    live: Option<CompassLive>,
    expanded_goal: Option<Id>,
    /// Goals whose children should be hidden (parent-node collapsed).
    collapsed: HashSet<Id>,
    compose: HashMap<String, ComposeForm>,
    /// Per-goal inline note-input buffer.
    note_inputs: HashMap<Id, String>,
    /// Goal whose status-move menu is currently open.
    status_menu: Option<Id>,
    column_height: f32,
}

impl Default for CompassBoard {
    fn default() -> Self {
        Self {
            live: None,
            expanded_goal: None,
            collapsed: HashSet::new(),
            compose: HashMap::new(),
            note_inputs: HashMap::new(),
            status_menu: None,
            column_height: 500.0,
        }
    }
}

impl CompassBoard {
    /// Build a board with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the per-column scroll-area height (pixels). Default 500.
    pub fn with_column_height(mut self, height: f32) -> Self {
        self.column_height = height.max(120.0);
        self
    }

    /// Render the board into a GORBIE card context. `ws` must point at
    /// the compass branch.
    pub fn render(&mut self, ctx: &mut CardCtx<'_>, ws: &mut Workspace<Pile<Blake3>>) {
        // Refresh cached state if the workspace head has advanced.
        let head = ws.head();
        let need_refresh = match self.live.as_ref() {
            None => true,
            Some(l) => l.cached_head != head,
        };
        if need_refresh {
            self.live = Some(CompassLive::refresh(ws));
        }
        let live = self.live.as_ref().expect("refreshed above");

        let mut goals = live.goals(ws);
        // Global sort used when a goal has no parent context.
        goals.sort_by(|a, b| {
            b.sort_key()
                .cmp(&a.sort_key())
                .then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
                .then_with(|| a.id.cmp(&b.id))
        });

        // Fill tree-ordered (row, depth) vectors per-status.
        let mut by_status: BTreeMap<String, Vec<GoalRow>> = BTreeMap::new();
        for g in goals.clone() {
            by_status.entry(g.status.clone()).or_default().push(g);
        }

        let mut columns: Vec<String> = DEFAULT_STATUSES.iter().map(|s| s.to_string()).collect();
        let mut extras: Vec<String> = by_status
            .keys()
            .filter(|s| !DEFAULT_STATUSES.contains(&s.as_str()))
            .cloned()
            .collect();
        extras.sort();
        columns.extend(extras);

        // Pre-compute a global id→title lookup (used for "> over <prefix>"
        // badges when the target isn't in the same column).
        let title_by_id: HashMap<Id, String> = goals
            .iter()
            .map(|g| (g.id, g.title.clone()))
            .collect();

        // Per-column tree-ordered rows.
        let column_data: Vec<(String, Vec<(GoalRow, usize)>)> = columns
            .into_iter()
            .map(|s| {
                let rows = by_status.remove(&s).unwrap_or_default();
                let ordered = order_rows(rows);
                (s, ordered)
            })
            .collect();

        // Resolve expanded goal's notes (if any).
        let expanded = self.expanded_goal;
        let expanded_notes: Option<(Id, Vec<NoteRow>)> = expanded.map(|gid| {
            let notes = live.notes_for(ws, gid);
            (gid, notes)
        });

        // Pull scalars out of `self` before the closure so we don't end up
        // with conflicting borrows.
        let column_height = self.column_height;
        let total_goals: usize = column_data.iter().map(|(_, r)| r.len()).sum();

        // Write intents collected during render (applied after the UI closure
        // so we don't re-enter `self` while holding egui state).
        let mut add_intent: Option<AddIntent> = None;
        let mut move_intent: Option<(Id, String)> = None;
        let mut note_intent: Option<(Id, String)> = None;

        // Mutable handles to self state we need inside the closure.
        let expanded_goal = &mut self.expanded_goal;
        let collapsed = &mut self.collapsed;
        let compose = &mut self.compose;
        let note_inputs = &mut self.note_inputs;
        let status_menu = &mut self.status_menu;

        ctx.section("Compass", |ctx| {
            // Header: total + per-status breakdown as small colored
            // chips. Same statuses appear as column headers below, so
            // the summary is a mini-legend too.
            let ui = ctx.ui_mut();
            ui.horizontal_wrapped(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                ui.label(
                    egui::RichText::new(format!("{total_goals} GOALS"))
                        .monospace()
                        .strong()
                        .small()
                        .color(color_muted(ui)),
                );
                ui.label(
                    egui::RichText::new("\u{00b7}")
                        .small()
                        .color(color_muted(ui)),
                );
                for (status, rows) in &column_data {
                    if rows.is_empty() {
                        continue;
                    }
                    let (dot, _) = ui.allocate_exact_size(
                        egui::vec2(8.0, 8.0),
                        egui::Sense::hover(),
                    );
                    ui.painter().circle_filled(
                        dot.center(),
                        3.5,
                        status_color(status),
                    );
                    ui.label(
                        egui::RichText::new(status.to_uppercase())
                            .monospace()
                            .strong()
                            .small(),
                    );
                    ui.label(
                        egui::RichText::new(rows.len().to_string())
                            .monospace()
                            .small()
                            .color(color_muted(ui)),
                    );
                }
            });

            if total_goals == 0 && column_data.iter().all(|(s, _)| !compose.contains_key(s)) {
                render_empty_state(
                    ctx.ui_mut(),
                    "\u{1f9ed}",
                    "No goals yet",
                    Some("Click + ADD in a column below to start tracking work."),
                );
            }

            // Vertically-stacked swim lanes: each status gets a full-
            // width lane, stacked top-to-bottom. Replaces the earlier
            // side-by-side kanban columns — lets card titles/tags
            // breathe on wide screens and uses the notebook's
            // natural vertical scroll instead of a nested horizontal
            // scroller.
            const LANE_GAP: f32 = 10.0;
            let ui = ctx.ui_mut();
            // Card-rect collection for the priority-edge overlay.
            let mut card_rects: HashMap<Id, egui::Rect> = HashMap::new();
            let lane_width = ui.available_width();
            ui.vertical(|ui| {
                ui.spacing_mut().item_spacing.y = LANE_GAP;
                for (status, rows) in &column_data {
                    let form = compose.entry(status.clone()).or_default();
                    render_column(
                        ui,
                        status,
                        rows,
                        lane_width,
                        column_height,
                        expanded_goal,
                        expanded_notes.as_ref(),
                        collapsed,
                        note_inputs,
                        status_menu,
                        form,
                        &title_by_id,
                        &mut card_rects,
                        &mut add_intent,
                        &mut move_intent,
                        &mut note_intent,
                    );
                }
            });

            // Priority-edge overlay — same tinting as before, but
            // now edges typically run top-to-bottom between lanes
            // instead of across the horizontal kanban.
            let painter = ui.painter();
            for row in column_data.iter().flat_map(|(_, rs)| rs) {
                let (src_row, _depth) = row;
                let Some(from_rect) = card_rects.get(&src_row.id) else {
                    continue;
                };
                let base = status_color(&src_row.status);
                let edge_color = egui::Color32::from_rgba_unmultiplied(
                    base.r(),
                    base.g(),
                    base.b(),
                    200,
                );
                for lower in &src_row.higher_over {
                    let Some(to_rect) = card_rects.get(lower) else {
                        continue;
                    };
                    draw_priority_edge(painter, *from_rect, *to_rect, edge_color);
                }
            }
        });

        // Apply writes after the UI closure. Each helper does a
        // `ws.commit(..)`; the host pushes between frames via
        // `StorageState::push` when the workspace head advanced.
        if let Some(intent) = add_intent {
            let status = intent.status.clone();
            let _ = CompassLive::add_goal(ws, intent.title, status.clone(), intent.parent, intent.tags);
            if let Some(form) = self.compose.get_mut(&status) {
                form.open = false;
                form.title.clear();
                form.tags.clear();
                form.parent_prefix.clear();
            }
            // Drop cached state so the next frame re-queries off the new head.
            self.live = None;
        }
        if let Some((id, status)) = move_intent {
            CompassLive::move_status(ws, id, status);
            self.status_menu = None;
            self.live = None;
        }
        if let Some((id, body)) = note_intent {
            let body_trimmed = body.trim();
            if !body_trimmed.is_empty() {
                CompassLive::add_note(ws, id, body_trimmed.to_string());
                if let Some(buf) = self.note_inputs.get_mut(&id) {
                    buf.clear();
                }
                self.live = None;
            }
        }
    }
}

// ── Write intents ────────────────────────────────────────────────────

struct AddIntent {
    title: String,
    status: String,
    parent: Option<Id>,
    tags: Vec<String>,
}

// ── Column rendering ─────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn render_column(
    ui: &mut egui::Ui,
    status: &str,
    rows: &[(GoalRow, usize)],
    width: f32,
    height: f32,
    expanded_goal: &mut Option<Id>,
    expanded_notes: Option<&(Id, Vec<NoteRow>)>,
    collapsed: &mut HashSet<Id>,
    note_inputs: &mut HashMap<Id, String>,
    status_menu: &mut Option<Id>,
    form: &mut ComposeForm,
    title_by_id: &HashMap<Id, String>,
    card_rects: &mut HashMap<Id, egui::Rect>,
    add_intent: &mut Option<AddIntent>,
    move_intent: &mut Option<(Id, String)>,
    note_intent: &mut Option<(Id, String)>,
) {
    let status_col = status_color(status);
    let frame_response = egui::Frame::NONE
        .fill(color_frame(ui))
        .corner_radius(egui::CornerRadius::same(6))
        .inner_margin(egui::Margin {
            left: 12,  // extra left padding for the accent stripe
            right: 8,
            top: 8,
            bottom: 8,
        })
        .show(ui, |ui| {
            // Claim the full available inside-Frame width. Using the
            // outer `width` here would exceed `available_width()` by
            // the Frame's inner_margin (left+right = 20 px) — which
            // pushed the lane that much past the notebook column and
            // caused the "stuff overflows" impression on every
            // relayout. `available_width()` respects the margin.
            let _ = width; // kept in the signature for the caller's math
            ui.set_width(ui.available_width());
            ui.set_min_height(height);
            ui.vertical(|ui| {

            // Column header: STATUS label + count chip on the left,
            // +ADD / × toggle on the right. Count sits in a muted
            // playbook-style chip instead of "(N)" parentheses so the
            // status name stays prominent and the count reads as a
            // metadata badge.
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                ui.label(
                    egui::RichText::new(status.to_uppercase())
                        .monospace()
                        .strong()
                        .color(status_col),
                );
                render_chip(ui, &rows.len().to_string(), color_muted(ui));
                ui.with_layout(
                    egui::Layout::right_to_left(egui::Align::Center),
                    |ui| {
                        let (label, hint) = if form.open {
                            ("×", "Close compose form")
                        } else {
                            ("+ ADD", "New goal in this column")
                        };
                        if ui
                            .add(
                                egui::Button::new(
                                    egui::RichText::new(label)
                                        .small()
                                        .monospace()
                                        .strong(),
                                ),
                            )
                            .on_hover_text(hint)
                            .clicked()
                        {
                            form.open = !form.open;
                        }
                    },
                );
            });
            ui.add_space(4.0);

            // Inline compose form.
            if form.open {
                render_compose_form(ui, status, form, add_intent);
                ui.add_space(6.0);
            }

            // Collect set of visible IDs for filtering children of collapsed parents.
            let ancestors_collapsed: HashSet<Id> = {
                // An ID is "hidden" if any of its ancestors (inside this
                // column, among the tree-ordered rows) is in `collapsed`.
                let mut hidden: HashSet<Id> = HashSet::new();
                // Walk tree-ordered list; since depth is non-decreasing when
                // walking into a subtree, we can track the active path.
                let mut path: Vec<(Id, usize)> = Vec::new();
                for (row, depth) in rows {
                    while path.last().map(|(_, d)| *d >= *depth).unwrap_or(false) {
                        path.pop();
                    }
                    let parent_hidden = path.iter().any(|(pid, _)| {
                        hidden.contains(pid) || collapsed.contains(pid)
                    });
                    if parent_hidden {
                        hidden.insert(row.id);
                    }
                    path.push((row.id, *depth));
                }
                hidden
            };

            egui::ScrollArea::vertical()
                .id_salt(("compass_column", status))
                .max_height(height)
                .auto_shrink([false, false])
                // Disable drag-to-scroll — it registers a content-wide
                // `Sense::drag()` that collides with nested click-senses
                // on cards/triangles and trips an `unwrap()` in egui's
                // hit_test under some layouts (egui 0.33.x / 0.34.x).
                .scroll_source(egui::scroll_area::ScrollSource {
                    scroll_bar: true,
                    drag: false,
                    mouse_wheel: true,
                })
                .show(ui, |ui| {
                    if rows.is_empty() && !form.open {
                        // Subtle centered placeholder for an empty
                        // column. Matches the muted monospace style
                        // used elsewhere (keeps the column compact —
                        // a full empty-state with icon would be
                        // heavy at 240px wide).
                        ui.add_space(8.0);
                        ui.vertical_centered(|ui| {
                            ui.label(
                                egui::RichText::new(format!(
                                    "NO {} GOALS",
                                    status.to_uppercase()
                                ))
                                .monospace()
                                .small()
                                .color(color_muted(ui)),
                            );
                        });
                        ui.add_space(8.0);
                        return;
                    }
                    for (row, depth) in rows {
                        if ancestors_collapsed.contains(&row.id) {
                            continue;
                        }
                        render_goal_card(
                            ui,
                            row,
                            *depth,
                            expanded_goal,
                            expanded_notes,
                            collapsed,
                            note_inputs,
                            status_menu,
                            title_by_id,
                            card_rects,
                            move_intent,
                            note_intent,
                        );
                        ui.add_space(6.0);
                    }
                });
            });
        });

    // Kanban-style left accent stripe in the status color. Painted on top
    // of the frame after layout so we know the exact rect.
    let frame_rect = frame_response.response.rect;
    let accent = egui::Rect::from_min_size(
        frame_rect.min,
        egui::vec2(4.0, frame_rect.height()),
    );
    ui.painter().rect_filled(
        accent,
        egui::CornerRadius {
            nw: 6,
            sw: 6,
            ne: 0,
            se: 0,
        },
        status_col,
    );
}

fn render_compose_form(
    ui: &mut egui::Ui,
    status: &str,
    form: &mut ComposeForm,
    add_intent: &mut Option<AddIntent>,
) {
    egui::Frame::NONE
        .fill(card_bg(ui))
        .corner_radius(egui::CornerRadius::same(4))
        .inner_margin(egui::Margin::symmetric(8, 6))
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            // Header: "NEW GOAL →" muted + status keyword in its status color.
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 4.0;
                ui.label(
                    egui::RichText::new("NEW GOAL \u{2192}")
                        .small()
                        .monospace()
                        .strong()
                        .color(color_muted(ui)),
                );
                ui.label(
                    egui::RichText::new(status.to_uppercase())
                        .small()
                        .monospace()
                        .strong()
                        .color(status_color(status)),
                );
            });
            ui.add_space(2.0);
            ui.add(
                egui::TextEdit::singleline(&mut form.title)
                    .hint_text("title")
                    .desired_width(f32::INFINITY),
            );
            ui.add(
                egui::TextEdit::singleline(&mut form.tags)
                    .hint_text("tags (space-separated)")
                    .desired_width(f32::INFINITY),
            );
            ui.add(
                egui::TextEdit::singleline(&mut form.parent_prefix)
                    .hint_text("parent id prefix (optional)")
                    .desired_width(f32::INFINITY),
            );
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                let submit_enabled = !form.title.trim().is_empty() && add_intent.is_none();
                // CREATE button tinted with the column's status color
                // — reinforces "this goal will land in this column" at
                // submit time.
                let fill = status_color(status);
                let text = colorhash::text_color_on(fill);
                if ui
                    .add_enabled(
                        submit_enabled,
                        egui::Button::new(
                            egui::RichText::new("CREATE")
                                .small()
                                .monospace()
                                .strong()
                                .color(text),
                        )
                        .fill(fill),
                    )
                    .clicked()
                {
                    let parent = resolve_prefix_hack(&form.parent_prefix);
                    let tags: Vec<String> = form
                        .tags
                        .split_whitespace()
                        .map(|s| s.trim_start_matches('#').to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                    *add_intent = Some(AddIntent {
                        title: form.title.trim().to_string(),
                        status: status.to_string(),
                        parent,
                        tags,
                    });
                }
                if ui
                    .add(egui::Button::new(
                        egui::RichText::new("CANCEL")
                            .small()
                            .monospace()
                            .color(color_muted(ui)),
                    ))
                    .clicked()
                {
                    form.open = false;
                    form.title.clear();
                    form.tags.clear();
                    form.parent_prefix.clear();
                }
            });
        });
}

/// Resolve a hex prefix to a full Id. This widget can't access the live
/// connection at form-render time (it'd re-enter the mutex), so we only
/// accept a full 32-char hex id. Shorter prefixes silently yield `None`.
/// Callers who need prefix resolution should copy the full id from the
/// board into the field — which is easy because the id_prefix is always
/// shown on cards.
fn resolve_prefix_hack(prefix: &str) -> Option<Id> {
    let trimmed = prefix.trim();
    if trimmed.is_empty() {
        return None;
    }
    // Only accept full 32-char hex — shorter prefixes are ambiguous and
    // we'd need another mutex re-entry to resolve them.
    Id::from_hex(trimmed)
}

// ── Card rendering ───────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn render_goal_card(
    ui: &mut egui::Ui,
    row: &GoalRow,
    depth: usize,
    expanded_goal: &mut Option<Id>,
    expanded_notes: Option<&(Id, Vec<NoteRow>)>,
    collapsed: &mut HashSet<Id>,
    note_inputs: &mut HashMap<Id, String>,
    status_menu: &mut Option<Id>,
    title_by_id: &HashMap<Id, String>,
    card_rects: &mut HashMap<Id, egui::Rect>,
    move_intent: &mut Option<(Id, String)>,
    note_intent: &mut Option<(Id, String)>,
) {
    const DEP_LINE_STEP: f32 = 6.0;
    const DEP_LINE_BASE: f32 = 8.0;
    let dep_lines = depth.min(3);
    let dep_indent = if dep_lines == 0 {
        0.0
    } else {
        (dep_lines as f32 * DEP_LINE_STEP) + DEP_LINE_BASE
    };

    let is_expanded = *expanded_goal == Some(row.id);
    let is_collapsed = collapsed.contains(&row.id);

    let card_response = egui::Frame::NONE
        .fill(card_bg(ui))
        .corner_radius(egui::CornerRadius::same(4))
        .outer_margin(egui::Margin {
            left: dep_indent as i8,
            right: 0,
            top: 0,
            bottom: 0,
        })
        .inner_margin(egui::Margin::symmetric(8, 6))
        .show(ui, |ui| {
            ui.set_width(ui.available_width());

            // Row 1: status chip · title · collapse triangle · short id.
            ui.horizontal(|ui| {
                render_status_chip(ui, &row.status, status_color(&row.status));
                // Collapse-subtree triangle, only shown when there are
                // visible children (we don't know here without the tree
                // snapshot, so show it always at depth=0 or higher — the
                // click is a no-op for leaves but is harmless).
                let tri = if is_collapsed { "" } else { "" };
                if ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new(tri).monospace().color(color_muted(ui)),
                        )
                        .sense(egui::Sense::click()),
                    )
                    .clicked()
                {
                    if is_collapsed {
                        collapsed.remove(&row.id);
                    } else {
                        collapsed.insert(row.id);
                    }
                }

                ui.add(
                    egui::Label::new(egui::RichText::new(&row.title).monospace())
                        .wrap_mode(egui::TextWrapMode::Wrap),
                );
            });

            // Row 2: id prefix · optional parent pointer (left) · note
            // count chip (right). Note count lives on the right edge so
            // it reads like a metadata badge, not a continuation of the
            // id string.
            ui.horizontal(|ui| {
                let id_text = if let Some(parent) = row.parent {
                    format!("^{} {}", id_prefix(parent), row.id_prefix)
                } else {
                    row.id_prefix.clone()
                };
                ui.label(
                    egui::RichText::new(id_text)
                        .monospace()
                        .small()
                        .color(color_muted(ui)),
                );
                if row.note_count > 0 {
                    ui.with_layout(
                        egui::Layout::right_to_left(egui::Align::Center),
                        |ui| {
                            render_chip(
                                ui,
                                &format!("{}n", row.note_count),
                                color_muted(ui),
                            );
                        },
                    );
                }
            });

            // Row 3: priority edges + tags. Tags and priority badges
            // share a tight horizontal_wrapped row — long names get
            // truncated so a single chip can't overflow the column.
            let has_prio = !row.higher_over.is_empty();
            if has_prio || !row.tags.is_empty() {
                ui.horizontal_wrapped(|ui| {
                    ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0);
                    for lower in &row.higher_over {
                        let target_label = title_by_id
                            .get(lower)
                            .map(|t| truncate_inline(t, 16))
                            .unwrap_or_else(|| id_prefix(*lower));
                        render_chip(
                            ui,
                            &format!("{target_label}"),
                            egui::Color32::from_rgb(0x55, 0x3f, 0x7f),
                        );
                    }
                    for tag in &row.tags {
                        let tag_label = truncate_inline(tag, 18);
                        render_chip(ui, &format!("#{tag_label}"), tag_color(tag));
                    }
                });
            }
        })
        .response;

    // Whole card is clickable to toggle note expansion.
    let click_id = ui.make_persistent_id(("compass_goal", row.id));
    let response = ui.interact(card_response.rect, click_id, egui::Sense::click());
    // PointingHand cursor + hover tooltip so the interaction model is
    // discoverable. The card looks like a card; without this it
    // doesn't look clickable.
    if response.hovered() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
        response
            .clone()
            .on_hover_text("Click to expand · Shift+click or right-click to move");
    }
    if response.clicked() {
        if *expanded_goal == Some(row.id) {
            *expanded_goal = None;
        } else {
            *expanded_goal = Some(row.id);
        }
    }
    let secondary = response.secondary_clicked();
    if secondary || response.hovered() && ui.input(|i| i.modifiers.shift && i.pointer.any_click()) {
        *status_menu = Some(row.id);
    }

    // Status-menu popup (opens next to the card).
    if *status_menu == Some(row.id) {
        egui::Window::new(format!("move_menu_{}", row.id_prefix))
            .title_bar(false)
            .resizable(false)
            .fixed_pos(card_response.rect.right_top())
            .show(ui.ctx(), |ui| {
                ui.label(
                    egui::RichText::new("MOVE TO")
                        .small()
                        .monospace()
                        .strong()
                        .color(color_muted(ui)),
                );
                for status in DEFAULT_STATUSES {
                    if status == row.status {
                        continue;
                    }
                    let fill = status_color(status);
                    let text = colorhash::text_color_on(fill);
                    if ui
                        .add(
                            egui::Button::new(
                                egui::RichText::new(status.to_uppercase())
                                    .small()
                                    .monospace()
                                    .strong()
                                    .color(text),
                            )
                            .fill(fill),
                        )
                        .clicked()
                    {
                        *move_intent = Some((row.id, status.to_string()));
                    }
                }
                if ui
                    .add(egui::Button::new(
                        egui::RichText::new("CANCEL")
                            .small()
                            .monospace()
                            .color(color_muted(ui)),
                    ))
                    .clicked()
                {
                    *status_menu = None;
                }
            });
    }

    if is_expanded {
        let notes: &[NoteRow] = expanded_notes
            .filter(|(gid, _)| *gid == row.id)
            .map(|(_, n)| n.as_slice())
            .unwrap_or(&[]);
        egui::Frame::NONE
            .stroke(egui::Stroke::new(1.0, color_muted(ui)))
            .outer_margin(egui::Margin {
                left: dep_indent as i8,
                right: 0,
                top: 0,
                bottom: 0,
            })
            .inner_margin(egui::Margin::symmetric(8, 6))
            .show(ui, |ui| {
                ui.set_width(ui.available_width());

                // Move-status row (inline, as an alternative to the popup).
                ui.horizontal_wrapped(|ui| {
                    ui.spacing_mut().item_spacing.x = 4.0;
                    ui.label(
                        egui::RichText::new("MOVE TO")
                            .small()
                            .monospace()
                            .strong()
                            .color(color_muted(ui)),
                    );
                    for status in DEFAULT_STATUSES {
                        if status == row.status {
                            continue;
                        }
                        let fill = status_color(status);
                        let text = colorhash::text_color_on(fill);
                        if ui
                            .add(egui::Button::new(
                                egui::RichText::new(status.to_uppercase())
                                    .small()
                                    .monospace()
                                    .strong()
                                    .color(text),
                            ).fill(fill))
                            .clicked()
                        {
                            *move_intent = Some((row.id, status.to_string()));
                        }
                    }
                });

                ui.separator();

                // Notes — rendered as their own small framed cards
                // with an age-chip header and a thin left-accent in
                // the goal's status color, so the note stream reads
                // like a timeline of annotations on this goal.
                let now = now_tai_ns();
                if notes.is_empty() {
                    ui.add_space(4.0);
                    ui.vertical_centered(|ui| {
                        ui.label(
                            egui::RichText::new("NO NOTES YET")
                                .monospace()
                                .small()
                                .color(color_muted(ui)),
                        );
                    });
                    ui.add_space(4.0);
                } else {
                    let status_col = status_color(&row.status);
                    for note in notes {
                        let note_resp = egui::Frame::NONE
                            .fill(card_bg(ui))
                            .corner_radius(egui::CornerRadius::same(3))
                            .inner_margin(egui::Margin {
                                left: 8,
                                right: 6,
                                top: 4,
                                bottom: 4,
                            })
                            .show(ui, |ui| {
                                ui.set_width(ui.available_width());
                                ui.label(
                                    egui::RichText::new(format_age(now, note.at))
                                        .small()
                                        .monospace()
                                        .color(color_muted(ui)),
                                );
                                ui.add(
                                    egui::Label::new(
                                        egui::RichText::new(&note.body).small(),
                                    )
                                    .wrap_mode(egui::TextWrapMode::Wrap),
                                );
                            });
                        // Paint a 2-px status-colored accent on the
                        // note's left edge after layout.
                        let r = note_resp.response.rect;
                        let painter = ui.painter();
                        painter.rect_filled(
                            egui::Rect::from_min_size(
                                r.min,
                                egui::vec2(2.0, r.height()),
                            ),
                            0.0,
                            status_col,
                        );
                        ui.add_space(3.0);
                    }
                }

                ui.separator();

                // + Note inline form.
                let buf = note_inputs.entry(row.id).or_default();
                ui.add(
                    egui::TextEdit::multiline(buf)
                        .hint_text("new note…")
                        .desired_rows(2)
                        .desired_width(f32::INFINITY),
                );
                ui.horizontal(|ui| {
                    let submit_enabled =
                        !buf.trim().is_empty() && note_intent.is_none();
                    if ui
                        .add_enabled(submit_enabled, egui::Button::new("+ Note"))
                        .clicked()
                    {
                        *note_intent = Some((row.id, buf.clone()));
                    }
                });
            });
        ui.add_space(4.0);
    }

    // Draw dependency gutter lines to the left of the card.
    let rect = card_response.rect;
    card_rects.insert(row.id, rect);
    let painter = ui.painter();
    let stroke = egui::Stroke::new(1.2, color_muted(ui));
    for idx in 0..dep_lines {
        let x = rect.left() - dep_indent + 4.0 + (idx as f32 * DEP_LINE_STEP);
        let y1 = rect.top() + 0.5;
        let y2 = rect.bottom() - 0.5;
        painter.line_segment([egui::pos2(x, y1), egui::pos2(x, y2)], stroke);
    }
}

/// Paint a priority edge between two goal cards: a smooth horizontal
/// cubic Bézier from the higher card's side to the lower card's side
/// with a small filled arrowhead at the target. The horizontally-
/// tangent control points make the curve bow outward from the
/// straight line, which naturally keeps it clear of intervening
/// cards most of the time (much better than the old 3-segment path
/// that cut straight through).
fn draw_priority_edge(
    painter: &egui::Painter,
    from: egui::Rect,
    to: egui::Rect,
    color: egui::Color32,
) {
    let (start, end, dir) = if from.center().x < to.center().x {
        (
            egui::pos2(from.right(), from.center().y),
            egui::pos2(to.left() - 6.0, to.center().y),
            1.0_f32,
        )
    } else {
        (
            egui::pos2(from.left(), from.center().y),
            egui::pos2(to.right() + 6.0, to.center().y),
            -1.0_f32,
        )
    };
    // Control-point offset: ~half the horizontal gap, clamped so short
    // edges still bow visibly and long edges don't over-curve.
    let dx = (end.x - start.x).abs().max(40.0).min(240.0) * 0.5;
    let c1 = egui::pos2(start.x + dir * dx, start.y);
    let c2 = egui::pos2(end.x - dir * dx, end.y);
    let stroke = egui::Stroke::new(1.5, color);
    painter.add(egui::Shape::CubicBezier(egui::epaint::CubicBezierShape {
        points: [start, c1, c2, end],
        closed: false,
        fill: egui::Color32::TRANSPARENT,
        stroke: egui::epaint::PathStroke::new(stroke.width, stroke.color),
    }));
    // Arrowhead — small filled triangle at the target, pointing along
    // the curve's terminal tangent (which is horizontal here).
    let head_len = 6.0;
    let back_x = end.x - dir * head_len;
    let tip = end;
    let back = egui::pos2(back_x, end.y);
    let wing_up = egui::pos2(back_x, end.y - 3.5);
    let wing_dn = egui::pos2(back_x, end.y + 3.5);
    painter.add(egui::Shape::convex_polygon(
        vec![tip, wing_up, back, wing_dn],
        color,
        egui::Stroke::NONE,
    ));
}

/// Centered empty-state block: a muted glyph, a monospace headline,
/// and an optional muted sub-hint. Used when the board is empty and
/// the user needs a nudge toward the right action.
fn render_empty_state(ui: &mut egui::Ui, glyph: &str, headline: &str, hint: Option<&str>) {
    ui.add_space(16.0);
    ui.vertical_centered(|ui| {
        ui.label(
            egui::RichText::new(glyph)
                .size(28.0)
                .color(color_muted(ui)),
        );
        ui.add_space(4.0);
        ui.label(
            egui::RichText::new(headline)
                .monospace()
                .small()
                .strong()
                .color(color_muted(ui)),
        );
        if let Some(h) = hint {
            ui.add_space(2.0);
            ui.label(
                egui::RichText::new(h)
                    .small()
                    .color(color_muted(ui)),
            );
        }
    });
    ui.add_space(16.0);
}

fn render_chip(ui: &mut egui::Ui, label: &str, fill: egui::Color32) {
    let text = colorhash::text_color_on(fill);
    egui::Frame::NONE
        .fill(fill)
        .corner_radius(egui::CornerRadius::same(4))
        .inner_margin(egui::Margin::symmetric(6, 1))
        .show(ui, |ui| {
            ui.label(egui::RichText::new(label).small().color(text));
        });
}

/// Same as [`render_chip`] but with the playbook's "label" styling:
/// monospace + strong + uppercase. Used for status pills where the
/// label is a short keyword (`todo`, `doing`, `blocked`, `done`).
fn render_status_chip(ui: &mut egui::Ui, label: &str, fill: egui::Color32) {
    let text = colorhash::text_color_on(fill);
    egui::Frame::NONE
        .fill(fill)
        .corner_radius(egui::CornerRadius::same(3))
        .inner_margin(egui::Margin::symmetric(6, 2))
        .show(ui, |ui| {
            ui.label(
                egui::RichText::new(label.to_uppercase())
                    .small()
                    .monospace()
                    .strong()
                    .color(text),
            );
        });
}