understatus 0.5.0

A calm, unobtrusive macOS statusline addon for AI coding CLIs (Claude Code): CPU/memory/disk/network + session info with a quiet glyph theme.
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
//! 라인 조립 + 폭/색상 채널 적응 + self/chain 합성.
//!
//! 계획서 §H-7/AC5 + CALM 디자인을 따른다. understatus 자체 세그먼트를 ANSI 한
//! 줄로 조립한다. `NO_COLOR`/색상 모드/`max_width`/와이드 글리프(2칸)를 존중한다.
//!
//! CALM COLOR-ONCE 규칙: 색은 **부분별로** 입힌다.
//! - load glyph(예 ▄): 밴드 틴트(펄스 ON이면 테라코타 숨쉬기) — **색 있음**.
//! - 세그먼트 VALUE(58%, $1.23, 모델명, 브랜치명, cwd, 속도): **색 없음**(터미널 기본).
//! - 라벨/단위(mem, disk, ctx, ↓ ↑, $, git 마커 ⎇): dim `label_color`.
//! - 구분자(가운뎃점 " · "): 더 어두운 `separator_color`.
//! - self/chain 사이 HUD seam("│"): `separator_color`.
//!
//! BOLD 이스케이프("\x1b[1m")는 일절 쓰지 않는다(불투명도 단계 밝기만 사용).

use crate::claude::ClaudeInput;
use crate::config::Config;
use crate::system::{NetThroughput, SystemSnapshot};
use crate::theme::{band_index, band_tint, parse_hex_pub, pick_emoji, pulse_color, ColorSpec};
use serde::Serialize;

/// cmux 사이드바 pill로 노출할 핵심 세그먼트(model/ctx/cpu/mem)의 구조화된 메타데이터.
///
/// oneline SGR 경로는 `plain`/`colored`로 색을 미리 합성하지만(COLOR-ONCE), cmux pill 경로는
/// 색을 `#RRGGBB` hex로 별도 직렬화하므로(SGR가 아니라 cmux `--color` 인자) 값/색/우선순위를
/// 구조화해 둔다. oneline 출력 바이트에는 일절 영향이 없는 additive-optional 부착물이다(설계 §5.2).
///
/// `value`는 같은 세그먼트의 원시 값(plain의 값 부분)에서 **단일 파생**한다(별도 손계산 금지 —
/// plain/colored/pill 3중 소스 드리프트 봉인, 설계 §5.2).
struct PillMeta {
    /// pill 식별 id(prefix 없음). 예 `"model"`/`"ctx"`/`"cpu"`/`"mem"`. lterm이 pane prefix를 붙인다.
    id: &'static str,
    /// pill 라벨(있으면 표시). 핵심 4개는 모두 `None`(값 자체가 라벨을 포함).
    label: Option<String>,
    /// pill 표시 값(예 `"gpt-5.5"`/`"ctx 42%"`/`"cpu 31%"`/`"mem 48%"`).
    value: String,
    /// pill 색(테마 일관 색맵 또는 cpu band_tint). `None`이면 cmux 기본색.
    color: Option<ColorSpec>,
    /// 우선순위(oneline과 동일 의미, 낮을수록 저우선). cmux priority 인자로도 전달.
    priority: u8,
    /// pill 아이콘명(cmux `--icon`, 미지원명은 cmux가 무시). model만 `Some("sparkles")`.
    icon: Option<&'static str>,
}

/// 세그먼트 한 조각: 폭 계산용 순수 텍스트 + ANSI 적용된 표시 텍스트 + 우선순위.
///
/// COLOR-ONCE 규칙상 한 세그먼트 안에서도 글리프/라벨/값이 서로 다른 색을 가지므로,
/// `colored`에 부분별 ANSI를 미리 합성해 둔다. 폭은 `plain`(이스케이프 없는 가시
/// 텍스트)으로 계산한다. `priority`가 낮을수록 먼저 버려진다(§H-7).
struct Segment {
    /// 폭 계산용 순수 텍스트(ANSI 이스케이프 없음).
    plain: String,
    /// 화면에 출력할, 부분별 ANSI가 적용된 텍스트.
    colored: String,
    /// 폭 초과 시 생략 우선순위(낮을수록 먼저 버림).
    priority: u8,
    /// cmux pill 경로 전용 메타데이터(model/ctx/cpu/mem에만 `Some`). oneline 경로는 미사용.
    /// 기본 `None` — oneline SGR 바이트에 영향 없음(additive-optional, 설계 §5.2).
    pill: Option<PillMeta>,
}

/// `understatus render --surface-format cmux-status`의 stdout 직렬화 루트(설계 §3.3).
///
/// lterm `CmuxStatusSink`가 이 JSON을 파싱해 cmux `set-status`로 diff 적용한다. 한 줄 JSON으로
/// 출력된다(`serde_json::to_string`).
///
/// 진행바(`set-progress`)는 의도적으로 직렬화하지 않는다: cmux `set-progress`가 워크스페이스
/// 전역이라 페인별 ctx 값이 서로 누수/덮어쓰기(클로버)되기 때문이다. ctx는 pill로만 표시한다
/// (사용자 결정).
#[derive(Debug, Serialize, PartialEq)]
pub struct CmuxStatusOutput {
    /// 스키마 식별자(항상 `"cmux-status"`). lterm sink가 non-JSON/타 스키마를 무해 처리하는 근거.
    schema: &'static str,
    /// 스키마 버전(현재 1). additive-optional 계약상 lterm은 version 하드게이트하지 않는다.
    version: u32,
    /// pill 배열(model/ctx/cpu/mem 중 소스 가용분만).
    pills: Vec<Pill>,
}

/// cmux 사이드바 pill 하나(설계 §3.3). `key`는 prefix 없는 세그먼트 id다.
#[derive(Debug, Serialize, PartialEq)]
pub struct Pill {
    /// 세그먼트 id(prefix 없음). lterm이 `lterm.<pane>.` prefix를 앞에 붙인다.
    key: String,
    /// pill 라벨(있으면). 핵심 4개는 `None`.
    label: Option<String>,
    /// pill 표시 값.
    value: String,
    /// pill 색 `#RRGGBB`(없으면 cmux 기본색).
    color: Option<String>,
    /// pill 아이콘명(cmux가 미지원명은 무시).
    icon: Option<String>,
    /// 우선순위(낮을수록 저우선).
    priority: u8,
}

// CONTRACT: signature is frozen — implement body only, do not change this signature
/// understatus 자체 세그먼트(ANSI 한 줄)를 조립한다.
///
/// # 인자
/// - `input`: 파싱된 Claude 세션 정보(모델/비용/컨텍스트/git 등 세그먼트 소스).
/// - `snap`: CPU/메모리/배터리 스냅샷(이모지/펄스/지표 소스).
/// - `cfg`: 표시 토글(`display.*`), 색상 모드(`color.*`), 폭(`display.max_width`).
/// - `now_ms`: 현재 시각(ms). 펄스 위상 계산에 [`crate::theme`]로 전달.
/// - `pulse_on`: [`crate::theme::pulse_gate`]가 산출한 이번 프레임 펄스 on 여부.
///
/// # 반환
/// understatus 자체 세그먼트 문자열(개행 없음). `NO_COLOR` 설정 시 색상 제거,
/// `max_width` 초과 시 저우선 세그먼트 생략/축약, 각 정보원 부재 시 해당 세그먼트 생략(AC5).
pub fn render(
    input: &ClaudeInput,
    snap: &SystemSnapshot,
    cfg: &Config,
    now_ms: u128,
    pulse_on: bool,
) -> String {
    // 색상 활성 여부: NO_COLOR(존재만으로 비활성) 또는 mode "none"이면 ANSI 일절 없음.
    let color_on = std::env::var_os("NO_COLOR").is_none() && cfg.color.mode != "none";

    // 1) 표시할 세그먼트들을 (plain/colored/priority)와 함께 수집.
    let segments = collect_segments(input, snap, cfg, now_ms, pulse_on, color_on);

    // 2) max_width를 넘으면 저우선 세그먼트부터 제거(폭은 plain 기준 + 구분자).
    let kept = enforce_width(segments, cfg.display.max_width, &cfg.color.separator);

    // 3) dim 가운뎃점 구분자로 합친다(색상 on이면 separator_color 적용).
    let separator = render_separator(cfg, color_on);
    kept.iter()
        .map(|segment| segment.colored.as_str())
        .collect::<Vec<_>>()
        .join(&separator)
}

