cautpartener / client / src / public / feed-service.ts
   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
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
/**
 * Public post feed (docs/PROTOCOL.md §2 feed rooms, §3 post/like docs, §6
 * behavior contracts): publish, browse, like, comment, re-seed, live valve.
 *
 * BROWSE: a shard ("<category>|<countySlug>") is 4 mailbox rooms (stripes
 * 0–3, keyed by author pub[0]&3). openFeed() replays all 4 stripes BACKWARD
 * from MAX_BEFORE within a page budget, verifies every 0x10 doc against the
 * §3 receiver rules (incl. shard + stripe binding), collects 0x11 blocks,
 * and merges verified posts in (ts, cid) DESC display order. Per-stripe
 * forward cursors serve refresh(); loadOlder() pages backward per stripe
 * until the room's oldest message (the TTL window edge — reported honestly)
 * or the spam budget (reported as truncation, never silence).
 *
 * LIKES are immutable signed docs, deduped per (author, re) at render;
 * un-like is impossible by design (immutable docs — the UI documents this).
 * POST COMMENTS are §3 comment docs with replyTo=<postCid> in the same shard
 * rooms, bound at collection to a verified post of this shard (to == the
 * post's author).
 *
 * RE-SEED (§6): after a shard replay, deposit own docs (always) + up to 5
 * random cached foreign docs older than 24 h (+ their image blocks), jittered
 * 0–60 s, ≤10 deposits per room per visit. The raw-envelope LRU cache
 * (envelope-cache.ts) provides byte-identical re-deposits (server dedup makes
 * them free; the TTL re-arms).
 *
 * LIVE VALVE (§6): while a shard feed is on screen, join feedTopic(shard)
 * with probability min(1, 12/estimatedSubscribers). Topic messages are
 * plaintext-signed head announcements { kind:"head", cids:[≤8] } under the
 * "cp-head|v1" tag; an announced cid we lack triggers a MAILBOX refresh
 * (deliberately no bitswap — the mailbox path is the load-bearing one, the
 * topic is purely a freshness hint and never load-bearing).
 */

import { decode as cborDecode, encode as cborEncode } from "@ipld/dag-cbor";
import { CID } from "multiformats/cid";
import { APP_SALT, nsKey, RuntimeLimits } from "../config";
import {
  decodeRestrictedActivity,
  decodeRestrictedPost,
  encodeRestrictedActivity,
  encodeRestrictedPost,
} from "../core/audience";
import { decodeWithinBounds, type EncodedImage } from "../core/media";
import { Session } from "../core/session";
import { fromB64url, randomBytes, toB64, toB64url, type Bytes } from "../lib/crypto";
import { verifyRaw, type Identity } from "../lib/identity";
import { cacheDelete, cacheDocsOf, cacheGet, cachePut, cacheTouch, type CachedEnvelope } from "./envelope-cache";
import { parseEnvelope, publicRoom, verifyBlock, ENV_BLOCK, ENV_DOC, MAX_BEFORE, type PublicRoom } from "./mailbox-io";
import { assembleBlocks, packBlocks } from "./profile-service";
import {
  isAid,
  isShard,
  sanitizeText,
  signDoc,
  verifyDoc,
  ACT_DESC_MAX,
  ACT_LOC_MAX,
  ACT_TITLE_MAX,
  ACT_TS_MAX,
  COMMENT_MAX,
  DAG_CBOR_CODE,
  POST_IMG_MAX_BYTES,
  POST_IMGS_MAX,
  POST_TEXT_MAX,
  type ActivityDoc,
  type CommentDoc,
  type JoinDoc,
  type LikeDoc,
  type PostDoc,
  type PostImgRef,
  type SealedBoxEnv,
} from "./public-doc";
import { feedRoom, feedTopic, stripe } from "./public-rooms";

// ---- §6 contract constants -----------------------------------------------------

/** ≤20 rendered posts per author per shard per day (§6 render cap). */
export const POSTS_PER_AUTHOR_DAY = 20;
/** ≤10 rendered comments per author per post per day (mirrors the §6 profile cap). */
export const POST_COMMENTS_PER_AUTHOR_DAY = 10;
/** Cross-post ceiling: one publish lands in at most this many shards. */
export const CROSS_POST_MAX = 2;
const RESEED_FOREIGN_DOCS = 5;
const RESEED_MAX_PER_ROOM = 10;
const RESEED_MIN_AGE_MS = 24 * 3_600_000;
const PAGE_LIMIT = 100;
const INITIAL_PAGES_PER_STRIPE = 3;
const OLDER_PAGES_PER_STRIPE = 2;
const MAX_PAGES_PER_STRIPE = 25; // hard spam budget per stripe per handle
const REFRESH_PAGES_PER_STRIPE = 3;
const HEAD_TAG = "cp-head|v1";
const HEAD_CIDS_MAX = 8;
const HEAD_DEBOUNCE_MS = 1_500; // coalesce a burst of head announcements
const HEAD_MIN_REFRESH_MS = 8_000; // hard floor between live-triggered refreshes
const LIVE_TARGET_SUBS = 12;
const BLOCK_MEM_BUDGET = 12 * 1024 * 1024; // transient per-handle block bytes
const THUMB_MAX_BYTES = 131_072;
/** ≤20 upcoming activities rendered per organizer (spam sanity, mirrors §6). */
export const ACTS_PER_AUTHOR = 20;
/** An activity may still be published/edited until `end` is this far gone. */
const ACT_PUBLISH_PAST_MS = 7 * 86_400_000;
/** Expired activities (end < now − 24 h) drop out of re-seeding (age-out). */
const ACT_RESEED_GRACE_MS = 24 * 3_600_000;
/**
 * Stale-doc replay resilience (P1 review): an attacker who re-deposits an OLD
 * signed activity revision at the room head (padding the window with filler)
 * must not pin resolvers to it. Author-strip walks page up to this many pages
 * PAST their base budget while pages still improve an aid's winner.
 */
const AUTHOR_ACTS_EXTRA_PAGES = 3;
/** The §3 receiver rule set the feed rooms accept (order = frequency). */
const FEED_KINDS = ["post", "like", "comment", "activity", "join"] as const;

/** Test/tuning knobs (e2e shortens the re-seed jitter; never load-bearing). */
export const FeedTuning = {
  reseedJitterMaxMs: 60_000,
  liveValve: true,
};

const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));

/** Opaque mailbox seqs order by (length, lexicographic) — mailbox.ts rule. */
function seqGtStr(a: string, b: string): boolean {
  return a.length !== b.length ? a.length > b.length : a > b;
}

// ---- local persistence ---------------------------------------------------------

const HIDDEN_KEY = nsKey("feed-hidden");
const OWN_KEY = nsKey("feed-own");
const LIKED_KEY = nsKey("feed-liked");
const SHARD_KEY = nsKey("feed-shard");

function loadStrList(key: string, cap: number): string[] {
  try {
    const raw = localStorage.getItem(key);
    const arr = raw ? (JSON.parse(raw) as unknown) : [];
    return Array.isArray(arr) ? arr.filter((x): x is string => typeof x === "string").slice(-cap) : [];
  } catch {
    return [];
  }
}

function saveStrList(key: string, list: string[], cap: number): void {
  try {
    localStorage.setItem(key, JSON.stringify(list.slice(-cap)));
  } catch {}
}

/** Local-only hidden posts (own local deletes + foreign "nu mă interesează"). */
export function hiddenPosts(): Set<string> {
  return new Set(loadStrList(HIDDEN_KEY, 500));
}

/**
 * Hide a post LOCALLY: it disappears from this device and is never re-seeded
 * by it again. NON-RETRACTIVE (§7): copies other clients hold live on until
 * their TTL runs out — the UI says so honestly.
 */
export function hidePostLocally(cidStr: string): void {
  const list = loadStrList(HIDDEN_KEY, 500);
  if (!list.includes(cidStr)) list.push(cidStr);
  saveStrList(HIDDEN_KEY, list, 500);
}

interface OwnPostRec {
  shard: string;
  cid: string;
  ts: number;
}

function loadOwnPosts(): OwnPostRec[] {
  try {
    const raw = localStorage.getItem(OWN_KEY);
    const arr = raw ? (JSON.parse(raw) as unknown) : [];
    if (!Array.isArray(arr)) return [];
    return arr.filter(
      (x): x is OwnPostRec =>
        !!x && typeof x === "object" && typeof (x as OwnPostRec).cid === "string" && typeof (x as OwnPostRec).shard === "string",
    );
  } catch {
    return [];
  }
}

function recordOwnPost(rec: OwnPostRec): void {
  const list = loadOwnPosts();
  list.push(rec);
  try {
    localStorage.setItem(OWN_KEY, JSON.stringify(list.slice(-200)));
  } catch {}
}

function myLikedSet(): Set<string> {
  return new Set(loadStrList(LIKED_KEY, 500));
}

