helix-im 0.1.28

基于 Helix Core 的确定性 MessageV3 IM 业务模块
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! Channel-list render-ready projection.
//!
//! Storage scans use the SQLite column names from `channel` (mostly snake_case),
//! while MessageV3 binds the camelCase channel contract. Keep this conversion at
//! the Helix boundary so every channel-list producer shares the same projection.

use serde_json::{json, Map, Value};

/// Pick the first channel field that exists, retaining its original JSON type.
fn pick(row: &Value, keys: &[&str]) -> Value {
    keys.iter()
        .find_map(|key| row.get(*key).cloned())
        .unwrap_or(Value::Null)
}

/// Parse a JSON-backed channel field without turning an invalid value into a raw string.
fn json_field(row: &Value, keys: &[&str], fallback: Value) -> Value {
    match pick(row, keys) {
        Value::String(raw) => serde_json::from_str::<Value>(&raw)
            .ok()
            .filter(|value| !value.is_null())
            .unwrap_or(fallback),
        Value::Null => fallback,
        value => value,
    }
}

/// Parse JSON-backed data but retain legitimate scalar channel values such as `IGNORE` or source names.
fn json_field_or_value(row: &Value, keys: &[&str], fallback: Value) -> Value {
    match pick(row, keys) {
        Value::String(raw) if raw.is_empty() => fallback,
        Value::String(raw) => {
            serde_json::from_str::<Value>(&raw).unwrap_or_else(|_| Value::String(raw))
        }
        Value::Null => fallback,
        value => value,
    }
}

/// Shape the persisted last-post object with the same message contract as the timeline.
fn shape_last_post(value: Value) -> Value {
    match value {
        Value::Object(_) => super::core::shape_row(&value, ""),
        _ => json!({}),
    }
}

/// Add one snake/camel alias to the render-ready channel object.
fn insert_alias(output: &mut Map<String, Value>, row: &Value, name: &str, keys: &[&str]) {
    let value = pick(row, keys);
    if !value.is_null() {
        output.insert(name.to_string(), value);
    }
}

/// Keep persisted urgent counters non-negative while preserving ordinary JSON values.
fn non_negative_count(value: Value) -> Value {
    match &value {
        Value::Number(number) if number.as_f64().is_some_and(|value| value < 0.0) => Value::from(0),
        Value::String(raw) if raw.trim().parse::<f64>().is_ok_and(|value| value < 0.0) => {
            Value::from(0)
        }
        _ => value,
    }
}

/// Write the urgent counter under every existing alias so legacy rows cannot leak a negative value.
fn insert_non_negative_count_alias(
    output: &mut Map<String, Value>,
    row: &Value,
    name: &str,
    keys: &[&str],
) {
    let value = non_negative_count(pick(row, keys));
    if value.is_null() {
        return;
    }
    output.insert(name.to_string(), value.clone());
    for key in keys {
        if output.contains_key(*key) {
            output.insert((*key).to_string(), value.clone());
        }
    }
}

/// Convert persisted SQLite boolean integers into the render-ready JSON boolean contract.
fn insert_bool_alias(output: &mut Map<String, Value>, row: &Value, name: &str, keys: &[&str]) {
    let value = match pick(row, keys) {
        Value::Bool(value) => Some(value),
        Value::Number(value) => value.as_i64().map(|value| value != 0),
        _ => None,
    };
    if let Some(value) = value {
        output.insert(name.to_string(), Value::Bool(value));
    }
}

/// Read a persisted capability without accepting stringly-typed authority values.
fn persisted_bool(row: &Value, keys: &[&str]) -> Option<bool> {
    let mut parsed = None;
    for key in keys {
        let Some(value) = row.get(*key) else {
            continue;
        };
        let Some(current) = (match value {
            Value::Bool(value) => Some(*value),
            Value::Number(value) => match value.as_i64() {
                Some(0) => Some(false),
                Some(1) => Some(true),
                _ => None,
            },
            _ => None,
        }) else {
            // An invalid alias is an authority conflict, never a reason to trust another alias.
            return None;
        };
        if parsed.is_some_and(|previous| previous != current) {
            return None;
        }
        parsed = Some(current);
    }
    parsed
}