// CONTRACT: cmux pill 경로 진입점 — oneline `render()`와 동일 `collect_segments` 호출을 공유한다.
/// cmux 네이티브 status pill JSON 구조를 만든다(`--surface-format cmux-status` 경로, 설계 §3.3).
///
/// oneline [`render`]와 **동일한 [`collect_segments`] 호출**을 써서 세그먼트 가용성 드리프트를
/// 막는다(같은 입력 → 같은 핵심 세그먼트 집합). pill은 model/ctx/cpu/mem에만 부착되어 있으므로
/// [`to_cmux_pills`]가 그 4개(소스 가용분)만 수집한다. 색은 `#RRGGBB` hex로 직렬화된다(SGR 아님).
///
/// # 인자
/// - `input`/`snap`/`cfg`/`now_ms`/`pulse_on`: [`render`]와 동일(세그먼트 수집 소스).
///
/// # 반환
/// 직렬화 가능한 [`CmuxStatusOutput`]. 호출부(main.rs)가 `serde_json::to_string`으로 1줄 출력한다.
pub fn render_cmux_pills(
    input: &ClaudeInput,
    snap: &SystemSnapshot,
    cfg: &Config,
    now_ms: u128,
    pulse_on: bool,
) -> CmuxStatusOutput {
    // color_on은 pill 색(hex)에 무관하지만 collect_segments 계약상 전달한다(oneline과 동일 수집).
    let color_on = std::env::var_os("NO_COLOR").is_none() && cfg.color.mode != "none";
    let segments = collect_segments(input, snap, cfg, now_ms, pulse_on, color_on);
    to_cmux_pills(&segments)
}

/// 표시 토글/스냅샷/세션 정보로 세그먼트 목록을 만든다(부분별 ANSI 적용).
///
/// 각 정보원이 부재(`None`)면 해당 세그먼트를 생략한다(AC5 우아한 저하).
/// COLOR-ONCE: 값엔 색 없음, 라벨/단위/마커엔 dim `label_color`, 글리프엔 밴드 틴트.
fn collect_segments(
    input: &ClaudeInput,
    snap: &SystemSnapshot,
    cfg: &Config,
    now_ms: u128,
    pulse_on: bool,
    color_on: bool,
) -> Vec<Segment> {
    let mut segments = Vec::new();

    // load glyph + CPU%: 가장 높은 우선순위(핵심, 마지막까지 유지).
    // 글리프는 밴드 틴트(펄스 ON이면 테라코타 숨쉬기), CPU% 값엔 색 없음.
    let glyph = pick_emoji(snap.cpu_percent, now_ms, pulse_on, cfg);
    let glyph_color = glyph_tint(snap.cpu_percent, now_ms, pulse_on, cfg);
    let cpu_value = format!("{:.0}%", snap.cpu_percent);
    segments.push(Segment {
        plain: format!("{glyph} {cpu_value}"),
        colored: format!(
            "{} {}",
            tinted(&glyph, glyph_color, cfg, color_on),
            cpu_value
        ),
        priority: 100,
        // cpu pill 값은 동일 cpu_value에서 단일 파생(3중-소스 동기화). 색은 기존 band_tint 재사용.
        pill: Some(PillMeta {
            id: "cpu",
            label: None,
            value: format!("cpu {cpu_value}"),
            color: Some(band_tint(band_index(snap.cpu_percent, cfg), cfg)),
            priority: 100,
            icon: None,
        }),
    });

    // 메모리%: 라벨 "mem" dim + 값 색 없음.
    let mem_value = format!("{:.0}%", snap.mem_percent);
    let mut mem_segment = label_value_segment("mem", &mem_value, 90, cfg, color_on);
    // mem pill 값은 mem_value(plain의 값 부분)에서 단일 파생. 색은 테마 중립 색맵.
    mem_segment.pill = Some(PillMeta {
        id: "mem",
        label: None,
        value: format!("mem {mem_value}"),
        color: Some(pill_neutral_color()),
        priority: 90,
        icon: None,
    });
    segments.push(mem_segment);

    // 배터리(P2): 토글 on + 값 있을 때만. 라벨 마커 dim + 값 색 없음.
    if cfg.display.show_battery {
        if let Some(battery) = snap.battery.as_ref() {
            segments.push(label_value_segment(
                battery_marker(battery.percent, battery.is_charging),
                &format!("{:.0}%", battery.percent),
                85,
                cfg,
                color_on,
            ));
        }
    }

    // 디스크(P2): 토글 on + 값 있을 때만. 라벨 "disk" dim + 값 색 없음.
    if cfg.display.show_disk {
        if let Some(disk) = snap.disk_percent {
            segments.push(label_value_segment(
                "disk",
                &format!("{disk:.0}%"),
                80,
                cfg,
                color_on,
            ));
        }
    }

    // 네트워크(P2): 토글 on + 값 있을 때만. ↓ ↑ 화살표 dim + 속도 값 색 없음.
    if cfg.display.show_network {
        if let Some(net) = snap.net.as_ref() {
            segments.push(net_segment(net, 75, cfg, color_on));
        }
    }

    // 모델 표시명: 값(색 없음).
    if cfg.display.show_model {
        if let Some(model) = input.model_display_name.as_deref() {
            if !model.is_empty() {
                let mut model_segment = value_segment(model, 60);
                // model pill 값은 plain과 동일한 model 문자열에서 단일 파생(enrich 성공 시 풍부한
                // 이름, 실패 시 bare agent 토큰 "codex" — oneline과 동일). 색은 테마 accent.
                model_segment.pill = Some(PillMeta {
                    id: "model",
                    label: None,
                    value: model.to_string(),
                    color: Some(pill_accent_color()),
                    priority: 60,
                    icon: Some("sparkles"),
                });
                segments.push(model_segment);
            }
        }
    }

    // 컨텍스트 사용률%: null이면 세그먼트 생략(AC2). 라벨 "ctx" dim + 값 색 없음.
    if cfg.display.show_context {
        if let Some(context) = input.context_used_percentage {
            // ctx %를 0..=100으로 클램프 + 단일 정수 양자화한다. 한 번 양자화한 정수를 plain/pill
            // 양쪽에 동일하게 써서 분기 드리프트(plain {:.0}% vs pill round())를 봉인한다(Codex
            // render.rs:272 지적). >100/음수/NaN 입력에서도 안전하다.
            let context_pct_int = clamp_ctx_percent(context);
            let mut ctx_segment =
                label_value_segment("ctx", &format!("{context_pct_int}%"), 50, cfg, color_on);
            // ctx pill 값은 동일 정수% 양자화에서 단일 파생. 색은 테마 band 색맵.
            ctx_segment.pill = Some(PillMeta {
                id: "ctx",
                label: None,
                value: format!("ctx {context_pct_int}%"),
                color: Some(pill_band_color()),
                priority: 50,
                icon: None,
            });
            segments.push(ctx_segment);
        }
    }

    // Codex 한도/요금제/effort(lterm+codex 소스 전용, spec §6). input.codex가 Some일 때만,
    // 그 안의 각 Option이 Some일 때만 추가한다(기존 None-skip 패턴 동형). Claude 경로는
    // codex=None이라 신규 세그먼트 0 → 기존 출력/바이트 보존.
    if let Some(codex) = input.codex.as_ref() {
        // 5h 한도%(priority 48): 라벨 "5h" dim + 값 색 없음.
        if let Some(rate_5h) = codex.rate_5h_percent {
            segments.push(label_value_segment(
                "5h",
                &format!("{rate_5h:.0}%"),
                48,
                cfg,
                color_on,
            ));
        }
        // 주간 한도%(priority 46): 라벨 "wk" dim + 값 색 없음.
        if let Some(rate_weekly) = codex.rate_weekly_percent {
            segments.push(label_value_segment(
                "wk",
                &format!("{rate_weekly:.0}%"),
                46,
                cfg,
                color_on,
            ));
        }
        // plan(priority 26): bare value(라벨 없음, 예 "pro").
        if let Some(plan) = codex.plan.as_deref() {
            if !plan.is_empty() {
                segments.push(value_segment(plan, 26));
            }
        }
        // effort(priority 24): bare value(라벨 없음, 예 "xhigh").
        if let Some(effort) = codex.effort.as_deref() {
            if !effort.is_empty() {
                segments.push(value_segment(effort, 24));
            }
        }
    }

    // cwd/git 브랜치: git_branch 우선. git 마커 ⎇ dim + 브랜치명 값 색 없음.
    if cfg.display.show_git {
        if let Some(branch) = input.git_branch.as_deref() {
            if !branch.is_empty() {
                // oneline plain/colored 바이트 보존을 위해 label_value_segment 시그니처는 불변으로 두고,
                // cmux pill 메타만 additive로 부착한다(model/ctx/mem pill 패턴 동형).
                let mut git_segment = label_value_segment("", branch, 40, cfg, color_on);
                git_segment.pill = Some(PillMeta {
                    id: "git",
                    label: None,
                    // bare 브랜치명(model pill 선례). 식별은 git-branch 아이콘이 담당.
                    value: branch.to_string(),
                    color: Some(pill_git_color()),
                    priority: 40,
                    icon: Some("git-branch"),
                });
                segments.push(git_segment);
            }
        }
    }
    // lterm 세션/페인 라벨(예 "codex/%3"): cwd 바로 앞 배치. bare value(cwd와 동일 스타일).
    // priority 35 = cwd 30 위, git 40 아래. Claude 경로는 session_label=None이라 미표시.
    if cfg.display.show_session {
        if let Some(label) = input.session_label.as_deref() {
            if !label.is_empty() {
                segments.push(value_segment(label, 35));
            }
        }
    }
    if let Some(cwd) = input.cwd.as_deref() {
        if let Some(dir) = cwd.rsplit('/').find(|part| !part.is_empty()) {
            segments.push(value_segment(dir, 30));
        }
    }

    // 누적 비용 USD: 가장 낮은 우선순위(먼저 버림). $ 마커 dim + 금액 값 색 없음.
    if cfg.display.show_cost {
        if let Some(cost) = input.cost_usd {
            segments.push(label_value_segment(
                "$",
                &format!("{cost:.2}"),
                20,
                cfg,
                color_on,
            ));
        }
    }

    segments
}