function recordMyLike(postCid: string): void {
  const list = loadStrList(LIKED_KEY, 500);
  if (!list.includes(postCid)) list.push(postCid);
  saveStrList(LIKED_KEY, list, 500);
}

export interface ShardChoice {
  cat: string;
  county: string;
}

/** The last-browsed shard (feed tab picker persistence + boot re-seed). */
export function loadShardChoice(): ShardChoice | null {
  try {
    const raw = localStorage.getItem(SHARD_KEY);
    const c = raw ? (JSON.parse(raw) as Partial<ShardChoice>) : null;
    return c && typeof c.cat === "string" && typeof c.county === "string" ? { cat: c.cat, county: c.county } : null;
  } catch {
    return null;
  }
}

export function saveShardChoice(c: ShardChoice): void {
  try {
    localStorage.setItem(SHARD_KEY, JSON.stringify(c));
  } catch {}
}

// ---- publish -------------------------------------------------------------------

export type FeedOutcome = { ok: true; cids: string[] } | { ok: false; reason: "invalid" | "offline" | "deposit" };

/**
 * Publish one post into ≤2 shards (cross-post = DISTINCT signed docs, one per
 * shard, each bound to its room). Image bytes ride as 0x11 blocks (thumb +
 * display roots via packBlocks); every deposited envelope is also cached as
 * an OWN envelope so future visits re-seed it.
 *
 * `aud` (M5b) restricts the post to one of MY contact groups: the body is
 * sealed under the group's CURRENT epoch key and the public doc carries only
 * {aud, box} — TEXT-ONLY by design (image blocks are public-plane; sealing
 * them under group keys is out of v1 scope). Existence, likes and comments
 * stay public metadata (§7 — stated in-app).
 */
export async function publishPost(
  shards: string[],
  text: string,
  images: EncodedImage[] = [],
  onProgress?: (done: number, total: number) => void,
  aud?: { gid: string },
): Promise<FeedOutcome> {
  const id = Session.identity;
  if (!id) return { ok: false, reason: "offline" };
  const myPub = id.identity.publicKeyB64;
  const clean = sanitizeText(text, POST_TEXT_MAX);
  const targets = [...new Set(shards)].filter(isShard).slice(0, CROSS_POST_MAX);
  if (targets.length === 0) return { ok: false, reason: "invalid" };
  if (!clean && images.length === 0) return { ok: false, reason: "invalid" };
  if (images.length > POST_IMGS_MAX) return { ok: false, reason: "invalid" };

  let sealedRef: { gidHint: string; epoch: number; box: SealedBoxEnv } | null = null;
  if (aud) {
    if (images.length > 0 || !clean) return { ok: false, reason: "invalid" }; // restricted posts are text-only
    const audience = Session.audience;
    if (!audience) return { ok: false, reason: "offline" };
    sealedRef = await audience.seal(aud.gid, encodeRestrictedPost(clean)).catch(() => null);
    if (!sealedRef) return { ok: false, reason: "invalid" };
  }

  // pack image blocks once — the same refs go into every shard's doc
  const imgs: PostImgRef[] = [];
  const blocks: { cid: CID; bytes: Bytes }[] = [];
  for (const im of images) {
    if (im.display.length > POST_IMG_MAX_BYTES) return { ok: false, reason: "invalid" };
    const display = await packBlocks(im.display);
    const thumb = await packBlocks(im.thumb);
    blocks.push(...display.blocks, ...thumb.blocks);
    imgs.push({
      thumbCid: thumb.root.toString(),
      cid: display.root.toString(),
      mime: im.mime === "image/jpeg" ? "image/jpeg" : "image/webp",
      w: im.w,
      h: im.h,
      bytes: im.display.length,
    });
  }

  const myStripe = stripe(myPub);
  const total = targets.length * (1 + blocks.length);
  let done = 0;
  const step = (): void => onProgress?.(++done, total);
  const cids: string[] = [];
  const cacheEntries: CachedEnvelope[] = [];
  let allOk = true;

  for (const shard of targets) {
    const doc: PostDoc = sealedRef
      ? {
          ts: Date.now(),
          shard,
          text: "",
          imgs: [],
          aud: { gidHint: sealedRef.gidHint, epoch: sealedRef.epoch },
          box: sealedRef.box,
        }
      : { ts: Date.now(), shard, text: clean, imgs };
    const signed = await signDoc(id.identity, "post", doc);
    const room = publicRoom(await feedRoom(shard, myStripe));
    if (!room) return { ok: false, reason: "offline" };
    const r = await room.depositDoc(signed);
    step();
    if (!r.ok) {
      allOk = false;
      continue;
    }
    for (const b of blocks) {
      const rb = await room.depositBlock(b.cid, b.bytes);
      step();
      if (!rb.ok) allOk = false;
    }
    const cidStr = signed.cid.toString();
    cids.push(cidStr);
    recordOwnPost({ shard, cid: cidStr, ts: doc.ts });
    const now = Date.now();
    const blockCids = blocks.map((b) => b.cid.toString());
    cacheEntries.push({
      cid: cidStr,
      kind: "doc",
      shard,
      stripe: myStripe,
      ts: doc.ts,
      own: true,
      size: signed.bytes.length,
      lastUsed: now,
      raw: envBytes(ENV_DOC, signed.cid, signed.bytes),
      blockCids,
    });
    for (const b of blocks) {
      cacheEntries.push({
        cid: b.cid.toString(),
        kind: "block",
        shard,
        stripe: myStripe,
        ts: doc.ts,
        own: true,
        size: b.bytes.length,
        lastUsed: now,
        raw: envBytes(ENV_BLOCK, b.cid, b.bytes),
      });
    }
  }
  await cachePut(cacheEntries);
  if (cids.length === 0) return { ok: false, reason: "deposit" };
  if (!allOk) {
    // a block deposit failed — the doc landed, and re-seeding will retry the
    // blocks from the own-envelope cache on the next visit; still a success
  }
  // live hint (never load-bearing): announce the new heads on each shard topic
  for (const shard of targets) void announceHeads(id.identity, shard, cids).catch(() => {});
  return { ok: true, cids };
}

function envBytes(type: number, cid: CID, body: Uint8Array): Bytes {
  const out = new Uint8Array(1 + cid.bytes.length + body.length);
  out[0] = type;
  out.set(cid.bytes, 1);
  out.set(body, 1 + cid.bytes.length);
  return out;
}

// ---- head announcements (live topic; PROTOCOL delta: tag "cp-head|v1") ---------

interface HeadMsg {
  v: 1;
  kind: "head";
  shard: string;
  ts: number;
  cids: string[];
}

const utf8 = (s: string): Bytes => new TextEncoder().encode(s) as Bytes;

function headSigMsg(docBytes: Uint8Array): Bytes {
  const prefix = utf8(`${HEAD_TAG}|${APP_SALT}|`);
  const out = new Uint8Array(prefix.length + docBytes.length);
  out.set(prefix, 0);
  out.set(docBytes, prefix.length);
  return out;
}

async function announceHeads(identity: Identity, shard: string, cids: string[]): Promise<void> {
  const live = Session.selfroom?.hub.live;
  if (!live || !live.started) return;
  const d: HeadMsg = { v: 1, kind: "head", shard, ts: Date.now(), cids: cids.slice(0, HEAD_CIDS_MAX) };
  const docBytes = cborEncode(d);
  const sig = await identity.signRaw(headSigMsg(docBytes));
  const msg = cborEncode({ p: fromB64url(identity.publicKeyB64), s: sig, d });
  await live.publishTopic(await feedTopic(shard), msg);
}

/** Verify one on-topic head announcement; null on any failure (drop silently). */
async function verifyHead(data: Uint8Array, shard: string): Promise<HeadMsg | null> {
  try {
    const outer = cborDecode(data) as { p?: unknown; s?: unknown; d?: unknown };
    if (!outer || typeof outer !== "object") return null;
    const { p, s, d } = outer;
    if (!(p instanceof Uint8Array) || p.length !== 32) return null;
    if (!(s instanceof Uint8Array) || s.length !== 64) return null;
    if (!d || typeof d !== "object" || Array.isArray(d)) return null;
    const m = d as Partial<HeadMsg>;
    if (m.v !== 1 || m.kind !== "head" || m.shard !== shard) return null;
    if (typeof m.ts !== "number" || Math.abs(Date.now() - m.ts) > 600_000) return null;
    if (!Array.isArray(m.cids) || m.cids.length === 0 || m.cids.length > HEAD_CIDS_MAX) return null;
    if (!m.cids.every((c) => typeof c === "string" && c.length > 0 && c.length <= 128)) return null;
    const pub = toB64url(p as Bytes);
    const sigB64 = toB64url(s as Bytes);
    if (!(await verifyRaw(pub, sigB64, headSigMsg(cborEncode(d))))) return null;
    return { v: 1, kind: "head", shard, ts: m.ts, cids: m.cids };
  } catch {
    return null;
  }
}