/// Read a persisted role and normalize Go/Helix owner/admin aliases for capability checks.
fn persisted_role(row: &Value) -> Option<String> {
    row.get("role")
        .and_then(Value::as_str)
        .map(str::trim)
        .map(str::to_ascii_uppercase)
        .and_then(|role| {
            let canonical = match role.as_str() {
                "OWNER" | "CREATOR" => "CREATOR",
                "ADMIN" | "MANAGER" | "MANGER" => "MANAGER",
                "MEMBER" => "MEMBER",
                "BOSS" => "BOSS",
                _ => return None,
            };
            Some(canonical.to_string())
        })
}

/// Read a persisted permission threshold and fail closed for invalid values.
fn persisted_role_value(row: &Value, keys: &[&str]) -> Option<String> {
    let mut parsed = None;
    for key in keys {
        let Some(value) = row.get(*key).and_then(Value::as_str) else {
            if row.get(*key).is_some() {
                return None;
            }
            continue;
        };
        let normalized = value.trim().to_ascii_uppercase();
        if !matches!(
            normalized.as_str(),
            "CREATOR" | "MANAGER" | "MEMBER" | "BOSS"
        ) {
            return None;
        }
        if parsed
            .as_deref()
            .is_some_and(|previous| previous != normalized)
        {
            return None;
        }
        parsed = Some(normalized);
    }
    parsed
}

/// Compare role thresholds using the Go ordering: BOSS, CREATOR, MANAGER, MEMBER.
fn role_at_or_above(role: Option<&str>, required: Option<&str>) -> bool {
    let role_level = match role {
        Some("BOSS") => 0,
        Some("CREATOR") => 1,
        Some("MANAGER") => 2,
        Some("MEMBER") => 3,
        _ => return false,
    };
    let required_level = match required {
        Some("BOSS") => 0,
        Some("CREATOR") => 1,
        Some("MANAGER") => 2,
        Some("MEMBER") => 3,
        _ => return false,
    };
    role_level <= required_level
}

/// Derive a threshold capability while distinguishing a missing policy from an invalid one.
fn derived_threshold_capability(row: &Value, role: Option<&str>, keys: &[&str]) -> bool {
    let required = persisted_role_value(row, keys);
    if required.is_some() {
        return role_at_or_above(role, required.as_deref());
    }
    // A role-readback row can omit thresholds when the channel row is unavailable; only the
    // canonical owner may safely default to true because it is above every valid gate.
    !keys.iter().any(|key| row.get(*key).is_some()) && role == Some("CREATOR")
}