/// 글리프에 입힐 틴트(펄스 ON이면 테라코타 숨쉬기, OFF면 정적 밴드 틴트)를 고른다.
///
/// COLOR-ONCE: 이 틴트는 글리프 문자에만 적용되고 값/라벨엔 적용되지 않는다.
fn glyph_tint(cpu_percent: f64, now_ms: u128, pulse_on: bool, cfg: &Config) -> ColorSpec {
    pulse_color(cpu_percent, now_ms, pulse_on, cfg)
        .unwrap_or_else(|| band_tint(band_index(cpu_percent, cfg), cfg))
}

/// "라벨 값" 형태의 세그먼트를 만든다(라벨 dim, 값 색 없음).
///
/// 라벨(단위/마커)은 `label_color`로 dim 처리하고, 값은 ANSI 없이 그대로 둔다.
fn label_value_segment(
    label: &str,
    value: &str,
    priority: u8,
    cfg: &Config,
    color_on: bool,
) -> Segment {
    Segment {
        plain: format!("{label} {value}"),
        colored: format!("{} {value}", dim_label(label, cfg, color_on)),
        priority,
        pill: None,
    }
}

/// 값만 있는 세그먼트(모델명/cwd 등)를 만든다(색 없음, 터미널 기본 밝기).
fn value_segment(value: &str, priority: u8) -> Segment {
    Segment {
        plain: value.to_string(),
        colored: value.to_string(),
        priority,
        pill: None,
    }
}

/// model pill 전용 accent 색(테마 일관 상수). understatus 값 세그먼트엔 색이 없으므로 신규 매핑.
///
/// understatus 디자인 토큰에 cmux pill 전용 색이 없어 pill 가독성을 위해 정의한다(설계 §5.3).
/// `#7AA2F7`(차분한 blue accent) — 모델명을 사이드바에서 한눈에 식별하게 한다.
fn pill_accent_color() -> ColorSpec {
    ColorSpec {
        r: 0x7a,
        g: 0xa2,
        b: 0xf7,
    }
}

/// ctx 사용률%를 0..=100으로 클램프 + 단일 정수로 양자화한다(plain/pill 공통 소스).
///
/// `context_used_percentage`가 100을 넘거나(예 분모 차이로 인한 값 튐) 음수/NaN이어도 안전하게
/// 0..=100 정수로 수렴시킨다. plain(`format!("{N}%")`)과 pill(`format!("ctx {N}%")`) 양쪽이 이
/// 한 정수를 공유하므로 양자화 분기 드리프트가 없다(Codex render.rs:272 지적).
fn clamp_ctx_percent(context: f64) -> u32 {
    if !context.is_finite() || context <= 0.0 {
        return 0;
    }
    // 0.0 초과가 보장된 시점에서 반올림 후 100으로 상한 클램프.
    context.round().min(100.0) as u32
}

/// ctx pill 전용 band 색(테마 일관 상수). 신규 매핑(설계 §5.3).
///
/// `#34D399`(차분한 green) — ctx 진행을 사이드바에서 식별하게 한다.
fn pill_band_color() -> ColorSpec {
    ColorSpec {
        r: 0x34,
        g: 0xd3,
        b: 0x99,
    }
}

/// mem pill 전용 중립 색(테마 일관 상수). 신규 매핑(설계 §5.3).
///
/// `#A0A0A0`(중립 회색) — 시스템 보조 지표라 강조하지 않는다.
fn pill_neutral_color() -> ColorSpec {
    ColorSpec {
        r: 0xa0,
        g: 0xa0,
        b: 0xa0,
    }
}

/// git pill 전용 색(테마 일관 상수). 신규 매핑.
///
/// `#F1502F`(git 주황) — 브랜치 pill을 사이드바에서 한눈에 식별하게 한다. 기존 4색
/// (`#7AA2F7`/`#34D399`/`#A0A0A0`/cpu band_tint)과 정적 충돌이 없다.
fn pill_git_color() -> ColorSpec {
    ColorSpec {
        r: 0xf1,
        g: 0x50,
        b: 0x2f,
    }
}

/// [`ColorSpec`](RGB)을 `#RRGGBB` 16진 문자열로 변환한다(cmux `--color` 인자용).
///
/// [`ansi_fg`]의 truecolor 산식(r/g/b 채널 추출)과 **동일 소스**를 쓰되, SGR 시퀀스가 아니라
/// cmux가 받는 hex를 출력한다(설계 §5.3). 색상 모드(auto/256)와 무관하게 항상 truecolor hex다
/// (cmux pill은 hex만 받으므로 256 근사가 불필요).
fn color_to_hex(color: ColorSpec) -> String {
    format!("#{:02X}{:02X}{:02X}", color.r, color.g, color.b)
}

/// 세그먼트 목록에서 `pill`이 있는 핵심 세그먼트만 모아 cmux pill JSON 구조를 만든다(설계 §3.3).
///
/// # 인자
/// - `segments`: [`collect_segments`]가 만든 세그먼트들(같은 호출을 oneline 경로와 공유 → 가용성
///   드리프트 없음). `pill.is_some()`인 것만 수집한다.
///
/// # 반환
/// `{schema, version, pills}`. ctx 세그먼트는 다른 핵심 세그먼트와 동일하게 pill로만 표시한다.
/// 진행바(`set-progress`)는 워크스페이스 전역 누수/클로버 때문에 직렬화하지 않는다(사용자 결정).
fn to_cmux_pills(segments: &[Segment]) -> CmuxStatusOutput {
    let mut pills = Vec::new();
    for segment in segments {
        let Some(meta) = segment.pill.as_ref() else {
            continue;
        };
        pills.push(Pill {
            key: meta.id.to_string(),
            label: meta.label.clone(),
            value: meta.value.clone(),
            color: meta.color.map(color_to_hex),
            icon: meta.icon.map(str::to_string),
            priority: meta.priority,
        });
    }
    CmuxStatusOutput {
        schema: "cmux-status",
        version: 1,
        pills,
    }
}