// ---- feed handle ---------------------------------------------------------------

export interface FeedComment {
  cidStr: string;
  pub: string;
  ts: number;
  text: string;
}

export interface FeedPost {
  cidStr: string;
  pub: string;
  ts: number;
  /** For restricted posts: the UNSEALED body ("" while locked). */
  text: string;
  imgs: PostImgRef[];
  likeCount: number;
  likedByMe: boolean;
  comments: FeedComment[];
  own: boolean;
  /**
   * Present on audience-restricted posts (M5b). locked = no key on this
   * device; label = MY group's name when I authored it (local knowledge),
   * null for content unsealed as a member (the UI shows a generic badge).
   */
  restricted?: { locked: boolean; label: string | null };
}

/** One activity as the UI renders it (P1). */
export interface FeedActivity {
  /** The organizer's pub. */
  org: string;
  aid: string;
  seq: number;
  ts: number;
  /** cid of the WINNING (highest-seq) activity doc. */
  cidStr: string;
  shard: string;
  title: string;
  /** For restricted activities: the UNSEALED desc ("" while locked). */
  desc: string;
  /** For restricted activities: the UNSEALED loc (null while locked). */
  loc: string | null;
  start: number;
  end: number;
  cancelled: boolean;
  visibility: "public" | "group";
  own: boolean;
  /** Present on group-restricted activities — like FeedPost.restricted. */
  restricted?: { locked: boolean; label: string | null; gidHint: string };
  /** Joiner pubs with status "going", join-order (ts asc). */
  going: string[];
  /** My folded join status for this activity (null = never joined). */
  myStatus: "going" | "out" | null;
}

export interface FeedView {
  /** net = NO stripe answered (mailbox unreachable); ok otherwise. */
  state: "ok" | "net";
  posts: FeedPost[];
  /**
   * The upcoming-activities index (P1): end ≥ now, sorted by start ASC,
   * ≤20 per organizer. Expired activities drop out of this view (and out of
   * re-seeding after a 24 h grace), so they age out of the public window.
   */
  activities: FeedActivity[];
  /** Posts suppressed by the ≤20/author/shard/day render cap. */
  suppressed: number;
  /** Every reachable stripe was walked to the room's oldest message. */
  atWindowEdge: boolean;
  /** Some stripe hit the page budget with older history remaining. */
  truncated: boolean;
  /** A refresh cursor aged out — messages expired unseen between visits. */
  gap: boolean;
}

interface StripeState {
  stripe: number;
  room: PublicRoom | null;
  /** Forward cursor for refresh() — the newest seq this handle has consumed. */
  cursor: string | null;
  /** Next backward cursor (the oldest seq seen so far). */
  before: string;
  complete: boolean;
  reached: boolean;
  pages: number;
}

interface RawPost {
  cidStr: string;
  pub: string;
  doc: PostDoc;
  stripe: number;
  raw: Bytes;
  size: number;
  /** Restricted posts only: unsealed body, or null while no key is held. */
  unsealed?: string | null;
}

/** Unseal one restricted post body with whatever keys this device holds. */
async function tryUnsealPost(pub: string, doc: PostDoc): Promise<string | null> {
  const audience = Session.audience;
  if (!audience || !doc.aud || !doc.box) return null;
  const pt = await audience
    .unseal(pub, { gidHint: doc.aud.gidHint, epoch: doc.aud.epoch, box: doc.box })
    .catch(() => null);
  return pt ? decodeRestrictedPost(pt) : null;
}

interface RawComment {
  cidStr: string;
  pub: string;
  doc: CommentDoc;
}

interface RawActivity {
  cidStr: string;
  pub: string;
  doc: ActivityDoc;
  stripe: number;
  raw: Bytes;
  size: number;
  /** Restricted activities only: unsealed body, or null while no key held. */
  unsealed?: { desc: string; loc: string } | null;
}

interface RawJoin {
  cidStr: string;
  pub: string;
  doc: JoinDoc;
  stripe: number;
  raw: Bytes;
  size: number;
}

/** Activity LWW (P1): highest (seq, ts, cid) per (pub, aid) wins. */
function activityWins(n: { doc: ActivityDoc; cidStr: string }, o: { doc: ActivityDoc; cidStr: string }): boolean {
  if (n.doc.seq !== o.doc.seq) return n.doc.seq > o.doc.seq;
  if (n.doc.ts !== o.doc.ts) return n.doc.ts > o.doc.ts;
  return n.cidStr > o.cidStr;
}

/** Join LWW (P1): highest (ts, cid) per (joiner, org, aid) wins. */
function joinWins(n: { doc: JoinDoc; cidStr: string }, o: { doc: JoinDoc; cidStr: string }): boolean {
  if (n.doc.ts !== o.doc.ts) return n.doc.ts > o.doc.ts;
  return n.cidStr > o.cidStr;
}

/** Unseal one restricted activity's desc/loc with whatever keys are held. */
async function tryUnsealActivity(pub: string, doc: ActivityDoc): Promise<{ desc: string; loc: string } | null> {
  const audience = Session.audience;
  if (!audience || !doc.aud || !doc.box) return null;
  const pt = await audience
    .unseal(pub, { gidHint: doc.aud.gidHint, epoch: doc.aud.epoch, box: doc.box })
    .catch(() => null);
  return pt ? decodeRestrictedActivity(pt) : null;
}

export class FeedHandle {
  readonly shard: string;
  #stripes: StripeState[] = [];
  #posts = new Map<string, RawPost>();
  #likes = new Map<string, Set<string>>(); // post cid → liker pubs
  #comments = new Map<string, Map<string, RawComment>>(); // post cid → (cid → comment)
  #activities = new Map<string, RawActivity>(); // `${org}|${aid}` → LWW winner
  #joins = new Map<string, Map<string, RawJoin>>(); // `${org}|${aid}` → (joiner → LWW winner)
  /** Verified doc cids already folded — skips re-verifying dup envelopes. */
  #seenDocs = new Set<string>();
  #blocks = new Map<string, Bytes>();
  #blockBytes = 0;
  #imgUrls = new Map<string, string | null>();
  #gap = false;
  #reseedDone = false;
  #liveTopic: string | null = null;
  #refreshTimer: ReturnType<typeof setTimeout> | null = null;
  #lastLiveRefreshAt = 0;
  #closed = false;
  /** Fires after a live-head-triggered background refresh lands (UI hook). */
  onLiveUpdate: () => void = () => {};

  private constructor(shard: string) {
    this.shard = shard;
  }

  /**
   * Open a shard feed: initial backward replay of all 4 stripes, then (per
   * §6) a jittered re-seed pass and the probabilistic live-topic join.
   */
  static async open(shard: string, opts: { live?: boolean; initialPages?: number } = {}): Promise<FeedHandle> {
    const h = new FeedHandle(shard);
    for (let s = 0; s < 4; s++) {
      let room: PublicRoom | null = null;
      try {
        room = publicRoom(await feedRoom(shard, s));
      } catch {}
      h.#stripes.push({ stripe: s, room, cursor: null, before: MAX_BEFORE, complete: false, reached: false, pages: 0 });
    }
    await h.#walkBackward(opts.initialPages ?? INITIAL_PAGES_PER_STRIPE);
    await h.#cacheVerified();
    void h.#reseed().catch(() => {});
    if (opts.live !== false && FeedTuning.liveValve) void h.#maybeJoinLive().catch(() => {});
    return h;
  }

  get closed(): boolean {
    return this.#closed;
  }