/// Project absolute settings/member capabilities, preserving persisted Go fields when present.
fn insert_viewer_capabilities(output: &mut Map<String, Value>, row: &Value) {
    let role = persisted_role(row);
    let is_open = matches!(
        pick(row, &["type"]),
        Value::String(ref value) if value.eq_ignore_ascii_case("O")
    );
    let admin_role = matches!(role.as_deref(), Some("CREATOR" | "MANAGER"))
        || (is_open && matches!(role.as_deref(), Some("BOSS")));
    let change_role = matches!(role.as_deref(), Some("CREATOR"))
        || (is_open && matches!(role.as_deref(), Some("BOSS")));
    let derived_settings = admin_role;
    let derived_members = admin_role;
    let derived_mention = derived_threshold_capability(
        row,
        role.as_deref(),
        &["mention_permission", "mentionPermission"],
    );
    let derived_notice = derived_threshold_capability(
        row,
        role.as_deref(),
        &["notice_permission", "noticePermission"],
    );
    let derived_top =
        derived_threshold_capability(row, role.as_deref(), &["top_permission", "topPermission"]);
    let can_edit = persisted_bool(
        row,
        &["can_edit_channel_settings", "canEditChannelSettings"],
    )
    .unwrap_or(derived_settings);
    let can_manage_settings =
        persisted_bool(row, &["can_manage_settings", "canManageSettings"]).unwrap_or(can_edit);
    let can_manage_members =
        persisted_bool(row, &["can_manage_members", "canManageMembers"]).unwrap_or(derived_members);
    let can_mention_all =
        persisted_bool(row, &["can_mention_all", "canMentionAll"]).unwrap_or(derived_mention);
    let can_publish_notice =
        persisted_bool(row, &["can_publish_notice", "canPublishNotice"]).unwrap_or(derived_notice);
    let can_change_permissions =
        persisted_bool(row, &["can_change_permissions", "canChangePermissions"])
            .unwrap_or(change_role);
    let can_pin_message =
        persisted_bool(row, &["can_pin_message", "canPinMessage"]).unwrap_or(derived_top);
    output.insert("canEditChannelSettings".to_string(), Value::Bool(can_edit));
    output.insert(
        "canManageSettings".to_string(),
        Value::Bool(can_manage_settings),
    );
    output.insert(
        "canManageMembers".to_string(),
        Value::Bool(can_manage_members),
    );
    output.insert("canMentionAll".to_string(), Value::Bool(can_mention_all));
    output.insert(
        "canPublishNotice".to_string(),
        Value::Bool(can_publish_notice),
    );
    output.insert(
        "canChangePermissions".to_string(),
        Value::Bool(can_change_permissions),
    );
    output.insert("canPinMessage".to_string(), Value::Bool(can_pin_message));
}