/// 네트워크 throughput 세그먼트를 만든다(↓ ↑ 화살표 dim + 속도 값 색 없음).
fn net_segment(net: &NetThroughput, priority: u8, cfg: &Config, color_on: bool) -> Segment {
    let rx = format_bytes_per_sec(net.rx_bps);
    let tx = format_bytes_per_sec(net.tx_bps);
    Segment {
        plain: format!("{rx}{tx}"),
        colored: format!(
            "{}{rx} {}{tx}",
            dim_label("", cfg, color_on),
            dim_label("", cfg, color_on)
        ),
        priority,
        pill: None,
    }
}

/// 배터리 잔량/충전 상태에 맞는 단일 셀 마커를 고른다(CALM, dim 라벨로 렌더).
///
/// 우선순위: 충전 중 → `bat+`, 비충전 & 잔량 ≤ 20% → `bat!`(저잔량 경고),
/// 그 외(비충전 & 충분) → `bat`. 마커는 라벨로 취급되어 `label_color`로 dim 처리된다.
///
/// # 인자
/// - `percent`: 배터리 잔량(0–100).
/// - `is_charging`: 충전/AC 연결 여부.
///
/// # 반환
/// 표시할 배터리 마커 문자열(차분한 텍스트, 이모지 아님).
fn battery_marker(percent: f64, is_charging: bool) -> &'static str {
    if is_charging {
        "bat+" // 충전 중.
    } else if percent <= 20.0 {
        "bat!" // 저잔량 경고(비충전).
    } else {
        "bat" // 배터리 구동 중(충분).
    }
}

/// 초당 바이트(rate)를 B/KB/MB 단위의 사람 친화 문자열로 환산한다(1024 기준).
///
/// # 인자
/// - `bps`: 초당 바이트.
///
/// # 반환
/// 예: `512B/s`, `12KB/s`, `3.4MB/s`. 음수/NaN은 `0B/s`로 안전 저하한다.
fn format_bytes_per_sec(bps: f64) -> String {
    if !bps.is_finite() || bps < 0.0 {
        return "0B/s".to_string();
    }
    const KB: f64 = 1024.0;
    const MB: f64 = 1024.0 * 1024.0;
    if bps < KB {
        format!("{:.0}B/s", bps)
    } else if bps < MB {
        format!("{:.0}KB/s", bps / KB)
    } else {
        format!("{:.1}MB/s", bps / MB)
    }
}

/// `max_width`를 넘으면 저우선 세그먼트부터 제거한다(와이드 글리프 2칸 계산).
///
/// 표시 순서는 보존하되, 폭 초과 시 `priority`가 가장 낮은 세그먼트를 하나씩 버린다.
/// 폭은 가시 텍스트(`plain`)와 구분자(`separator`) 표시 폭으로 계산한다(ANSI 제외).
/// 단일 핵심 세그먼트 하나는 항상 남긴다(빈 줄 방지).
fn enforce_width(mut segments: Vec<Segment>, max_width: usize, separator: &str) -> Vec<Segment> {
    let sep_width = display_width(separator);
    while segments.len() > 1 && composed_width(&segments, sep_width) > max_width {
        // 가장 낮은 priority(동률이면 뒤쪽) 세그먼트를 제거.
        let drop_index = segments
            .iter()
            .enumerate()
            .min_by_key(|(_, segment)| segment.priority)
            .map(|(index, _)| index)
            .unwrap_or(segments.len() - 1);
        segments.remove(drop_index);
    }
    segments
}

/// 세그먼트들을 구분자로 합쳤을 때의 표시 폭(와이드 문자 2칸)을 계산한다(ANSI 제외).
fn composed_width(segments: &[Segment], sep_width: usize) -> usize {
    let text_width: usize = segments
        .iter()
        .map(|segment| display_width(&segment.plain))
        .sum();
    // 세그먼트 사이 구분자 폭만큼.
    let separators = segments.len().saturating_sub(1);
    text_width + separators * sep_width
}

/// 문자열의 터미널 표시 폭을 계산한다(와이드/이모지 = 2칸, 그 외 1칸).
///
/// 정밀한 East Asian Width 테이블 대신, 이모지/넓은 문자 범위를 휴리스틱으로
/// 폭 2칸 처리한다(§H-7 — 와이드 이모지 2칸 계산 요구).
fn display_width(text: &str) -> usize {
    text.chars().map(char_width).sum()
}

/// 단일 문자의 표시 폭(1 또는 2)을 휴리스틱으로 판정한다.
///
/// 결합 문자(zero-width)는 0, 이모지/CJK 등 와이드 문자는 2, 나머지는 1.
fn char_width(c: char) -> usize {
    let code = c as u32;
    // Variation Selector / Zero-Width Joiner 등 결합 문자는 폭 0.
    if c == '\u{200d}' || (0xFE00..=0xFE0F).contains(&code) {
        return 0;
    }
    if is_wide(code) {
        2
    } else {
        1
    }
}

/// 코드포인트가 폭 2칸(와이드/이모지)에 해당하는지 휴리스틱으로 판정한다.
fn is_wide(code: u32) -> bool {
    matches!(code,
        0x1100..=0x115F        // Hangul Jamo
        | 0x2600..=0x27BF      // Misc symbols / Dingbats (다수 이모지)
        | 0x2E80..=0x303E      // CJK Radicals ~ punctuation
        | 0x3041..=0x33FF      // Hiragana ~ CJK compat
        | 0x3400..=0x4DBF      // CJK Ext A
        | 0x4E00..=0x9FFF      // CJK Unified
        | 0xA000..=0xA4CF      // Yi
        | 0xAC00..=0xD7A3      // Hangul Syllables
        | 0xF900..=0xFAFF      // CJK Compat Ideographs
        | 0xFE30..=0xFE4F      // CJK Compat Forms
        | 0xFF00..=0xFF60      // Fullwidth Forms
        | 0xFFE0..=0xFFE6
        | 0x1F300..=0x1FAFF    // 이모지 평면(😌🙂😅🥵🔥 포함)
        | 0x20000..=0x3FFFD    // CJK Ext B+
    )
}

/// 글리프 문자에 밴드 틴트를 입힌다(COLOR-ONCE: 글리프에만, 값엔 안 입힘).
///
/// `color_on`이 false면 ANSI 없이 글리프 텍스트만 반환한다. 색상 모드 auto/
/// truecolor/256에 따라 ANSI 시퀀스 형식을 고르고 항상 리셋으로 닫는다(§H-7).
/// BOLD("\x1b[1m")는 절대 쓰지 않는다.
fn tinted(glyph: &str, color: ColorSpec, cfg: &Config, color_on: bool) -> String {
    if !color_on {
        return glyph.to_string();
    }
    format!("{}{glyph}\x1b[0m", ansi_fg(color, cfg))
}

/// 라벨/단위/마커를 dim `label_color`로 칠한다(값엔 적용하지 않는다).
///
/// `color_on`이 false면 ANSI 없이 라벨 텍스트만 반환한다.
fn dim_label(label: &str, cfg: &Config, color_on: bool) -> String {
    if !color_on {
        return label.to_string();
    }
    let color = parse_hex_pub(&cfg.color.label_color).unwrap_or(ColorSpec {
        r: 0x6b,
        g: 0x72,
        b: 0x80,
    });
    format!("{}{label}\x1b[0m", ansi_fg(color, cfg))
}

/// 세그먼트 사이에 들어갈 구분자를 만든다(dim 가운뎃점 " · ").
///
/// `color_on`이 false면 ANSI 없이 구분자 텍스트만 반환한다. 색상 on이면 양옆 공백은
/// 보존하고 가운뎃점 글리프에만 `separator_color`를 입힌다(공백 밝기 유지 불필요).
fn render_separator(cfg: &Config, color_on: bool) -> String {
    let separator = &cfg.color.separator;
    if !color_on {
        return separator.clone();
    }
    let color = separator_spec(cfg);
    format!("{}{separator}\x1b[0m", ansi_fg(color, cfg))
}

/// `separator_color`를 [`ColorSpec`]으로 파싱한다(기본 #3b4048으로 안전 저하).
fn separator_spec(cfg: &Config) -> ColorSpec {
    parse_hex_pub(&cfg.color.separator_color).unwrap_or(ColorSpec {
        r: 0x3b,
        g: 0x40,
        b: 0x48,
    })
}