  /** Leave the live topic and drop transient block memory. */
  close(): void {
    this.#closed = true;
    if (this.#refreshTimer) clearTimeout(this.#refreshTimer);
    if (this.#liveTopic) {
      Session.selfroom?.hub.live.leaveTopic(this.#liveTopic);
      this.#liveTopic = null;
    }
    // imageUrl() mints only data: URLs (see below), so there is nothing to
    // URL.revokeObjectURL — just release the cached strings and block bytes.
    this.#imgUrls.clear();
    this.#blocks.clear();
    this.#blockBytes = 0;
  }

  // ---- replay ------------------------------------------------------------------

  async #walkBackward(pages: number): Promise<void> {
    for (const st of this.#stripes) {
      if (!st.room || st.complete) continue;
      let stepPages = 0;
      while (stepPages < pages && st.pages < MAX_PAGES_PER_STRIPE) {
        const page = await st.room.pageBefore(st.before, PAGE_LIMIT);
        if (page === null) break;
        st.reached = true;
        st.pages++;
        stepPages++;
        if (st.cursor === null) st.cursor = page.latestSeq;
        if (page.messages.length === 0) {
          st.complete = true;
          break;
        }
        for (const m of page.messages) await this.#ingest(m.payload, st.stripe);
        if (!page.hasMore) {
          st.complete = true;
          break;
        }
        st.before = page.messages[0].seq;
      }
    }
  }

  async #ingest(payloadB64: string, stripeNo: number): Promise<void> {
    const env = parseEnvelope(payloadB64);
    if (!env) return;
    const cidStr = env.cid.toString();
    if (env.type === ENV_BLOCK) {
      // SECURITY (§6): hash-verify the body against its cid BEFORE it can take
      // the cid slot. Rooms are open, replay is newest-first, and the block map
      // is first-write-wins — without this an attacker's junk block deposited
      // under a real image cid would occupy the slot and permanently break
      // image assembly (the genuine older block would be skipped). Verify-at-
      // ingest makes first-write-wins safe: only the genuine block ever lands.
      if (!this.#blocks.has(cidStr)) {
        if (!(await verifyBlock(env))) return;
        this.#blocks.set(cidStr, env.body);
        this.#blockBytes += env.body.length;
        // bound transient memory: drop the oldest-inserted blocks first
        while (this.#blockBytes > BLOCK_MEM_BUDGET && this.#blocks.size > 0) {
          const first = this.#blocks.keys().next().value as string;
          this.#blockBytes -= this.#blocks.get(first)?.length ?? 0;
          this.#blocks.delete(first);
        }
      }
      return;
    }
    if (env.type !== ENV_DOC) return;
    if (this.#posts.has(cidStr) || this.#seenDocs.has(cidStr)) return;
    const v = await verifyDoc(env.body, {
      kinds: [...FEED_KINDS],
      shard: this.shard,
      stripe: stripeNo,
      cid: env.cid,
    });
    if (!v) return;
    // only VERIFIED cids enter the seen-set: a junk doc claiming a genuine cid
    // fails the re-hash and must never block the genuine envelope's ingest
    this.#seenDocs.add(cidStr);
    if (v.kind === "post") {
      const doc = v.doc as PostDoc;
      const rec: RawPost = { cidStr, pub: v.pub, doc, stripe: stripeNo, raw: env.raw, size: env.body.length };
      if (doc.aud) rec.unsealed = await tryUnsealPost(v.pub, doc);
      this.#posts.set(cidStr, rec);
    } else if (v.kind === "like") {
      const doc = v.doc as LikeDoc;
      let set = this.#likes.get(doc.re);
      if (!set) this.#likes.set(doc.re, (set = new Set()));
      set.add(v.pub);
    } else if (v.kind === "activity") {
      // P1: LWW per (organizer, aid) — the organizer edits/cancels via seq
      const doc = v.doc as ActivityDoc;
      const key = `${v.pub}|${doc.aid}`;
      const rec: RawActivity = { cidStr, pub: v.pub, doc, stripe: stripeNo, raw: env.raw, size: env.body.length };
      const prev = this.#activities.get(key);
      if (prev && !activityWins(rec, prev)) return;
      // A NEWER OWN revision supersedes the older one on ANY of my devices —
      // drop the superseded own envelope from the re-seed cache here too, not
      // only on the editing device (which passes replacesCid explicitly).
      if (prev && prev.doc.seq < doc.seq && v.pub === Session.identity?.identity.publicKeyB64) {
        void cacheDelete([prev.cidStr]).catch(() => {});
      }
      if (doc.aud) rec.unsealed = await tryUnsealActivity(v.pub, doc);
      this.#activities.set(key, rec);
    } else if (v.kind === "join") {
      // P1: LWW per (joiner, org, aid) — bound to the organizer pair, not an
      // activity cid, so joins survive activity edits
      const doc = v.doc as JoinDoc;
      const key = `${doc.org}|${doc.aid}`;
      let map = this.#joins.get(key);
      if (!map) this.#joins.set(key, (map = new Map()));
      const rec: RawJoin = { cidStr, pub: v.pub, doc, stripe: stripeNo, raw: env.raw, size: env.body.length };
      const prev = map.get(v.pub);
      if (prev && !joinWins(rec, prev)) return;
      map.set(v.pub, rec);
    } else {
      const doc = v.doc as CommentDoc;
      if (!doc.replyTo) return; // post comments MUST bind to a post cid
      let map = this.#comments.get(doc.replyTo);
      if (!map) this.#comments.set(doc.replyTo, (map = new Map()));
      if (!map.has(v.cidStr)) map.set(v.cidStr, { cidStr: v.cidStr, pub: v.pub, doc });
    }
  }

  /** Cache verified post envelopes + their in-memory blocks for re-seeding. */
  async #cacheVerified(): Promise<void> {
    const myPub = Session.identity?.identity.publicKeyB64 ?? null;
    const entries: CachedEnvelope[] = [];
    const now = Date.now();
    for (const p of this.#posts.values()) {
      const blockCids: string[] = [];
      for (const img of p.doc.imgs) {
        for (const root of [img.thumbCid, img.cid]) {
          blockCids.push(root, ...this.#chunkCidsOf(root));
        }
      }
      entries.push({
        cid: p.cidStr,
        kind: "doc",
        shard: this.shard,
        stripe: p.stripe,
        ts: p.doc.ts,
        own: p.pub === myPub,
        size: p.size,
        lastUsed: now,
        raw: p.raw,
        blockCids,
      });
      for (const bc of blockCids) {
        const bytes = this.#blocks.get(bc);
        if (!bytes) continue;
        let cid: CID;
        try {
          cid = CID.parse(bc);
        } catch {
          continue;
        }
        entries.push({
          cid: bc,
          kind: "block",
          shard: this.shard,
          stripe: p.stripe,
          ts: p.doc.ts,
          own: p.pub === myPub,
          size: bytes.length,
          lastUsed: now,
          raw: envBytes(ENV_BLOCK, cid, bytes),
        });
      }
    }
    // P1 activities + joins: cached with exp = the activity's end, so expired
    // ones (end < now − 24 h) are EXCLUDED here and skipped by reseedShard —
    // they age out of the public window instead of being kept alive forever.
    for (const a of this.#activities.values()) {
      if (now - a.doc.end > ACT_RESEED_GRACE_MS) continue;
      entries.push({
        cid: a.cidStr,
        kind: "doc",
        shard: this.shard,
        stripe: a.stripe,
        ts: a.doc.ts,
        own: a.pub === myPub,
        size: a.size,
        lastUsed: now,
        raw: a.raw,
        exp: a.doc.end,
      });
    }
    for (const [key, map] of this.#joins) {
      const act = this.#activities.get(key);
      if (act && now - act.doc.end > ACT_RESEED_GRACE_MS) continue; // its activity expired
      for (const j of map.values()) {
        entries.push({
          cid: j.cidStr,
          kind: "doc",
          shard: this.shard,
          stripe: j.stripe,
          ts: j.doc.ts,
          own: j.pub === myPub,
          size: j.size,
          lastUsed: now,
          raw: j.raw,
          // unknown activity ⇒ fallback exp one TTL window out, so an orphan
          // join still ages out of re-seeding instead of living forever
          exp: act ? act.doc.end : now + RuntimeLimits.ttlHours * 3_600_000,
        });
      }
    }
    await cachePut(entries);
  }

  /** Chunk cids referenced by a manifest block held in memory (else []). */
  #chunkCidsOf(rootCidStr: string): string[] {
    try {
      const root = CID.parse(rootCidStr);
      if (root.code !== DAG_CBOR_CODE) return [];
      const bytes = this.#blocks.get(rootCidStr);
      if (!bytes) return [];
      const m = cborDecode(bytes) as { v?: unknown; chunks?: unknown };
      if (!m || m.v !== 1 || !Array.isArray(m.chunks) || m.chunks.length > 16) return [];
      const out: string[] = [];
      for (const c of m.chunks) {
        const cid = CID.asCID(c);
        if (cid) out.push(cid.toString());
      }
      return out;
    } catch {
      return [];
    }
  }

  /** Forward refresh from the per-stripe cursors (new posts since replay). */
  async refresh(): Promise<FeedView> {
    for (const st of this.#stripes) {
      if (!st.room) continue;
      if (st.cursor === null) {
        // stripe never answered — or was EMPTY at first visit (no latest_seq
        // to cursor from): restart its backward walk from the newest window
        st.complete = false;
        st.before = MAX_BEFORE;
        await this.#walkStripe(st, INITIAL_PAGES_PER_STRIPE);
        continue;
      }
      let pages = 0;
      let cursor: string | null = st.cursor;
      while (pages < REFRESH_PAGES_PER_STRIPE) {
        const r = await st.room.replayForward(cursor, PAGE_LIMIT);
        if (!r.ok) break;
        pages++;
        // gap honesty (§6): our cursor fell below the room's oldest message —
        // deposits expired between visits without ever being seen here
        if (r.page.oldestSeq && cursor && seqGtStr(r.page.oldestSeq, cursor)) this.#gap = true;
        for (const m of r.page.messages) await this.#ingest(m.payload, st.stripe);
        const last = r.page.messages.at(-1);
        if (last) cursor = last.seq;
        if (!r.page.hasMore) break;
      }
      st.cursor = cursor;
    }
    // audience keys may have arrived since the initial replay (a grant folded
    // from a pairwise room) — retry locked posts/activities so a refresh
    // unseals them
    for (const p of this.#posts.values()) {
      if (p.doc.aud && p.unsealed == null) p.unsealed = await tryUnsealPost(p.pub, p.doc);
    }
    for (const a of this.#activities.values()) {
      if (a.doc.aud && a.unsealed == null) a.unsealed = await tryUnsealActivity(a.pub, a.doc);
    }
    await this.#cacheVerified();
    return this.view();
  }