/// Project one storage channel row into the MessageV3 channel-list contract.
pub(crate) fn shape_channel_row(row: &Value) -> Value {
    let Some(object) = row.as_object() else {
        return json!({});
    };
    let mut output = object.clone();

    insert_alias(&mut output, row, "id", &["id"]);
    insert_alias(
        &mut output,
        row,
        "channelId",
        &["channel_id", "channelId", "id"],
    );
    insert_alias(
        &mut output,
        row,
        "displayName",
        &["display_name", "displayName"],
    );
    insert_alias(&mut output, row, "type", &["type"]);
    insert_alias(&mut output, row, "teamId", &["team_id", "teamId"]);
    insert_alias(
        &mut output,
        row,
        "companyId",
        &["company_id", "companyId", "team_id", "teamId"],
    );
    // Go still exposes channel.update_at for legacy settingVersion readers and the
    // permissionRevision read-side ordering hint; permission writes no longer send it
    // as a CAS condition. Prefer explicit columns when a newer schema has them.
    insert_alias(
        &mut output,
        row,
        "settingVersion",
        &[
            "setting_version",
            "settingVersion",
            "updated_at",
            "updateAt",
        ],
    );
    insert_alias(
        &mut output,
        row,
        "permissionRevision",
        &[
            "permission_revision",
            "permissionRevision",
            "updated_at",
            "updateAt",
        ],
    );
    insert_alias(&mut output, row, "userId", &["user_id", "userId"]);
    insert_alias(&mut output, row, "isActive", &["is_active", "isActive"]);
    insert_alias(
        &mut output,
        row,
        "unreadCount",
        &["unread_count", "unreadCount"],
    );
    insert_alias(
        &mut output,
        row,
        "unreadPostId",
        &["unread_post_id", "unreadPostId", "unReadPostId"],
    );
    insert_alias(
        &mut output,
        row,
        "mentionCount",
        &["mention_count", "mentionCount"],
    );
    insert_alias(
        &mut output,
        row,
        "mentionCountRoot",
        &["mention_count_root", "mentionCountRoot"],
    );
    insert_alias(
        &mut output,
        row,
        "mentionUser",
        &["mention_user", "mentionUser"],
    );
    insert_non_negative_count_alias(
        &mut output,
        row,
        "urgentCount",
        &["urgent_count", "urgentCount"],
    );
    insert_alias(
        &mut output,
        row,
        "lastPostAt",
        &["last_post_at", "lastPostAt"],
    );
    insert_alias(
        &mut output,
        row,
        "lastRootPostAt",
        &["last_root_post_at", "lastRootPostAt"],
    );
    insert_alias(
        &mut output,
        row,
        "lastEventSeq",
        &["last_event_seq", "lastEventSeq"],
    );
    insert_alias(
        &mut output,
        row,
        "lastReadSeq",
        &["last_read_seq", "lastReadSeq"],
    );
    insert_alias(
        &mut output,
        row,
        "projectionRevision",
        &["projection_revision", "projectionRevision"],
    );
    insert_alias(&mut output, row, "topCount", &["top_count", "topCount"]);
    insert_alias(&mut output, row, "isRemove", &["is_remove", "isRemove"]);
    insert_alias(&mut output, row, "deleteAt", &["delete_at", "deleteAt"]);
    insert_alias(&mut output, row, "role", &["role"]);
    insert_viewer_capabilities(&mut output, row);
    insert_alias(&mut output, row, "orient", &["orient"]);
    insert_alias(&mut output, row, "purpose", &["purpose"]);
    insert_alias(
        &mut output,
        row,
        "pictureType",
        &["picture_type", "pictureType"],
    );
    insert_alias(&mut output, row, "rootId", &["root_id", "rootId"]);
    insert_alias(
        &mut output,
        row,
        "rootPostId",
        &["root_post_id", "rootPostId"],
    );
    insert_alias(
        &mut output,
        row,
        "threadCount",
        &["thread_count", "threadCount"],
    );
    insert_alias(
        &mut output,
        row,
        "topicMsgCount",
        &["topic_msg_count", "topicMsgCount"],
    );
    insert_alias(
        &mut output,
        row,
        "adminMaxCount",
        &["admin_max_count", "adminMaxCount"],
    );
    insert_bool_alias(
        &mut output,
        row,
        "hasUrgentPost",
        &["has_urgent_post", "hasUrgentPost"],
    );
    insert_alias(
        &mut output,
        row,
        "hasSchedulePost",
        &["has_schedule_post", "hasSchedulePost"],
    );
    insert_alias(&mut output, row, "createBy", &["create_by", "createBy"]);
    insert_alias(&mut output, row, "updateBy", &["update_by", "updateBy"]);
    insert_alias(
        &mut output,
        row,
        "urgentCurrentName",
        &["urgent_current_name", "urgentCurrentName"],
    );
    insert_alias(
        &mut output,
        row,
        "mentionPermission",
        &["mention_permission", "mentionPermission"],
    );
    insert_alias(
        &mut output,
        row,
        "noticePermission",
        &["notice_permission", "noticePermission"],
    );
    insert_alias(
        &mut output,
        row,
        "topPermission",
        &["top_permission", "topPermission"],
    );
    insert_alias(
        &mut output,
        row,
        "postMapDaily",
        &["post_map_daily", "postMapDaily"],
    );
    insert_alias(
        &mut output,
        row,
        "memberCount",
        &["member_count", "memberCount"],
    );
    insert_alias(
        &mut output,
        row,
        "subtopicsLoadedAt",
        &["subtopics_loaded_at", "subtopicsLoadedAt"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleId",
        &["schedule_id", "scheduleId"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleOwnerUserId",
        &["schedule_owner_user_id", "scheduleOwnerUserId"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleMessage",
        &["schedule_message", "scheduleMessage"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleMessagePreview",
        &["schedule_message_preview", "scheduleMessagePreview"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleSendAt",
        &["schedule_send_at", "scheduleSendAt"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleStatus",
        &["schedule_status", "scheduleStatus"],
    );
    insert_alias(
        &mut output,
        row,
        "scheduleRevision",
        &["schedule_revision", "scheduleRevision"],
    );
    insert_bool_alias(
        &mut output,
        row,
        "channelIsTop",
        &["is_top", "channelIsTop"],
    );
    insert_alias(&mut output, row, "createAt", &["created_at", "createAt"]);
    insert_alias(&mut output, row, "updateAt", &["updated_at", "updateAt"]);

    output.insert(
        "lastPost".to_string(),
        shape_last_post(json_field(row, &["last_post", "lastPost"], json!({}))),
    );
    output.insert(
        "mentionList".to_string(),
        json_field(row, &["mention_list", "mentionList"], json!([])),
    );
    output.insert(
        "urgentPostList".to_string(),
        json_field(row, &["urgent_post_list", "urgentPostList"], json!([])),
    );
    output.insert(
        "members".to_string(),
        json_field(row, &["members"], json!([])),
    );
    output.insert(
        "adminUsers".to_string(),
        json_field(row, &["admin_users", "adminUsers"], json!([])),
    );
    output.insert("boss".to_string(), json_field(row, &["boss"], json!([])));
    output.insert("owner".to_string(), json_field(row, &["owner"], json!({})));
    // Go increment and notify-only WS both expose the viewer mode as one scalar string;
    // retain that render-ready shape instead of inventing a nested notifyProps object.
    output.insert(
        "notifyProps".to_string(),
        json_field_or_value(row, &["notify_props", "notifyProps"], json!({})),
    );
    output.insert("props".to_string(), json_field(row, &["props"], json!({})));
    output.insert(
        "source".to_string(),
        json_field_or_value(row, &["source"], json!({})),
    );
    output.insert(
        "picture".to_string(),
        json_field(row, &["picture"], json!({})),
    );
    output.insert(
        "targetUsers".to_string(),
        json_field(row, &["target_users", "targetUsers"], json!([])),
    );
    output.insert(
        "draft".to_string(),
        json_field(row, &["draft"], Value::Null),
    );
    Value::Object(output)
}

/// Project every object in a channel scan while retaining empty channels.
pub(crate) fn shape_channel_rows(rows: &Value) -> Value {
    Value::Array(
        rows.as_array()
            .into_iter()
            .flatten()
            .filter(|row| row.is_object())
            .map(shape_channel_row)
            .collect(),
    )
}

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

    /// Channel scans expose the camel fields and a shaped last post to MessageV3.
    #[test]
    fn shapes_snake_channel_rows_without_dropping_empty_channels() {
        let rows = json!([
            {
                "id": "channel-1",
                "display_name": "测试群",
                "type": "P",
                "unread_count": 2,
                "mention_count": 1,
                "urgent_count": 3,
                "has_urgent_post": 1,
                "last_event_seq": 151,
                "last_read_seq": 9,
                "projection_revision": 12,
                "is_top": 1,
                "picture_type": "USER",
                "picture": "{\"userIds\":[\"444\"]}",
                "notify_props": "IGNORE",
                "source": "sync_events",
                "last_post": "{\"id\":\"post-1\",\"temporary_id\":\"tmp-1\",\"channel_id\":\"channel-1\",\"user_id\":\"444\",\"user_snapshot\":\"{\\\"userName\\\":\\\"破坏者\\\"}\",\"message\":\"回复消息\",\"type\":\"TEXT\"}"
            },
            { "id": "channel-2", "display_name": "空群" }
        ]);

        let shaped = shape_channel_rows(&rows);
        assert_eq!(shaped[0]["displayName"], "测试群");
        assert_eq!(shaped[0]["unreadCount"], 2);
        assert_eq!(shaped[0]["urgentCount"], 3);
        assert_eq!(shaped[0]["hasUrgentPost"], true);
        assert_eq!(shaped[0]["lastEventSeq"], 151);
        assert_eq!(shaped[0]["lastReadSeq"], 9);
        assert_eq!(shaped[0]["projectionRevision"], 12);
        assert_eq!(shaped[0]["channelIsTop"], true);
        assert_eq!(shaped[0]["picture"]["userIds"][0], "444");
        assert_eq!(shaped[0]["notifyProps"], "IGNORE");
        assert_eq!(shaped[0]["source"], "sync_events");
        assert_eq!(shaped[0]["lastPost"]["message"], "回复消息");
        assert_eq!(shaped[1]["displayName"], "空群");
        assert_eq!(shaped.as_array().map(Vec::len), Some(2));
    }

    /// Legacy negative urgent counters become zero without changing the urgent post list.
    #[test]
    fn clamps_negative_urgent_count_for_snake_and_camel_rows() {
        let rows = json!([
            {
                "id": "channel-negative-snake",
                "urgent_count": -2,
                "urgent_post_list": "[\"post-1\"]"
            },
            {
                "id": "channel-negative-camel",
                "urgentCount": -3,
                "urgentPostList": ["post-2"]
            }
        ]);

        let shaped = shape_channel_rows(&rows);
        assert_eq!(shaped[0]["urgentCount"], 0);
        assert_eq!(shaped[0]["urgent_count"], 0);
        assert_eq!(shaped[0]["urgentPostList"], json!(["post-1"]));
        assert_eq!(shaped[1]["urgentCount"], 0);
        assert_eq!(shaped[1]["urgentPostList"], json!(["post-2"]));
    }

    /// A single legacy negative row must not invalidate a twenty-row channel page.
    #[test]
    fn keeps_twenty_row_page_renderable_with_one_negative_urgent_count() {
        let rows = Value::Array(
            (0..20)
                .map(|index| {
                    json!({
                        "id": format!("channel-{index}"),
                        "urgent_count": if index == 7 { -1 } else { index },
                    })
                })
                .collect(),
        );

        let shaped = shape_channel_rows(&rows);
        assert_eq!(shaped.as_array().map(Vec::len), Some(20));
        assert_eq!(shaped[7]["urgentCount"], 0);
        assert_eq!(shaped[6]["urgentCount"], 6);
        assert_eq!(shaped[19]["urgentCount"], 19);
    }

    /// Channel pages expose the Go-equivalent absolute capabilities for every persisted viewer role.
    #[test]
    fn projects_viewer_capabilities_from_authoritative_role() {
        let rows = json!([
            { "id": "creator", "type": "P", "role": "CREATOR", "mentionPermission": "MANAGER", "noticePermission": "MANAGER", "topPermission": "MANAGER" },
            { "id": "manager", "type": "P", "role": "MANAGER", "mentionPermission": "MANAGER", "noticePermission": "MANAGER", "topPermission": "MANAGER" },
            { "id": "boss", "type": "O", "role": "BOSS", "mentionPermission": "MANAGER", "noticePermission": "MANAGER", "topPermission": "MANAGER" },
            { "id": "member", "type": "P", "role": "MEMBER", "noticePermission": "MANAGER", "topPermission": "MANAGER" },
            { "id": "invalid", "type": "P", "role": "UNKNOWN", "noticePermission": "MANAGER", "topPermission": "MANAGER" },
            { "id": "missing", "type": "P" }
        ]);

        let shaped = shape_channel_rows(&rows);
        for id in ["creator", "manager", "boss"] {
            let row = shaped
                .as_array()
                .unwrap()
                .iter()
                .find(|row| row["id"] == id)
                .unwrap();
            assert_eq!(row["canManageSettings"], true, "{id}");
            assert_eq!(row["canManageMembers"], true, "{id}");
            assert_eq!(row["canEditChannelSettings"], true, "{id}");
            assert_eq!(row["canChangePermissions"], id != "manager", "{id}");
            assert_eq!(row["canMentionAll"], true, "{id}");
            assert_eq!(row["canPublishNotice"], true, "{id}");
            assert_eq!(row["canPinMessage"], true, "{id}");
        }
        for id in ["member", "invalid", "missing"] {
            let row = shaped
                .as_array()
                .unwrap()
                .iter()
                .find(|row| row["id"] == id)
                .unwrap();
            assert_eq!(row["canManageSettings"], false, "{id}");
            assert_eq!(row["canManageMembers"], false, "{id}");
            assert_eq!(row["canEditChannelSettings"], false, "{id}");
            assert_eq!(row["canMentionAll"], false, "{id}");
            assert_eq!(row["canPublishNotice"], false, "{id}");
            assert_eq!(row["canChangePermissions"], false, "{id}");
            assert_eq!(row["canPinMessage"], false, "{id}");
        }
    }

    /// Invalid policy values and stringly-typed booleans never grant a capability.
    #[test]
    fn fails_closed_for_invalid_policy_and_boolean_values() {
        let shaped = shape_channel_row(&json!({
            "id": "invalid-policy",
            "type": "O",
            "role": "BOSS",
            "noticePermission": "UNKNOWN",
            "topPermission": "UNKNOWN",
            "can_publish_notice": "true",
            "can_pin_message": 2
        }));
        assert_eq!(shaped["canPublishNotice"], false);
        assert_eq!(shaped["canPinMessage"], false);
        assert_eq!(shaped["canManageMembers"], true);
    }

    /// Persisted absolute fields win over role fallback and remain JSON booleans.
    #[test]
    fn preserves_persisted_viewer_capabilities_without_role_inference() {
        let shaped = shape_channel_row(&json!({
            "id": "channel-1",
            "role": "MEMBER",
            "can_manage_settings": 1,
            "canManageMembers": false,
        }));

        assert_eq!(shaped["canManageSettings"], true);
        assert_eq!(shaped["canManageMembers"], false);
    }

    /// 角色读回使用 OWNER/ADMIN 别名时,viewer capability 仍按 CREATOR/MANAGER 计算。
    #[test]
    fn normalizes_owner_and_admin_aliases_for_role_readback() {
        let owner = shape_channel_row(&json!({
            "id": "owner-readback",
            "role": "OWNER",
        }));
        assert_eq!(owner["canEditChannelSettings"], true);
        assert_eq!(owner["canManageMembers"], true);
        assert_eq!(owner["canMentionAll"], true);
        assert_eq!(owner["canPublishNotice"], true);
        assert_eq!(owner["canChangePermissions"], true);
        assert_eq!(owner["canPinMessage"], true);

        let admin = shape_channel_row(&json!({
            "id": "admin-readback",
            "role": "ADMIN",
            "mentionPermission": "MANAGER",
            "noticePermission": "MANAGER",
            "topPermission": "MANAGER",
        }));
        assert_eq!(admin["canEditChannelSettings"], true);
        assert_eq!(admin["canManageMembers"], true);
        assert_eq!(admin["canMentionAll"], true);
        assert_eq!(admin["canPublishNotice"], true);
        assert_eq!(admin["canChangePermissions"], false);
        assert_eq!(admin["canPinMessage"], true);
    }

    /// 回归锚: legacy channel rows use the durable update timestamp as the Go CAS version.
    #[test]
    fn restores_cas_versions_from_legacy_updated_at_rows() {
        let shaped = shape_channel_row(&json!({
            "id": "channel-cas-version",
            "type": "P",
            "role": "CREATOR",
            "updated_at": 1_786_001_262_956_i64,
        }));

        assert_eq!(shaped["settingVersion"], 1_786_001_262_956_i64);
        assert_eq!(shaped["permissionRevision"], 1_786_001_262_956_i64);

        let explicit = shape_channel_row(&json!({
            "id": "channel-explicit-version",
            "updated_at": 10_i64,
            "setting_version": 11_i64,
            "permission_revision": 12_i64,
        }));

        assert_eq!(explicit["settingVersion"], 11_i64);
        assert_eq!(explicit["permissionRevision"], 12_i64);
    }
}