/// 색상 모드에 맞는 전경색 ANSI 시퀀스를 만든다(truecolor 또는 256색).
///
/// - `truecolor`: `\x1b[38;2;R;G;Bm`.
/// - `256`: 가장 가까운 xterm-256 코드로 `\x1b[38;5;Nm`.
/// - `auto`: `COLORTERM=truecolor`면 truecolor, 아니면 256(§H-7).
fn ansi_fg(color: ColorSpec, cfg: &Config) -> String {
    if use_truecolor(cfg) {
        format!("\x1b[38;2;{};{};{}m", color.r, color.g, color.b)
    } else {
        format!("\x1b[38;5;{}m", nearest_xterm256(color))
    }
}

/// 현재 색상 모드/환경에서 truecolor를 써야 하는지 판정한다.
fn use_truecolor(cfg: &Config) -> bool {
    match cfg.color.mode.as_str() {
        "truecolor" => true,
        "256" => false,
        // auto: COLORTERM=truecolor 또는 24bit일 때만 truecolor.
        _ => std::env::var("COLORTERM")
            .map(|value| value == "truecolor" || value == "24bit")
            .unwrap_or(false),
    }
}

/// RGB를 가장 가까운 xterm-256 색 코드로 근사한다(6×6×6 컬러 큐브 + 그레이스케일).
fn nearest_xterm256(color: ColorSpec) -> u8 {
    // 6단계 큐브로 각 채널을 양자화(0,95,135,175,215,255).
    let cube = |value: u8| -> (u8, u8) {
        let steps = [0u8, 95, 135, 175, 215, 255];
        let mut best_index = 0usize;
        let mut best_distance = u16::MAX;
        for (index, &step) in steps.iter().enumerate() {
            let distance = (step as i16 - value as i16).unsigned_abs();
            if distance < best_distance {
                best_distance = distance;
                best_index = index;
            }
        }
        (best_index as u8, steps[best_index])
    };

    let (ri, _) = cube(color.r);
    let (gi, _) = cube(color.g);
    let (bi, _) = cube(color.b);
    16 + 36 * ri + 6 * gi + bi
}

// CONTRACT: signature is frozen — implement body only, do not change this signature
/// understatus 자체 세그먼트와 체인 자식 출력을 설정된 순서로 합성한다.
///
/// # 인자
/// - `self_segment`: [`render`]가 만든 understatus 자체 세그먼트.
/// - `chain_output`: 체인 자식 stdout(없으면 빈 문자열).
/// - `order`: `"self_first"` | `"chain_first"`(기본 self_first).
///
/// # 반환
/// 합성된 한 줄(개행 없음). 체인 출력이 비었으면 자체 세그먼트만 반환한다(AC8).
/// HUD seam이 필요하면 [`compose_with_seam`]을 사용한다(이 함수는 공백 1칸 합성).
///
/// 시그니처는 계약상 고정이라 보존한다. 런타임 경로는 [`compose_with_seam`]을 쓰지만
/// 공개 API/테스트가 이 함수를 참조하므로 dead_code 경고를 명시적으로 허용한다.
#[cfg_attr(not(test), allow(dead_code))]
pub fn compose(self_segment: &str, chain_output: &str, order: &str) -> String {
    compose_internal(self_segment, chain_output, order, " ")
}

/// [`compose`]에 dim HUD seam("│")을 끼워 소유권 경계를 표시한 변형이다.
///
/// # 인자
/// - `self_segment`/`chain_output`/`order`: [`compose`]와 동일.
/// - `cfg`: `color.hud_seam`(기본 "│") + `color.separator_color`(seam 색).
/// - `color_on`: 색상 활성 여부(NO_COLOR/mode none이면 false → ANSI 없음).
///
/// # 반환
/// `self … │ … chain`(order=chain_first면 `chain … │ … self`). 체인 출력이 비면
/// seam 없이 자체 세그먼트만 반환한다(후행 seam 금지, AC8).
pub fn compose_with_seam(
    self_segment: &str,
    chain_output: &str,
    order: &str,
    cfg: &Config,
    color_on: bool,
) -> String {
    // 체인 출력이 비면 seam 없이 자체 세그먼트만(후행 seam 금지).
    if chain_output.trim_end_matches(['\n', '\r']).is_empty() {
        return self_segment.to_string();
    }
    let seam = render_seam(cfg, color_on);
    let joiner = format!(" {seam} ");
    compose_internal(self_segment, chain_output, order, &joiner)
}

/// self/chain을 주어진 joiner로 합성하는 공통 내부 헬퍼.
///
/// 체인 출력 끝 개행은 한 줄 합성을 위해 제거하고, 비면 자체 세그먼트만 반환한다.
fn compose_internal(self_segment: &str, chain_output: &str, order: &str, joiner: &str) -> String {
    let chain = chain_output.trim_end_matches(['\n', '\r']);
    if chain.is_empty() {
        return self_segment.to_string();
    }
    match order {
        "chain_first" => format!("{chain}{joiner}{self_segment}"),
        // 기본 self_first.
        _ => format!("{self_segment}{joiner}{chain}"),
    }
}