  async #walkStripe(st: StripeState, pages: number): Promise<void> {
    if (!st.room || st.complete) return;
    let stepPages = 0;
    while (stepPages < pages && st.pages < MAX_PAGES_PER_STRIPE) {
      const page = await st.room.pageBefore(st.before, PAGE_LIMIT);
      if (page === null) break;
      st.reached = true;
      st.pages++;
      stepPages++;
      if (st.cursor === null) st.cursor = page.latestSeq;
      if (page.messages.length === 0) {
        st.complete = true;
        break;
      }
      for (const m of page.messages) await this.#ingest(m.payload, st.stripe);
      if (!page.hasMore) {
        st.complete = true;
        break;
      }
      st.before = page.messages[0].seq;
    }
  }

  /** Page every incomplete stripe further back; false = nothing left to load. */
  async loadOlder(): Promise<boolean> {
    let any = false;
    for (const st of this.#stripes) {
      if (!st.room || st.complete || st.pages >= MAX_PAGES_PER_STRIPE) continue;
      const beforePages = st.pages;
      await this.#walkStripe(st, OLDER_PAGES_PER_STRIPE);
      if (st.pages > beforePages) any = true;
    }
    if (any) await this.#cacheVerified();
    return this.#stripes.some((st) => st.room && !st.complete && st.pages < MAX_PAGES_PER_STRIPE);
  }

  // ---- view --------------------------------------------------------------------

  view(): FeedView {
    const myPub = Session.identity?.identity.publicKeyB64 ?? null;
    const hidden = hiddenPosts();
    const blocked = new Set(Session.selfroom?.state.modSrc?.blocked ?? []);
    const liked = myLikedSet();

    const ordered = [...this.#posts.values()].sort(
      (a, b) => b.doc.ts - a.doc.ts || (b.cidStr > a.cidStr ? 1 : -1),
    );
    const perAuthorDay = new Map<string, number>();
    const posts: FeedPost[] = [];
    let suppressed = 0;
    for (const p of ordered) {
      if (hidden.has(p.cidStr)) continue;
      if (blocked.has(p.pub) && p.pub !== myPub) continue;
      const key = `${p.pub}|${Math.floor(p.doc.ts / 86_400_000)}`;
      const n = (perAuthorDay.get(key) ?? 0) + 1;
      perAuthorDay.set(key, n);
      if (n > POSTS_PER_AUTHOR_DAY) {
        suppressed++;
        continue;
      }
      posts.push(this.#toFeedPost(p, myPub, hidden, blocked, liked));
    }

    // P1 upcoming-activities index: end ≥ now, start ASC, ≤20 per organizer
    const now = Date.now();
    const actsOrdered = [...this.#activities.values()]
      .filter((a) => a.doc.end >= now)
      .filter((a) => !(blocked.has(a.pub) && a.pub !== myPub))
      .sort((a, b) => a.doc.start - b.doc.start || (a.cidStr < b.cidStr ? -1 : 1));
    const perOrg = new Map<string, number>();
    const activities: FeedActivity[] = [];
    for (const a of actsOrdered) {
      const n = (perOrg.get(a.pub) ?? 0) + 1;
      perOrg.set(a.pub, n);
      if (n > ACTS_PER_AUTHOR) continue;
      activities.push(this.#toFeedActivity(a, myPub, blocked));
    }

    const reachable = this.#stripes.filter((st) => st.room !== null);
    const reached = reachable.filter((st) => st.reached);
    return {
      state: reachable.length > 0 && reached.length === 0 ? "net" : "ok",
      posts,
      activities,
      suppressed,
      atWindowEdge: reached.length > 0 && reached.every((st) => st.complete),
      truncated: reached.some((st) => !st.complete && st.pages >= MAX_PAGES_PER_STRIPE),
      gap: this.#gap,
    };
  }

  #toFeedPost(
    p: RawPost,
    myPub: string | null,
    hidden: Set<string>,
    blocked: Set<string>,
    liked: Set<string>,
  ): FeedPost {
    const likers = this.#likes.get(p.cidStr) ?? new Set<string>();
    const commentsRaw = [...(this.#comments.get(p.cidStr)?.values() ?? [])]
      .filter((c) => c.doc.to === p.pub && !blocked.has(c.pub) && !hidden.has(c.cidStr))
      .sort((a, b) => a.doc.ts - b.doc.ts || (a.cidStr < b.cidStr ? -1 : 1));
    const perAuthorDay = new Map<string, number>();
    const comments: FeedComment[] = [];
    for (const c of commentsRaw) {
      const key = `${c.pub}|${Math.floor(c.doc.ts / 86_400_000)}`;
      const n = (perAuthorDay.get(key) ?? 0) + 1;
      perAuthorDay.set(key, n);
      if (n > POST_COMMENTS_PER_AUTHOR_DAY) continue;
      comments.push({ cidStr: c.cidStr, pub: c.pub, ts: c.doc.ts, text: c.doc.text });
    }
    return {
      cidStr: p.cidStr,
      pub: p.pub,
      ts: p.doc.ts,
      text: p.doc.aud ? (p.unsealed ?? "") : p.doc.text,
      imgs: p.doc.imgs,
      likeCount: likers.size + (liked.has(p.cidStr) && myPub !== null && !likers.has(myPub) ? 1 : 0),
      likedByMe: (myPub !== null && likers.has(myPub)) || liked.has(p.cidStr),
      comments,
      own: p.pub === myPub,
      ...(p.doc.aud
        ? {
            restricted: {
              locked: p.unsealed == null,
              label: p.unsealed == null ? null : (Session.audience?.labelFor(p.pub, p.doc.aud.gidHint) ?? null),
            },
          }
        : {}),
    };
  }

  #toFeedActivity(a: RawActivity, myPub: string | null, blocked: Set<string>): FeedActivity {
    const joiners = this.#joins.get(`${a.pub}|${a.doc.aid}`);
    const going: { pub: string; ts: number }[] = [];
    let myStatus: "going" | "out" | null = null;
    if (joiners) {
      for (const j of joiners.values()) {
        if (myPub !== null && j.pub === myPub) myStatus = j.doc.status;
        if (j.doc.status !== "going") continue;
        if (blocked.has(j.pub) && j.pub !== myPub) continue;
        going.push({ pub: j.pub, ts: j.doc.ts });
      }
      going.sort((x, y) => x.ts - y.ts || (x.pub < y.pub ? -1 : 1));
    }
    const locked = a.doc.aud ? a.unsealed == null : false;
    return {
      org: a.pub,
      aid: a.doc.aid,
      seq: a.doc.seq,
      ts: a.doc.ts,
      cidStr: a.cidStr,
      shard: a.doc.shard,
      title: a.doc.title,
      desc: a.doc.aud ? (a.unsealed?.desc ?? "") : a.doc.desc,
      loc: a.doc.aud ? (a.unsealed?.loc || null) : (a.doc.loc ?? null),
      start: a.doc.start,
      end: a.doc.end,
      cancelled: a.doc.cancelled === true,
      visibility: a.doc.visibility,
      own: a.pub === myPub,
      ...(a.doc.aud
        ? {
            restricted: {
              locked,
              label: locked ? null : (Session.audience?.labelFor(a.pub, a.doc.aud.gidHint) ?? null),
              gidHint: a.doc.aud.gidHint,
            },
          }
        : {}),
      going: going.map((g) => g.pub),
      myStatus,
    };
  }

  /**
   * One activity by (organizer, aid) — permalink + detail views. Returned
   * regardless of expiry (the caller renders the honest expired state).
   */
  activity(org: string, aid: string): FeedActivity | null {
    const a = this.#activities.get(`${org}|${aid}`);
    if (!a) return null;
    const myPub = Session.identity?.identity.publicKeyB64 ?? null;
    const blocked = new Set(Session.selfroom?.state.modSrc?.blocked ?? []);
    if (blocked.has(a.pub) && a.pub !== myPub) return null;
    return this.#toFeedActivity(a, myPub, blocked);
  }

  /**
   * Join/leave one activity (P1): a signed join doc into MY stripe room of
   * this shard, LWW per (me, org, aid) — idempotent (an unchanged status
   * deposits nothing) and reversible, unlike likes.
   */
  async joinActivity(org: string, aid: string, status: "going" | "out"): Promise<{ ok: boolean; already: boolean }> {
    const id = Session.identity;
    if (!id || !isAid(aid) || !/^[A-Za-z0-9_-]{43}$/.test(org)) return { ok: false, already: false };
    const myPub = id.identity.publicKeyB64;
    const key = `${org}|${aid}`;
    const prev = this.#joins.get(key)?.get(myPub);
    if (prev?.doc.status === status) return { ok: true, already: true };
    const doc: JoinDoc = { ts: Math.max(Date.now(), (prev?.doc.ts ?? 0) + 1), org, aid, shard: this.shard, status };
    const signed = await signDoc(id.identity, "join", doc);
    const myStripe = stripe(myPub);
    let room: PublicRoom | null = null;
    try {
      room = publicRoom(await feedRoom(this.shard, myStripe));
    } catch {}
    if (!room) return { ok: false, already: false };
    const r = await room.depositDoc(signed);
    if (!r.ok) return { ok: false, already: false };
    let map = this.#joins.get(key);
    if (!map) this.#joins.set(key, (map = new Map()));
    map.set(myPub, { cidStr: signed.cid.toString(), pub: myPub, doc, stripe: myStripe, raw: envBytes(ENV_DOC, signed.cid, signed.bytes), size: signed.bytes.length });
    const act = this.#activities.get(key);
    await cachePut([
      {
        cid: signed.cid.toString(),
        kind: "doc",
        shard: this.shard,
        stripe: myStripe,
        ts: doc.ts,
        own: true,
        size: signed.bytes.length,
        lastUsed: Date.now(),
        raw: envBytes(ENV_DOC, signed.cid, signed.bytes),
        // unknown activity ⇒ fallback exp one TTL window out (ages out, §6)
        exp: act ? act.doc.end : Date.now() + RuntimeLimits.ttlHours * 3_600_000,
      },
    ]);
    return { ok: true, already: false };
  }

  /** One post by cid (permalink view), or null when not in the window. */
  post(cidStr: string): FeedPost | null {
    const p = this.#posts.get(cidStr);
    if (!p) return null;
    const myPub = Session.identity?.identity.publicKeyB64 ?? null;
    if (hiddenPosts().has(cidStr)) return null;
    const blocked = new Set(Session.selfroom?.state.modSrc?.blocked ?? []);
    // consistency with view(): a blocked author's own post is filtered here too
    if (blocked.has(p.pub) && p.pub !== myPub) return null;
    return this.#toFeedPost(p, myPub, hiddenPosts(), blocked, myLikedSet());
  }

  // ---- actions -----------------------------------------------------------------

  /**
   * Like a post: an immutable signed doc, deposited into MY stripe room of
   * this shard. Un-like is impossible by design (docs are immutable); dedup
   * per (author, re) happens at render.
   */
  async like(postCid: string): Promise<{ ok: boolean; already: boolean }> {
    const id = Session.identity;
    if (!id) return { ok: false, already: false };
    const myPub = id.identity.publicKeyB64;
    if (this.#likes.get(postCid)?.has(myPub) || myLikedSet().has(postCid)) return { ok: true, already: true };
    const doc: LikeDoc = { ts: Date.now(), re: postCid, shard: this.shard };
    const signed = await signDoc(id.identity, "like", doc);
    const myStripe = stripe(myPub);
    let room: PublicRoom | null = null;
    try {
      room = publicRoom(await feedRoom(this.shard, myStripe));
    } catch {}
    if (!room) return { ok: false, already: false };
    const r = await room.depositDoc(signed);
    if (!r.ok) return { ok: false, already: false };
    let set = this.#likes.get(postCid);
    if (!set) this.#likes.set(postCid, (set = new Set()));
    set.add(myPub);
    recordMyLike(postCid);
    await cachePut([
      {
        cid: signed.cid.toString(),
        kind: "doc",
        shard: this.shard,
        stripe: myStripe,
        ts: doc.ts,
        own: true,
        size: signed.bytes.length,
        lastUsed: Date.now(),
        raw: envBytes(ENV_DOC, signed.cid, signed.bytes),
      },
    ]);
    return { ok: true, already: false };
  }

  /** Comment on a post (comment doc, replyTo=postCid, same shard rooms). */
  async comment(postCid: string, authorPub: string, text: string): Promise<{ ok: boolean }> {
    const id = Session.identity;
    if (!id) return { ok: false };
    const clean = sanitizeText(text, COMMENT_MAX);
    if (!clean) return { ok: false };
    const doc: CommentDoc = { ts: Date.now(), to: authorPub, text: clean, replyTo: postCid };
    const signed = await signDoc(id.identity, "comment", doc);
    const myStripe = stripe(id.identity.publicKeyB64);
    let room: PublicRoom | null = null;
    try {
      room = publicRoom(await feedRoom(this.shard, myStripe));
    } catch {}
    if (!room) return { ok: false };
    const r = await room.depositDoc(signed);
    if (!r.ok) return { ok: false };
    let map = this.#comments.get(postCid);
    if (!map) this.#comments.set(postCid, (map = new Map()));
    map.set(signed.cid.toString(), { cidStr: signed.cid.toString(), pub: id.identity.publicKeyB64, doc });
    // own docs re-seed on every visit (§6) — comments included
    await cachePut([
      {
        cid: signed.cid.toString(),
        kind: "doc",
        shard: this.shard,
        stripe: myStripe,
        ts: doc.ts,
        own: true,
        size: signed.bytes.length,
        lastUsed: Date.now(),
        raw: envBytes(ENV_DOC, signed.cid, signed.bytes),
      },
    ]);
    return { ok: true };
  }

  /**
   * Locally delete a post I authored (or hide any post): local-only, plus
   * this device stops re-seeding it. Non-retractive (§7) — the UI says so.
   */
  hideLocal(cidStr: string): void {
    hidePostLocally(cidStr);
    const p = this.#posts.get(cidStr);
    if (p) {
      // also drop it (and its blocks) from the re-seed cache on this device
      const blockCids: string[] = [];
      for (const img of p.doc.imgs) blockCids.push(img.thumbCid, img.cid, ...this.#chunkCidsOf(img.thumbCid), ...this.#chunkCidsOf(img.cid));
      void cacheDelete([cidStr, ...blockCids]).catch(() => {});
    }
  }

  // ---- images ------------------------------------------------------------------

  /**
   * Data URL of one post image (thumb-first UX: callers ask for "thumb"
   * eagerly and "display" lazily). Blocks come from the replay walks or the
   * envelope cache; assembly is hash-verified and the DECODE is bounded
   * (decodeWithinBounds) before any URL reaches an <img>. Null = honest
   * "unavailable" (blocks aged out of the window).
   */
  async imageUrl(ref: PostImgRef, which: "thumb" | "display"): Promise<string | null> {
    const root = which === "thumb" ? ref.thumbCid : ref.cid;
    if (this.#imgUrls.has(root)) return this.#imgUrls.get(root) ?? null;
    await this.#ensureBlocks(root);
    const bytes =
      which === "thumb"
        ? await assembleBlocks(root, null, THUMB_MAX_BYTES, 4, this.#blocks)
        : await assembleBlocks(root, ref.bytes, POST_IMG_MAX_BYTES, 16, this.#blocks);
    let url: string | null = null;
    if (bytes) {
      const blob = new Blob([bytes as BlobPart], { type: ref.mime });
      if (await decodeWithinBounds(blob)) url = `data:${ref.mime};base64,${toB64(bytes)}`;
    }
    this.#imgUrls.set(root, url);
    return url;
  }

  /** Pull a root block (and its manifest chunks) from the envelope cache. */
  async #ensureBlocks(rootCidStr: string): Promise<void> {
    const load = async (cidStr: string): Promise<void> => {
      if (this.#blocks.has(cidStr)) return;
      const cached = await cacheGet(cidStr);
      if (!cached || cached.kind !== "block") return;
      const env = parseEnvelope(toB64(cached.raw as Bytes));
      if (env && env.type === ENV_BLOCK) this.#blocks.set(cidStr, env.body);
    };
    await load(rootCidStr);
    for (const c of this.#chunkCidsOf(rootCidStr)) await load(c);
    void cacheTouch([rootCidStr]).catch(() => {});
  }

  // ---- re-seed (§6) ------------------------------------------------------------

  async #reseed(): Promise<void> {
    if (this.#reseedDone) return;
    this.#reseedDone = true;
    await sleep(Math.random() * FeedTuning.reseedJitterMaxMs);
    await reseedShard(this.shard);
  }

  // ---- live valve (§6) ---------------------------------------------------------

  async #maybeJoinLive(): Promise<void> {
    const hub = Session.selfroom?.hub;
    if (!hub) return; // selfroom not up (first seconds) — the valve just stays off
    hub.ensureLive();
    if (!hub.live.enabled) return;
    const topic = await feedTopic(this.shard);
    if (this.#closed) return;
    hub.live.joinTopic(topic, (data) => void this.#onHead(data));
    this.#liveTopic = topic;
    // estimate AFTER subscribing (getSubscribers needs the mesh to gossip our
    // interest around); roll the §6 valve once the estimate had a beat
    setTimeout(() => {
      if (this.#closed || this.#liveTopic !== topic) return;
      const subs = hub.live.subscribersOf(topic);
      const p = Math.min(1, LIVE_TARGET_SUBS / Math.max(1, subs));
      if (Math.random() >= p) {
        hub.live.leaveTopic(topic);
        this.#liveTopic = null;
      }
    }, 3000);
  }

  async #onHead(data: Uint8Array): Promise<void> {
    const head = await verifyHead(data, this.shard);
    if (!head || this.#closed) return;
    const unknown = head.cids.some((c) => !this.#posts.has(c) && !this.#comments.has(c) && !this.#likes.has(c));
    if (!unknown) return;
    // fetch the announced docs over the MAILBOX (deliberately no bitswap):
    // a debounced forward refresh picks up whatever was just deposited. Beyond
    // the 1.5 s debounce, enforce a per-handle MINIMUM interval between
    // live-triggered refreshes so a flood of head announcements can never drive
    // more than one mailbox refresh per HEAD_MIN_REFRESH_MS (spam defense, §6).
    if (this.#refreshTimer) return;
    const sinceLast = Date.now() - this.#lastLiveRefreshAt;
    const delay = Math.max(HEAD_DEBOUNCE_MS, HEAD_MIN_REFRESH_MS - sinceLast);
    this.#refreshTimer = setTimeout(() => {
      this.#refreshTimer = null;
      if (this.#closed) return;
      this.#lastLiveRefreshAt = Date.now();
      void this.refresh()
        .then(() => {
          if (!this.#closed) this.onLiveUpdate();
        })
        .catch(() => {});
    }, delay);
  }
}

/** §6 feed browse entry point. */
export function openFeed(shard: string, opts?: { live?: boolean; initialPages?: number }): Promise<FeedHandle> {
  return FeedHandle.open(shard, opts);
}

// ---- re-seed pass (shared by handle + boot) ------------------------------------

/**
 * §6 re-seed deposits for one shard, from the raw-envelope cache: own docs
 * always (except locally-hidden ones — moderation via decay), plus ≤5 random
 * foreign docs older than 24 h, each with its cached blocks; ≤10 deposits per
 * room per visit. Callers own the jitter.
 */
export async function reseedShard(shard: string): Promise<void> {
  const docs = await cacheDocsOf(shard);
  if (docs.length === 0) return;
  const hidden = hiddenPosts();
  const now = Date.now();
  const budgets = new Map<number, number>();
  const roomOf = new Map<number, PublicRoom | null>();
  const depositEntry = async (e: CachedEnvelope): Promise<void> => {
    let room = roomOf.get(e.stripe);
    if (room === undefined) {
      try {
        room = publicRoom(await feedRoom(shard, e.stripe));
      } catch {
        room = null;
      }
      roomOf.set(e.stripe, room);
    }
    if (!room) return;
    const left = budgets.get(e.stripe) ?? RESEED_MAX_PER_ROOM;
    if (left <= 0) return;
    budgets.set(e.stripe, left - 1);
    await room.depositRaw(e.raw as Bytes).catch(() => {});
  };
  const depositWithBlocks = async (doc: CachedEnvelope): Promise<void> => {
    if (hidden.has(doc.cid)) return; // hidden content is never re-seeded (§6/§7)
    // P1: expired activities (and their joins) age out — never re-seeded
    if (doc.exp !== undefined && now - doc.exp > ACT_RESEED_GRACE_MS) return;
    await depositEntry(doc);
    for (const bc of doc.blockCids ?? []) {
      const b = await cacheGet(bc);
      if (b && b.kind === "block") await depositEntry(b);
    }
  };

  const own = docs.filter((d) => d.own);
  const foreignOld = docs.filter((d) => !d.own && now - d.ts >= RESEED_MIN_AGE_MS && !hidden.has(d.cid));
  // Fisher–Yates for the random-5 pick
  for (let i = foreignOld.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [foreignOld[i], foreignOld[j]] = [foreignOld[j], foreignOld[i]];
  }
  for (const d of own) await depositWithBlocks(d);
  for (const d of foreignOld.slice(0, RESEED_FOREIGN_DOCS)) await depositWithBlocks(d);
  void cacheTouch(docs.map((d) => d.cid)).catch(() => {});
}

/**
 * Boot-time re-seed for the LAST-VIEWED shard: a one-page-per-stripe replay
 * primes the cache (and proves the visit), then the §6 re-seed pass runs.
 * Jittered by the caller's boot delay + the §6 deposit jitter here.
 */
export async function bootReseedLastShard(): Promise<void> {
  const choice = loadShardChoice();
  if (!choice) return;
  const shard = `${choice.cat}|${choice.county}`;
  if (!isShard(shard)) return;
  const h = await FeedHandle.open(shard, { live: false, initialPages: 1 });
  h.close(); // FeedHandle.open already scheduled the jittered re-seed pass
}

// ---- activities publish (P1) ----------------------------------------------------

export interface ActivityInput {
  shard: string;
  title: string;
  desc: string;
  /** Activity window, epoch ms; publish requires start < end, end > now − 7 d. */
  start: number;
  end: number;
  loc?: string;
  /** Editing/cancelling an existing activity: its aid + the CURRENT seq. */
  aid?: string;
  prevSeq?: number;
  cancelled?: boolean;
  /** Group restriction: title stays public, desc/loc seal under the gid's key. */
  aud?: { gid: string };
  /** cid of the doc this edit supersedes — dropped from the re-seed cache. */
  replacesCid?: string;
}

export type ActivityOutcome =
  | { ok: true; cid: string; aid: string; seq: number }
  | { ok: false; reason: "invalid" | "offline" | "deposit" };

/**
 * Publish (or edit/cancel — same aid, bumped seq; LWW per (pub, aid)) one
 * activity into its shard's feed rooms (organizer's stripe — no new room
 * derivations). Group-restricted activities keep the TITLE public and seal
 * desc/loc under the group's CURRENT epoch key (§5b). Joins stay public
 * metadata either way (§7 — stated in-app).
 */
export async function publishActivity(input: ActivityInput): Promise<ActivityOutcome> {
  const id = Session.identity;
  if (!id) return { ok: false, reason: "offline" };
  const myPub = id.identity.publicKeyB64;
  if (!isShard(input.shard)) return { ok: false, reason: "invalid" };
  const title = sanitizeText(input.title, ACT_TITLE_MAX);
  const desc = sanitizeText(input.desc, ACT_DESC_MAX);
  const loc = input.loc ? sanitizeText(input.loc, ACT_LOC_MAX) : "";
  if (!title) return { ok: false, reason: "invalid" };
  const { start, end } = input;
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start <= 0 || start >= end)
    return { ok: false, reason: "invalid" };
  // §3 receiver ceiling (year 2100): never SIGN a doc every receiver rejects —
  // an author picking a wild future date would otherwise publish into the void
  if (start > ACT_TS_MAX || end > ACT_TS_MAX) return { ok: false, reason: "invalid" };
  if (end <= Date.now() - ACT_PUBLISH_PAST_MS) return { ok: false, reason: "invalid" };
  const aid = input.aid ?? toB64url(randomBytes(16));
  if (!isAid(aid)) return { ok: false, reason: "invalid" };
  const prevSeq = input.prevSeq ?? 0;
  if (!Number.isSafeInteger(prevSeq) || prevSeq < 0) return { ok: false, reason: "invalid" };
  const seq = prevSeq + 1;

  let doc: ActivityDoc;
  if (input.aud) {
    const audience = Session.audience;
    if (!audience) return { ok: false, reason: "offline" };
    const sealed = await audience.seal(input.aud.gid, encodeRestrictedActivity(desc, loc)).catch(() => null);
    if (!sealed) return { ok: false, reason: "invalid" };
    doc = {
      ts: Date.now(),
      aid,
      seq,
      shard: input.shard,
      title,
      desc: "",
      start,
      end,
      ...(input.cancelled ? { cancelled: true as const } : {}),
      visibility: "group",
      aud: { gidHint: sealed.gidHint, epoch: sealed.epoch },
      box: sealed.box,
    };
  } else {
    doc = {
      ts: Date.now(),
      aid,
      seq,
      shard: input.shard,
      title,
      desc,
      start,
      end,
      ...(loc ? { loc } : {}),
      ...(input.cancelled ? { cancelled: true as const } : {}),
      visibility: "public",
    };
  }

  const signed = await signDoc(id.identity, "activity", doc);
  const myStripe = stripe(myPub);
  let room: PublicRoom | null = null;
  try {
    room = publicRoom(await feedRoom(input.shard, myStripe));
  } catch {}
  if (!room) return { ok: false, reason: "offline" };
  const r = await room.depositDoc(signed);
  if (!r.ok) return { ok: false, reason: "deposit" };
  const cidStr = signed.cid.toString();
  await cachePut([
    {
      cid: cidStr,
      kind: "doc",
      shard: input.shard,
      stripe: myStripe,
      ts: doc.ts,
      own: true,
      size: signed.bytes.length,
      lastUsed: Date.now(),
      raw: envBytes(ENV_DOC, signed.cid, signed.bytes),
      exp: end,
    },
  ]);
  // the superseded doc loses LWW anyway — stop re-seeding it from this device
  if (input.replacesCid) void cacheDelete([input.replacesCid]).catch(() => {});
  void announceHeads(id.identity, input.shard, [cidStr]).catch(() => {});
  return { ok: true, cid: cidStr, aid, seq };
}

// ---- author activities strip (profile view, P1) ---------------------------------

export interface AuthorActivity {
  shard: string;
  org: string;
  aid: string;
  title: string;
  start: number;
  end: number;
  restricted: boolean;
}

/**
 * UPCOMING activities BY one author, resolved from the feed rooms of their
 * DECLARED shards (profile categories × county — the author-grid mechanism,
 * kind-filtered). Same honest limit as the grid: only what those rooms hold
 * within the TTL window is discoverable. LWW-folded per aid; cancelled and
 * expired activities are excluded; start ASC; ≤12.
 */
export async function loadAuthorActivities(
  pub: string,
  categories: string[],
  county: string,
): Promise<{ acts: AuthorActivity[]; reachedAll: boolean }> {
  let authorStripe: number;
  try {
    authorStripe = stripe(pub);
  } catch {
    return { acts: [], reachedAll: false };
  }
  const winners = new Map<string, { doc: ActivityDoc; cidStr: string }>();
  let reachedAll = true;
  for (const cat of categories.slice(0, 8)) {
    const shard = `${cat}|${county}`;
    if (!isShard(shard)) continue;
    let room: PublicRoom | null = null;
    try {
      room = publicRoom(await feedRoom(shard, authorStripe));
    } catch {}
    if (!room) {
      reachedAll = false;
      continue;
    }
    let before = MAX_BEFORE;
    let reached = false;
    // Stale-doc replay resilience (same rule as the permalink resolver): a
    // re-deposited OLD revision at the room head plus filler could hide the
    // newest revision below the base page budget. Whenever a page still
    // introduced or upgraded an aid winner, look one page deeper — stop after
    // the first page that adds nothing (bounded extra pages).
    for (let page = 0; page < 2 + AUTHOR_ACTS_EXTRA_PAGES; page++) {
      const p = await room.pageBefore(before, PAGE_LIMIT);
      if (p === null) break;
      reached = true;
      let improved = false;
      for (const m of p.messages) {
        const env = parseEnvelope(m.payload);
        if (!env || env.type !== ENV_DOC) continue;
        const v = await verifyDoc(env.body, { kinds: ["activity"], pub, shard, stripe: authorStripe, cid: env.cid });
        if (!v) continue;
        const doc = v.doc as ActivityDoc;
        const rec = { doc, cidStr: v.cidStr };
        const prev = winners.get(doc.aid);
        if (!prev || activityWins(rec, prev)) {
          winners.set(doc.aid, rec);
          improved = true;
        }
      }
      if (p.messages.length === 0 || !p.hasMore) break;
      before = p.messages[0].seq;
      if (page >= 1 && !improved) break; // one-extra-page rule past the base budget
    }
    if (!reached) reachedAll = false;
  }
  const now = Date.now();
  const acts = [...winners.values()]
    .filter((w) => w.doc.end >= now && w.doc.cancelled !== true)
    .sort((a, b) => a.doc.start - b.doc.start || (a.cidStr < b.cidStr ? -1 : 1))
    .slice(0, 12)
    .map((w) => ({
      shard: w.doc.shard,
      org: pub,
      aid: w.doc.aid,
      title: w.doc.title,
      start: w.doc.start,
      end: w.doc.end,
      restricted: w.doc.aud !== undefined,
    }));
  return { acts, reachedAll };
}

// ---- author grid (profile view, M5) -------------------------------------------

export interface GridPost {
  shard: string;
  cidStr: string;
  ts: number;
  img: PostImgRef | null;
  text: string;
  /** Audience-restricted post — the tile shows a lock, the permalink unseals. */
  restricted?: boolean;
}

export interface AuthorGrid {
  posts: GridPost[];
  /** Every walked room answered (false ⇒ the grid may be even more partial). */
  reachedAll: boolean;
  thumbUrl: (p: GridPost) => Promise<string | null>;
}

const gridCache = new Map<string, { at: number; grid: AuthorGrid }>();

/**
 * Posts BY one author, resolved from the feed rooms of their DECLARED shards
 * (profile categories × county) — the only shards a stranger can derive from
 * the profile. HONEST LIMIT (documented in-app): the grid shows only what is
 * discoverable there within the TTL window; posts in undeclared shards, or
 * older than the window, are invisible. ≤8 walks (one room per category —
 * the author's own stripe), 2 pages each.
 */
export async function loadAuthorGrid(pub: string, categories: string[], county: string): Promise<AuthorGrid> {
  const key = `${pub}|${categories.join(",")}|${county}`;
  const cached = gridCache.get(key);
  if (cached && Date.now() - cached.at < 300_000) return cached.grid;

  let authorStripe: number;
  try {
    authorStripe = stripe(pub);
  } catch {
    return { posts: [], reachedAll: false, thumbUrl: async () => null };
  }
  const blocks = new Map<string, Bytes>();
  const posts: GridPost[] = [];
  let reachedAll = true;
  for (const cat of categories.slice(0, 8)) {
    const shard = `${cat}|${county}`;
    if (!isShard(shard)) continue;
    let room: PublicRoom | null = null;
    try {
      room = publicRoom(await feedRoom(shard, authorStripe));
    } catch {}
    if (!room) {
      reachedAll = false;
      continue;
    }
    let before = MAX_BEFORE;
    let reached = false;
    for (let page = 0; page < 2; page++) {
      const p = await room.pageBefore(before, PAGE_LIMIT);
      if (p === null) break;
      reached = true;
      for (const m of p.messages) {
        const env = parseEnvelope(m.payload);
        if (!env) continue;
        if (env.type === ENV_BLOCK) {
          // verify-at-ingest (see #ingest): junk under a real cid must never win
          // the first-write-wins slot and break the genuine block's assembly
          const bc = env.cid.toString();
          if (blocks.size < 400 && !blocks.has(bc) && (await verifyBlock(env))) blocks.set(bc, env.body);
          continue;
        }
        if (env.type !== ENV_DOC) continue;
        const v = await verifyDoc(env.body, { kinds: ["post"], pub, shard, stripe: authorStripe, cid: env.cid });
        if (!v) continue;
        const doc = v.doc as PostDoc;
        posts.push({
          shard,
          cidStr: v.cidStr,
          ts: doc.ts,
          img: doc.imgs[0] ?? null,
          text: doc.text,
          ...(doc.aud ? { restricted: true } : {}),
        });
      }
      if (p.messages.length === 0 || !p.hasMore) break;
      before = p.messages[0].seq;
    }
    if (!reached) reachedAll = false;
  }

  const hidden = hiddenPosts();
  const unique = new Map<string, GridPost>();
  for (const p of posts) if (!hidden.has(p.cidStr)) unique.set(p.cidStr, p);
  const ordered = [...unique.values()].sort((a, b) => b.ts - a.ts || (b.cidStr > a.cidStr ? 1 : -1)).slice(0, 24);

  const urlMemo = new Map<string, string | null>();
  const grid: AuthorGrid = {
    posts: ordered,
    reachedAll,
    thumbUrl: async (p: GridPost) => {
      if (!p.img) return null;
      const root = p.img.thumbCid;
      if (urlMemo.has(root)) return urlMemo.get(root) ?? null;
      const bytes = await assembleBlocks(root, null, THUMB_MAX_BYTES, 4, blocks);
      let url: string | null = null;
      if (bytes) {
        const blob = new Blob([bytes as BlobPart], { type: p.img.mime });
        if (await decodeWithinBounds(blob)) url = `data:${p.img.mime};base64,${toB64(bytes)}`;
      }
      urlMemo.set(root, url);
      return url;
    },
  };
  gridCache.set(key, { at: Date.now(), grid });
  if (gridCache.size > 16) {
    const oldest = [...gridCache.entries()].sort((a, b) => a[1].at - b[1].at)[0];
    if (oldest) gridCache.delete(oldest[0]);
  }
  return grid;
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git