/// HUD seam 글리프("│")를 dim `separator_color`로 렌더한다(색상 off면 글리프만).
fn render_seam(cfg: &Config, color_on: bool) -> String {
    let seam = &cfg.color.hud_seam;
    if !color_on {
        return seam.clone();
    }
    format!("{}{seam}\x1b[0m", ansi_fg(separator_spec(cfg), cfg))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::claude::ClaudeInput;
    use crate::config::Config;
    use crate::system::{BatteryInfo, NetThroughput, SystemSnapshot};

    /// 테스트용 고정 Claude 세션 정보(모델/컨텍스트/git/cwd/cost).
    fn sample_input() -> ClaudeInput {
        ClaudeInput {
            model_display_name: Some("Opus".to_string()),
            context_used_percentage: Some(42.0),
            context_fallback_percentage: None,
            cwd: Some("/Users/dev/proj".to_string()),
            git_branch: Some("main".to_string()),
            cost_usd: Some(1.23),
            session_id: Some("sess-1".to_string()),
            session_label: None,
            codex: None,
        }
    }

    /// 테스트용 고정 시스템 스냅샷(P2 지표는 기본 None).
    fn sample_snap(cpu: f64) -> SystemSnapshot {
        SystemSnapshot {
            cpu_percent: cpu,
            mem_percent: 55.0,
            battery: None,
            disk_percent: None,
            net: None,
        }
    }

    /// 환경변수(NO_COLOR/COLORTERM)를 만지는 테스트들의 직렬화를 위한 프로세스 전역 락.
    ///
    /// `std::env::set_var`는 프로세스 전역 상태라 병렬 테스트에서 경합할 수 있으므로
    /// env를 변경하는 테스트는 이 락을 잡아 직렬 실행한다.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn render_no_color_env_has_no_escape_bytes() {
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        // NO_COLOR이 설정되면 truecolor 모드라도 ANSI를 일절 출력하지 않아야 한다.
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        // SAFETY: ENV_LOCK으로 직렬화된 단일 스레드 구간에서만 env를 변경한다.
        unsafe { std::env::set_var("NO_COLOR", "1") };
        let line = render(&sample_input(), &sample_snap(95.0), &cfg, 1_000, true);
        unsafe { std::env::remove_var("NO_COLOR") };
        assert!(
            !line.contains('\x1b'),
            "NO_COLOR 설정 시 ANSI ESC 바이트가 없어야 함: {line:?}"
        );
        assert!(line.contains("95%"));
    }

    #[test]
    fn render_no_color_mode_has_no_escape_bytes() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let line = render(&sample_input(), &sample_snap(95.0), &cfg, 1_000, true);
        assert!(
            !line.contains('\x1b'),
            "mode=none이면 ANSI ESC 바이트가 없어야 함: {line:?}"
        );
        // 핵심 텍스트는 그대로 존재.
        assert!(line.contains("95%"));
    }

    #[test]
    fn render_has_no_bold_escape() {
        // CALM: understatus 자체 세그먼트에 BOLD("\x1b[1m")가 절대 없어야 한다.
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        let mut snap = sample_snap(95.0);
        snap.battery = Some(BatteryInfo {
            percent: 80.0,
            is_charging: false,
        });
        snap.disk_percent = Some(63.0);
        snap.net = Some(NetThroughput {
            rx_bps: 2048.0,
            tx_bps: 512.0,
        });
        // 펄스 ON/OFF 양쪽 모두 BOLD가 없어야 한다.
        for pulse_on in [false, true] {
            let line = render(&sample_input(), &snap, &cfg, 1_000, pulse_on);
            assert!(
                !line.contains("\x1b[1m"),
                "BOLD 이스케이프(\\x1b[1m)가 없어야 함(pulse_on={pulse_on}): {line:?}"
            );
        }
    }

    #[test]
    fn render_truecolor_has_escape_bytes() {
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        // NO_COLOR이 다른 테스트에서 새지 않도록 보장.
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        let line = render(&sample_input(), &sample_snap(95.0), &cfg, 1_000, true);
        assert!(
            line.contains('\x1b'),
            "truecolor 모드는 ANSI ESC 바이트를 포함해야 함: {line:?}"
        );
        // truecolor 시퀀스 형식 확인.
        assert!(
            line.contains("\x1b[38;2;"),
            "truecolor 38;2 시퀀스 필요: {line:?}"
        );
        // CALM: 색은 부분별로 입히므로 각 색 조각은 리셋으로 닫힌다(라인 끝은
        // 색 없는 값일 수 있어 더 이상 \x1b[0m으로 끝나지 않는다 — COLOR-ONCE).
        assert!(
            line.contains("\x1b[0m"),
            "색을 입힌 조각은 리셋으로 닫혀야 함: {line:?}"
        );
        // 마지막 가시 텍스트는 색 없는 값($1.23)이라 ESC로 끝나지 않아야 한다.
        assert!(
            line.ends_with("1.23"),
            "마지막 값은 색 없이 출력되어야 함: {line:?}"
        );
    }

    #[test]
    fn render_color_once_value_has_no_escape() {
        // COLOR-ONCE: 글리프엔 틴트가 붙지만 CPU% 값엔 ANSI가 붙지 않는다.
        // 밴드2(58%) truecolor 출력에서 "▄"는 색이 붙고 "58%"는 색이 안 붙어야 한다.
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        // 글리프 틴트는 밴드2(#86a0b4) truecolor 시퀀스로 시작해야 한다.
        let line = render(&sample_input(), &sample_snap(58.0), &cfg, 0, false);
        let expected_glyph = "\x1b[38;2;134;160;180m▄\x1b[0m 58%";
        assert!(
            line.starts_with(expected_glyph),
            "글리프엔 틴트, 값(58%)엔 색 없음: {line:?}"
        );
        // 값 바로 앞뒤에 색 escape가 끼지 않음(글리프 리셋 직후 ' 58%').
        assert!(
            line.contains("\x1b[0m 58%"),
            "CPU% 값은 리셋 직후 색 없이 출력: {line:?}"
        );
    }

    #[test]
    fn render_uses_dim_middot_separator() {
        // 세그먼트 구분자가 dim 가운뎃점 " · "(separator_color)여야 한다.
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        let line = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        // separator_color(#3b4048 = 59,64,72) + 가운뎃점.
        assert!(
            line.contains("\x1b[38;2;59;64;72m · \x1b[0m"),
            "dim 가운뎃점 구분자 필요: {line:?}"
        );
        // 옛 공백 단독 구분자(이모지 시절)는 더 이상 쓰지 않는다.
        assert!(
            !line.contains("% mem"),
            "구분자는 가운뎃점이어야 함: {line:?}"
        );
    }

    #[test]
    fn render_labels_are_dim_values_are_not() {
        // 라벨(mem)엔 label_color(#6b7280 = 107,114,128) dim, 값(55%)엔 색 없음.
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        let line = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert!(
            line.contains("\x1b[38;2;107;114;128mmem\x1b[0m 55%"),
            "라벨 dim + 값 색 없음: {line:?}"
        );
    }

    #[test]
    fn render_band_snapshots_glyph_and_tint() {
        // 5개 밴드 모두 글리프+틴트가 결정적으로 드러나도록 truecolor 스냅샷 검증(라이브 CPU 무관).
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        // (cpu%, 기대 글리프, 기대 밴드 틴트 truecolor 프리픽스).
        let cases = [
            (10.0, "", "\x1b[38;2;90;104;120m"),  // idle  #5a6878
            (30.0, "", "\x1b[38;2;109;130;150m"), // low   #6d8296
            (58.0, "", "\x1b[38;2;134;160;180m"), // mid   #86a0b4
            (80.0, "", "\x1b[38;2;159;191;206m"), // high  #9fbfce
            (95.0, "", "\x1b[38;2;184;120;72m"),  // crit  #b87848 (warm)
        ];
        for (cpu, glyph, tint_prefix) in cases {
            // 펄스 OFF로 정적 밴드 틴트를 확인(crit도 pulse_on=false면 정적 틴트).
            let line = render(&sample_input(), &sample_snap(cpu), &cfg, 0, false);
            let expected = format!("{tint_prefix}{glyph}\x1b[0m {cpu:.0}%");
            assert!(
                line.starts_with(&expected),
                "밴드 {cpu}%: 글리프 {glyph} + 틴트 {tint_prefix:?} 필요\n  got: {line:?}"
            );
        }
    }

    #[test]
    fn render_crit_pulse_breathes_terracotta() {
        // crit 밴드 + pulse_on이면 글리프 틴트가 테라코타 숨쉬기로 칠해진다(글리프 모양 고정 ◆).
        let _guard = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        unsafe { std::env::remove_var("NO_COLOR") };
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        // wave=0(phase=0.75, 22500ms) → high 테라코타 #b87848.
        let high = render(&sample_input(), &sample_snap(95.0), &cfg, 22_500, true);
        assert!(
            high.starts_with("\x1b[38;2;184;120;72m◆\x1b[0m 95%"),
            "펄스 high 끝점 테라코타 + 고정 글리프 ◆: {high:?}"
        );
        // wave=1(phase=0.25, 7500ms) → low dim 테라코타 #7a5030.
        let low = render(&sample_input(), &sample_snap(95.0), &cfg, 7_500, true);
        assert!(
            low.starts_with("\x1b[38;2;122;80;48m◆\x1b[0m 95%"),
            "펄스 low 끝점 dim 테라코타 + 고정 글리프 ◆: {low:?}"
        );
    }

    #[test]
    fn render_omits_context_when_null() {
        let mut input = sample_input();
        input.context_used_percentage = None;
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let line = render(&input, &sample_snap(10.0), &cfg, 0, false);
        assert!(
            !line.contains("ctx"),
            "context null이면 ctx 세그먼트 생략: {line:?}"
        );
    }

    #[test]
    fn render_enforces_max_width_drops_low_priority() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        cfg.display.max_width = 14; // 매우 좁게 → 저우선(cost 등) 제거
        let line = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        // 최저 우선순위인 cost($)가 가장 먼저 버려진다.
        assert!(
            !line.contains('$'),
            "max_width 초과 시 cost 세그먼트 제거: {line:?}"
        );
        // 핵심 CPU 세그먼트는 유지.
        assert!(line.contains("10%"), "핵심 CPU 세그먼트는 유지: {line:?}");
    }

    #[test]
    fn render_shows_session_label_when_some() {
        // session_label=Some("codex/%3")면 출력에 "codex/%3"가 cwd("proj") 앞에 표시된다.
        let mut input = sample_input();
        input.session_label = Some("codex/%3".to_string());
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let line = render(&input, &sample_snap(10.0), &cfg, 0, false);
        assert!(
            line.contains("codex/%3"),
            "session_label이 있으면 표시되어야 함: {line:?}"
        );
    }

    #[test]
    fn render_omits_session_label_when_none() {
        // session_label=None(Claude 경로 등)이면 표시되지 않는다(기존 출력 보존).
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let line = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert!(
            !line.contains('/'),
            "session_label None이면 세션 세그먼트 없음(cwd는 basename만): {line:?}"
        );
    }

    #[test]
    fn render_omits_session_label_when_toggle_off() {
        // show_session=false면 session_label이 있어도 표시하지 않는다.
        let mut input = sample_input();
        input.session_label = Some("codex/%3".to_string());
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        cfg.display.show_session = false;
        let line = render(&input, &sample_snap(10.0), &cfg, 0, false);
        assert!(
            !line.contains("codex/%3"),
            "show_session=false면 라벨이 있어도 생략: {line:?}"
        );
    }

    #[test]
    fn compose_self_first() {
        assert_eq!(compose("SELF", "CHAIN", "self_first"), "SELF CHAIN");
    }

    #[test]
    fn compose_chain_first() {
        assert_eq!(compose("SELF", "CHAIN", "chain_first"), "CHAIN SELF");
    }

    #[test]
    fn compose_empty_chain_returns_self_only() {
        assert_eq!(compose("SELF", "", "self_first"), "SELF");
        assert_eq!(compose("SELF", "\n", "self_first"), "SELF");
    }

    #[test]
    fn compose_with_seam_inserts_dim_seam() {
        // 체인 있음 + 색상 off → plain "│" seam이 양옆 공백과 함께 들어간다(self_first).
        let cfg = Config::default();
        assert_eq!(
            compose_with_seam("SELF", "CHAIN", "self_first", &cfg, false),
            "SELF │ CHAIN"
        );
        // chain_first면 순서가 뒤바뀐다.
        assert_eq!(
            compose_with_seam("SELF", "CHAIN", "chain_first", &cfg, false),
            "CHAIN │ SELF"
        );
    }

    #[test]
    fn compose_with_seam_colors_seam_when_color_on() {
        // 색상 on이면 seam("│")이 separator_color(#3b4048 = 59,64,72)로 칠해진다.
        let mut cfg = Config::default();
        cfg.color.mode = "truecolor".to_string();
        let line = compose_with_seam("SELF", "CHAIN", "self_first", &cfg, true);
        assert!(
            line.contains("\x1b[38;2;59;64;72m│\x1b[0m"),
            "dim seam 필요: {line:?}"
        );
    }

    #[test]
    fn compose_with_seam_no_trailing_seam_when_empty_chain() {
        // 체인 출력이 비면 seam 없이 자체 세그먼트만(후행 seam 금지, AC8).
        let cfg = Config::default();
        assert_eq!(
            compose_with_seam("SELF", "", "self_first", &cfg, true),
            "SELF"
        );
        assert_eq!(
            compose_with_seam("SELF", "\n", "self_first", &cfg, true),
            "SELF"
        );
    }

    #[test]
    fn battery_marker_states() {
        // 충전 중 → bat+(잔량 무관).
        assert_eq!(battery_marker(15.0, true), "bat+");
        assert_eq!(battery_marker(95.0, true), "bat+");
        // 비충전 + 저잔량(≤20%) → bat!.
        assert_eq!(battery_marker(20.0, false), "bat!");
        assert_eq!(battery_marker(5.0, false), "bat!");
        // 비충전 + 충분 → bat.
        assert_eq!(battery_marker(21.0, false), "bat");
        assert_eq!(battery_marker(80.0, false), "bat");
    }

    #[test]
    fn format_bytes_per_sec_units() {
        // 1024 미만 → B/s, 1024~1MB → KB/s, ≥1MB → MB/s.
        assert_eq!(format_bytes_per_sec(512.0), "512B/s");
        assert_eq!(format_bytes_per_sec(2048.0), "2KB/s");
        assert_eq!(format_bytes_per_sec(3.0 * 1024.0 * 1024.0), "3.0MB/s");
        // 음수/NaN은 0B/s로 안전 저하.
        assert_eq!(format_bytes_per_sec(-1.0), "0B/s");
        assert_eq!(format_bytes_per_sec(f64::NAN), "0B/s");
    }

    #[test]
    fn render_shows_battery_when_some_and_toggle_on() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let mut snap = sample_snap(10.0);
        snap.battery = Some(BatteryInfo {
            percent: 75.0,
            is_charging: true,
        });
        let line = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(line.contains("bat+"), "충전 중 배터리 마커 표시: {line:?}");
        assert!(line.contains("75%"), "배터리 잔량 표시: {line:?}");
    }

    #[test]
    fn render_omits_battery_when_none() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        // battery=None(데스크톱) → 세그먼트 없음.
        let line = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert!(!line.contains("bat"), "배터리 None이면 생략: {line:?}");
    }

    #[test]
    fn render_omits_battery_when_toggle_off() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        cfg.display.show_battery = false;
        let mut snap = sample_snap(10.0);
        snap.battery = Some(BatteryInfo {
            percent: 50.0,
            is_charging: false,
        });
        let line = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(
            !line.contains("bat"),
            "show_battery=false면 값이 있어도 생략: {line:?}"
        );
    }

    #[test]
    fn render_shows_disk_when_some_and_toggle_on() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let mut snap = sample_snap(10.0);
        snap.disk_percent = Some(63.0);
        let line = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(line.contains("disk"), "디스크 라벨 표시: {line:?}");
        assert!(line.contains("63%"), "디스크 사용률 표시: {line:?}");
    }

    #[test]
    fn render_omits_disk_when_none_or_toggle_off() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        // None → 생략.
        let line_none = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert!(
            !line_none.contains("disk"),
            "disk None이면 생략: {line_none:?}"
        );
        // toggle off → 생략.
        cfg.display.show_disk = false;
        let mut snap = sample_snap(10.0);
        snap.disk_percent = Some(63.0);
        let line_off = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(
            !line_off.contains("disk"),
            "show_disk=false면 생략: {line_off:?}"
        );
    }

    #[test]
    fn render_shows_network_when_some_and_toggle_on() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let mut snap = sample_snap(10.0);
        snap.net = Some(NetThroughput {
            rx_bps: 2048.0,
            tx_bps: 512.0,
        });
        let line = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(line.contains("↓2KB/s"), "수신 속도 표시: {line:?}");
        assert!(line.contains("↑512B/s"), "송신 속도 표시: {line:?}");
    }

    #[test]
    fn render_omits_network_when_none_or_toggle_off() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        // None(첫 렌더) → 생략.
        let line_none = render(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert!(!line_none.contains(''), "net None이면 생략: {line_none:?}");
        // toggle off → 생략.
        cfg.display.show_network = false;
        let mut snap = sample_snap(10.0);
        snap.net = Some(NetThroughput {
            rx_bps: 2048.0,
            tx_bps: 512.0,
        });
        let line_off = render(&sample_input(), &snap, &cfg, 0, false);
        assert!(
            !line_off.contains(''),
            "show_network=false면 생략: {line_off:?}"
        );
    }

    #[test]
    fn display_width_counts_wide_glyph_as_two() {
        // 와이드 이모지 = 폭 2, CALM 글리프(◆ ○)/ASCII는 폭 1.
        assert_eq!(display_width("🔥"), 2);
        assert_eq!(display_width("a"), 1);
        assert_eq!(display_width("🔥a"), 3);
        // 가운뎃점 구분자 " · "는 폭 3(공백1 + 중점1 + 공백1).
        assert_eq!(display_width(" · "), 3);
    }

    // ===== cmux 네이티브 status pills(C1: PillMeta + 색맵 + to_cmux_pills) =====

    /// 한 pill을 key로 찾는 헬퍼(순서 무관 단언).
    fn find_pill<'a>(out: &'a CmuxStatusOutput, key: &str) -> Option<&'a Pill> {
        out.pills.iter().find(|p| p.key == key)
    }

    /// 색 문자열이 `#RRGGBB` 정규식(6 hex 대문자/숫자)인지 검사한다.
    fn is_rrggbb(color: &str) -> bool {
        let bytes = color.as_bytes();
        color.len() == 7 && bytes[0] == b'#' && bytes[1..].iter().all(|b| b.is_ascii_hexdigit())
    }

    /// color_to_hex: ansi_fg truecolor 산식과 동일 채널 소스를 써서 #RRGGBB(대문자)로 출력한다.
    #[test]
    fn color_to_hex_formats_uppercase_rrggbb() {
        assert_eq!(
            color_to_hex(ColorSpec {
                r: 0x7a,
                g: 0xa2,
                b: 0xf7
            }),
            "#7AA2F7"
        );
        // 0 패딩 확인(한 자리 채널도 두 자리로).
        assert_eq!(color_to_hex(ColorSpec { r: 0, g: 5, b: 255 }), "#0005FF");
    }

    /// AC4(가용 집합 + git pill): enrich-성공 상당(model+ctx+cpu+mem+git 소스 가용) →
    /// pill key 집합 {cpu,ctx,git,mem,model}(5). git pill 값/색/아이콘/우선순위도 함께 고정한다.
    #[test]
    fn to_cmux_pills_enriched_has_five_keys() {
        // sample_input: model=Some, ctx=Some(42.0), git_branch=Some("main"). sample_snap: cpu/mem. → 5 pill.
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let out = render_cmux_pills(&sample_input(), &sample_snap(58.0), &cfg, 0, false);
        let mut keys: Vec<&str> = out.pills.iter().map(|p| p.key.as_str()).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            vec!["cpu", "ctx", "git", "mem", "model"],
            "enrich-성공 5 pill(git 포함)"
        );
        // git pill: bare 브랜치명 + git 주황 + git-branch 아이콘 + priority 40(AC4 positive 앵커).
        let git = find_pill(&out, "git").expect("git pill");
        assert_eq!(git.value, "main", "git pill 값은 bare 브랜치명");
        assert_eq!(
            git.color.as_deref(),
            Some(color_to_hex(pill_git_color()).as_str()),
            "git pill 색은 pill_git_color()"
        );
        assert_eq!(
            git.icon.as_deref(),
            Some("git-branch"),
            "git pill 아이콘은 git-branch"
        );
        assert_eq!(
            git.priority, 40,
            "git pill priority는 40(oneline 세그먼트와 일치)"
        );
    }

    /// AC2(가용 집합): enrich-실패 상당(ctx None, model bare "codex") → pill key 집합 {model,cpu,mem}(3, ctx 부재).
    #[test]
    fn to_cmux_pills_unenriched_has_three_keys_no_ctx() {
        let mut input = sample_input();
        input.context_used_percentage = None; // enrich 실패 → ctx 없음.
        input.git_branch = None; // git 무관(이 테스트 의도 = ctx-skip + bare model).
        input.model_display_name = Some("codex".to_string()); // bare agent 토큰 폴백.
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let out = render_cmux_pills(&input, &sample_snap(58.0), &cfg, 0, false);
        let mut keys: Vec<&str> = out.pills.iter().map(|p| p.key.as_str()).collect();
        keys.sort_unstable();
        // **2가 아니라 3**: ctx만 None-skip, model(bare)+cpu+mem은 가용.
        assert_eq!(
            keys,
            vec!["cpu", "mem", "model"],
            "enrich-실패 3 pill(ctx 부재)"
        );
        assert!(find_pill(&out, "ctx").is_none(), "ctx pill 부재");
        // bare "codex"가 그대로 model pill 값으로 표시(oneline과 동일).
        assert_eq!(find_pill(&out, "model").unwrap().value, "codex");
    }

    /// AC3(색): 각 pill.color는 #RRGGBB 또는 null. cpu.color는 color_to_hex(band_tint(..))와 일치.
    #[test]
    fn to_cmux_pills_colors_are_rrggbb_and_cpu_uses_band_tint() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let cpu_percent = 58.0;
        let out = render_cmux_pills(&sample_input(), &sample_snap(cpu_percent), &cfg, 0, false);
        for pill in &out.pills {
            if let Some(color) = &pill.color {
                assert!(
                    is_rrggbb(color),
                    "pill {} 색 #RRGGBB 위반: {color:?}",
                    pill.key
                );
            }
        }
        // cpu.color == color_to_hex(band_tint(band_index(cpu, cfg), cfg)) — 기존 글리프 밴드 색 재사용.
        let expected_cpu = color_to_hex(band_tint(band_index(cpu_percent, &cfg), &cfg));
        assert_eq!(
            find_pill(&out, "cpu").unwrap().color.as_deref(),
            Some(expected_cpu.as_str()),
            "cpu pill 색은 band_tint 재사용"
        );
    }

    /// AC4(ctx 양자화): ctx 41.6% → pill "ctx 42%"(정수% 반올림). progress는 더 이상 직렬화하지 않는다.
    #[test]
    fn to_cmux_pills_ctx_quantizes_to_integer_percent() {
        let mut input = sample_input();
        input.context_used_percentage = Some(41.6);
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let out = render_cmux_pills(&input, &sample_snap(10.0), &cfg, 0, false);
        let ctx = find_pill(&out, "ctx").expect("ctx pill");
        assert_eq!(ctx.value, "ctx 42%", "41.6% → 반올림 42%");
    }

    /// ctx 클램프: >100/음수/NaN 입력도 0..=100 정수로 안전 수렴(pill 텍스트 동일 소스).
    #[test]
    fn to_cmux_pills_ctx_clamps_out_of_range() {
        let cases = [
            (137.0_f64, "ctx 100%"), // 100 초과 → 상한 클램프.
            (100.4, "ctx 100%"),     // 반올림 후 상한.
            (-5.0, "ctx 0%"),        // 음수 → 0.
            (f64::NAN, "ctx 0%"),    // NaN → 0(무패닉).
        ];
        for (input_pct, expected) in cases {
            let mut input = sample_input();
            input.context_used_percentage = Some(input_pct);
            let mut cfg = Config::default();
            cfg.color.mode = "none".to_string();
            let out = render_cmux_pills(&input, &sample_snap(10.0), &cfg, 0, false);
            let ctx = find_pill(&out, "ctx").expect("ctx pill");
            assert_eq!(ctx.value, expected, "{input_pct} → {expected}");
        }
    }

    /// AC5(동기화): pill.value가 해당 세그먼트 plain 값과 일치(model/cpu/mem).
    ///
    /// model: pill.value == plain(둘 다 model 문자열). cpu/mem: 값 부분(NN%)이 plain의 NN%와 동일.
    #[test]
    fn to_cmux_pills_values_match_plain_source() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let snap = sample_snap(58.0); // cpu 58% → "58%", mem 55% → "55%".
                                      // collect_segments를 직접 호출해 plain과 pill을 같은 수집에서 대조한다(3중-소스 동기화).
        let segments = collect_segments(&sample_input(), &snap, &cfg, 0, false, false);
        for segment in &segments {
            let Some(meta) = segment.pill.as_ref() else {
                continue;
            };
            match meta.id {
                // model: pill 값 == plain(둘 다 model 문자열 그대로).
                "model" => assert_eq!(meta.value, segment.plain, "model pill==plain"),
                // cpu: plain="<glyph> 58%", pill="cpu 58%" → 값 부분(58%)이 plain에 포함.
                "cpu" => {
                    let value_part = meta.value.trim_start_matches("cpu ");
                    assert!(
                        segment.plain.ends_with(value_part),
                        "cpu pill 값 부분이 plain과 동기화: pill={:?} plain={:?}",
                        meta.value,
                        segment.plain
                    );
                }
                // mem: plain="mem 55%" == pill="mem 55%".
                "mem" => assert_eq!(meta.value, segment.plain, "mem pill==plain"),
                // ctx: plain="ctx 42%"(정수%), pill="ctx 42%"(정수%) → 동일 양자화.
                "ctx" => assert_eq!(meta.value, segment.plain, "ctx pill==plain(정수% 동기화)"),
                _ => {}
            }
        }
    }

    /// to_cmux_pills 스키마 봉투(schema/version) 고정.
    #[test]
    fn to_cmux_pills_schema_envelope() {
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let out = render_cmux_pills(&sample_input(), &sample_snap(10.0), &cfg, 0, false);
        assert_eq!(out.schema, "cmux-status");
        assert_eq!(out.version, 1);
        // 직렬화가 유효 JSON 1줄(개행 없음).
        let json = serde_json::to_string(&out).expect("직렬화");
        assert!(!json.contains('\n'), "단일 줄 JSON: {json:?}");
        assert!(json.contains("\"schema\":\"cmux-status\""));
    }

    /// 소스 없는 세그먼트(None)는 pill 미부착 → 수집에서 제외(None-skip).
    #[test]
    fn to_cmux_pills_skips_pillless_segments() {
        // show_model=false면 model 세그먼트 자체가 없고, 다른 세그먼트(cwd 등)는 pill:None.
        let mut input = sample_input();
        input.model_display_name = None; // model 세그먼트 없음.
        input.context_used_percentage = None; // ctx 없음.
        input.git_branch = None; // git pill 무관(이 테스트 의도 = pill:None 세그먼트 제외).
        let mut cfg = Config::default();
        cfg.color.mode = "none".to_string();
        let out = render_cmux_pills(&input, &sample_snap(10.0), &cfg, 0, false);
        // cwd 세그먼트는 pill:None이라 수집 안 됨 → cpu/mem만.
        let mut keys: Vec<&str> = out.pills.iter().map(|p| p.key.as_str()).collect();
        keys.sort_unstable();
        assert_eq!(keys, vec!["cpu", "mem"], "pill 없는 세그먼트는 제외");
    }
}