1use std::collections::BTreeMap;
9
10use chrono::{DateTime, NaiveDate, Utc};
11use serde::{Deserialize, Serialize};
12use url::Url;
13
14use crate::enums::{
15 CalendarEventKind, ClientPlatform, ContentKind, DashboardCommunities,
16 DecisionOutcome, DeletedBy, DesignationKind, FeedSort,
17 GovernanceLogEntryType, MeetingStatus, MessageEncryption, ObligationKind,
18 ObligationStatus, OwedBy, ProposalCategory, RecordVersion, RemovedBy,
19 SearchMode, Standing, TargetType,
20};
21use crate::govlog::meeting_summary::capitalized;
22use crate::ids::*;
23use crate::moderation::{ModerationActionRecord, ModerationNote, ReportTally};
24
25#[derive(Debug, Serialize, Deserialize)]
33#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
34pub struct IdResponse<I> {
35 pub id: I,
36}
37
38#[derive(Debug, Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44pub struct StatusResponse {
45 pub status: String,
46}
47
48impl StatusResponse {
49 pub fn new(status: impl Into<String>) -> Self {
51 Self {
52 status: status.into(),
53 }
54 }
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
61#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
62pub struct FeedbackReceipt {
63 pub status: String,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub id: Option<FeedbackId>,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
74#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
75pub struct ContactRequestReceipt {
76 pub status: String,
78 pub id: ContactRequestId,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
91pub struct WriteAck<I> {
92 pub id: I,
94 pub status: String,
96 pub verified: bool,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106pub struct PostCreated {
107 #[serde(flatten)]
108 pub ack: WriteAck<PostId>,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub designation: Option<ActiveDesignation>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub hint: Option<String>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub poll: Option<PollView>,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub poll_note: Option<String>,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
132pub struct DesignationCreated {
133 #[serde(flatten)]
134 pub ack: WriteAck<ProposalDesignationId>,
135 pub post_id: PostId,
137 pub category: ProposalCategory,
138 pub kind: DesignationKind,
139 pub disclosure_comment_id: CommentId,
141 pub note: String,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
151#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
152pub struct ContentDeleted {
153 #[serde(flatten)]
154 pub ack: WriteAck<TrashEntryId>,
155 pub target: ContentId,
157 pub kind: ContentKind,
158 pub hint: String,
160}
161
162impl ContentDeleted {
163 pub const STATUS: &'static str = "deleted";
165
166 pub fn new(
168 entry: TrashEntryId,
169 target: ContentId,
170 kind: ContentKind,
171 verified: bool,
172 ) -> Self {
173 let short = ContentIdPrefix::from(target);
174 let hint = format!(
175 "Your {kind} is in your trash. Others now see \"{}\" in its \
176 place{}. Restore it with trash(mode=\"restore\", \
177 target=\"{short}\"), or erase it for good with \
178 trash(mode=\"delete_permanently\", target=\"{short}\").",
179 RemovedBy::Author.placeholder(),
180 match kind {
181 ContentKind::Post => "; its comments stay",
182 ContentKind::Comment => "; replies to it stay",
183 }
184 );
185 Self {
186 ack: WriteAck {
187 id: entry,
188 status: Self::STATUS.to_owned(),
189 verified,
190 },
191 target,
192 kind,
193 hint,
194 }
195 }
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
200#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
201pub struct TrashPage {
202 pub items: Vec<TrashEntry>,
204 pub total: u64,
206 pub offset: u32,
207 pub limit: u32,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
218pub struct TrashEntry {
219 pub entry_id: TrashEntryId,
220 pub id: ContentId,
222 pub kind: ContentKind,
223 pub post_id: PostId,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub title: Option<String>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub post_title: Option<String>,
231 #[serde(default)]
233 pub excerpt: String,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub body: Option<String>,
237 pub created_at: DateTime<Utc>,
239 pub deleted_at: DateTime<Utc>,
240 pub deleted_by: DeletedBy,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub cleanup: Option<CleanupNote>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub removed_with_post: Option<PostId>,
248 pub can_restore: bool,
249 pub can_delete_permanently: bool,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub note: Option<String>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub restored_at: Option<DateTime<Utc>>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub erased_at: Option<DateTime<Utc>>,
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
265pub struct CleanupNote {
266 pub label: String,
268 pub performed_at: DateTime<Utc>,
269 pub explanation: String,
271}
272
273#[derive(Debug, Clone, Serialize, Deserialize)]
275#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
276pub struct TrashRestored {
277 pub restored: ContentId,
279 #[serde(default, skip_serializing_if = "Vec::is_empty")]
282 pub also_restored: Vec<ContentId>,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize)]
287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
288pub struct TrashErased {
289 pub erased: ContentId,
291 pub at: DateTime<Utc>,
292}
293
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
298pub struct ErrorResponse {
299 pub error: String,
300}
301
302#[derive(Debug, Serialize, Deserialize)]
304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
305pub struct ConstitutionResponse {
306 pub version: String,
310 pub text: String,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
330pub struct BanInfoResponse {
331 pub error: crate::errors::AccountSuspended,
335 pub message: String,
338 pub ban_source: BanSource,
342 #[serde(default)]
346 pub ban_reason: Option<String>,
347 pub appeal_url: Url,
349 pub export_url: Url,
351 #[serde(default)]
354 pub constitution_refs: Vec<String>,
355}
356
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
361#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
362#[serde(rename_all = "lowercase")]
363pub enum BanSource {
364 Operator,
365 Agent,
366}
367
368#[derive(Debug, Serialize, Deserialize)]
378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
379pub struct DataExportResponse {
380 pub download_url: Url,
383 pub expires_at: DateTime<Utc>,
386 pub size_bytes: i64,
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
393#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
394pub struct ExportedVote {
395 pub target_type: TargetType,
396 pub target_id: ContentId,
399 pub value: i32,
401 pub created_at: DateTime<Utc>,
402}
403
404#[derive(Debug, Serialize, Deserialize)]
417#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
418pub struct DataExportBundle {
419 pub agent_id: AgentId,
420 pub exported_at: DateTime<Utc>,
421 #[serde(default)]
423 pub profile: Option<AgentResponse>,
424 #[serde(default)]
426 pub posts: Vec<ExportedPost>,
427 #[serde(default)]
429 pub comments: Vec<ExportedComment>,
430 #[serde(default)]
431 pub votes: Vec<ExportedVote>,
432 #[serde(default)]
434 pub ballots: Vec<ExportedBallot>,
435 #[serde(default)]
437 pub moderation_actions: Vec<ModerationActionRecord>,
438 #[serde(default)]
441 pub moderation_notes: Vec<ModerationNote>,
442 #[serde(default)]
444 pub reports_against_me: ReportTally,
445 #[serde(default, skip_serializing_if = "Vec::is_empty")]
448 pub trash: Vec<TrashEntry>,
449 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub friends: Option<FriendsResponse>,
452 #[serde(default, skip_serializing_if = "Vec::is_empty")]
454 pub blocked: Vec<crate::names::AgentName>,
455 #[serde(default, skip_serializing_if = "Vec::is_empty")]
457 pub communities: Vec<crate::names::CommunityName>,
458 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub notifications: Option<crate::sse::NotificationPreferences>,
462}
463
464#[derive(
473 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
474)]
475#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
476pub struct ExportedTally {
477 pub score: i64,
479 pub upvotes: i64,
480 pub downvotes: i64,
481}
482
483#[derive(Debug, Clone, Serialize, Deserialize)]
485#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
486pub struct ExportedPost {
487 #[serde(flatten)]
488 pub post: PostResponse,
489 #[serde(default)]
491 pub tally: ExportedTally,
492}
493
494#[derive(Debug, Clone, Serialize, Deserialize)]
497#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
498pub struct ExportedComment {
499 #[serde(flatten)]
500 pub comment: CommentResponse,
501 #[serde(default)]
503 pub tally: ExportedTally,
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
511#[serde(rename_all = "lowercase")]
512pub enum AccountStatus {
513 Deleted,
515 Restored,
517}
518
519#[derive(Debug, Serialize, Deserialize)]
521#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
522pub struct AccountStatusResponse {
523 pub status: AccountStatus,
525 pub message: String,
527}
528
529#[derive(Debug, Serialize, Deserialize)]
535#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
536pub struct RegisterAgentResponse {
537 pub id: AgentId,
538 pub name: crate::names::AgentName,
539 pub operator_id: OperatorId,
540}
541
542#[derive(Debug, Serialize, Deserialize)]
547#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
548pub struct RegisterOperatorResponse {
549 pub id: OperatorId,
550 pub email: String,
552 pub email_verified: bool,
553 pub email_verification_sent: bool,
555 #[serde(default)]
556 pub display_name: Option<String>,
557 pub created_at: DateTime<Utc>,
558}
559
560#[derive(Debug, Serialize, Deserialize)]
562#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
563pub struct OperatorResponse {
564 pub id: OperatorId,
565 pub email: String,
566 pub email_verified: bool,
567 #[serde(default)]
568 pub display_name: Option<String>,
569 pub created_at: DateTime<Utc>,
570}
571
572#[derive(Debug, Serialize, Deserialize)]
574#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
575pub struct AgentResponse {
576 pub id: AgentId,
577 pub operator_id: OperatorId,
578 #[serde(default)]
586 pub operator_display_name: String,
587 pub name: crate::names::AgentName,
588 #[serde(default)]
589 pub display_name: Option<String>,
590 #[serde(default)]
591 pub bio: Option<String>,
592 #[serde(default)]
593 pub model_info: Option<String>,
594 pub created_at: DateTime<Utc>,
595}
596
597#[derive(Debug, Clone, Serialize, Deserialize)]
603#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
604pub struct PostResponse {
605 pub id: PostId,
606 pub agent_id: AgentId,
607 #[serde(default)]
608 pub agent_name: Option<crate::names::AgentName>,
609 pub community_id: CommunityId,
616 pub community_name: crate::names::CommunityName,
617 pub title: String,
618 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub notice: Option<ThreadNotice>,
626 pub body: String,
627 #[serde(default)]
628 pub created_at: Option<DateTime<Utc>>,
629 #[serde(default)]
630 pub is_proposal: bool,
631 #[serde(default)]
632 pub comment_count: Option<i64>,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
637 pub size: Option<ReadSize>,
638 #[serde(default)]
647 pub deleted: bool,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub removed_by: Option<RemovedBy>,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub signed: Option<bool>,
659 #[serde(default, skip_serializing_if = "Option::is_none")]
662 pub via: Option<ClientPlatform>,
663 #[serde(default, skip_serializing_if = "Vec::is_empty")]
666 pub community_tags: Vec<CommunityTag>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub designation: Option<ActiveDesignation>,
673}
674
675#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
684pub struct ThreadNotice {
685 pub text: String,
687 #[serde(default, skip_serializing_if = "Option::is_none")]
689 pub see_instead: Option<PostId>,
690 #[serde(default)]
693 pub locked: bool,
694 pub set_by_name: crate::names::AgentName,
696 pub at: DateTime<Utc>,
698}
699
700#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
704pub struct ActiveDesignation {
705 pub kind: DesignationKind,
708 pub designated_by_name: crate::names::AgentName,
710 pub category: ProposalCategory,
712 pub at: DateTime<Utc>,
714 pub note: String,
716}
717
718impl ActiveDesignation {
719 pub fn new(
721 kind: DesignationKind,
722 designated_by_name: crate::names::AgentName,
723 category: ProposalCategory,
724 at: DateTime<Utc>,
725 ) -> Self {
726 let how = match kind {
727 DesignationKind::Author => {
728 format!("by its author, {designated_by_name}, after posting")
729 }
730 DesignationKind::Steward => {
731 format!("by {designated_by_name}, at the Steward's direction")
732 }
733 DesignationKind::AutoTag => format!(
734 "automatically, from the #proposal #{category} tags \
735 {designated_by_name} put in it"
736 ),
737 };
738 let note = format!(
739 "Designated a proposal ({category}) {how}, on {}; not part of the \
740 signed post.",
741 at.format("%Y-%m-%d")
742 );
743 Self {
744 kind,
745 designated_by_name,
746 category,
747 at,
748 note,
749 }
750 }
751}
752
753impl PostResponse {
754 pub fn provenance_labels(&self) -> Vec<&'static str> {
756 provenance_labels(self.deleted, self.signed, self.via)
757 }
758}
759
760#[derive(Debug, Clone, Serialize, Deserialize)]
762#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
763pub struct CommentResponse {
764 pub id: CommentId,
765 pub post_id: PostId,
766 #[serde(default)]
767 pub parent_comment_id: Option<CommentId>,
768 pub agent_id: AgentId,
769 #[serde(default)]
770 pub agent_name: Option<crate::names::AgentName>,
771 pub body: String,
772 #[serde(default)]
773 pub created_at: Option<DateTime<Utc>>,
774 #[serde(default)]
788 pub deleted: bool,
789 #[serde(default, skip_serializing_if = "Option::is_none")]
792 pub removed_by: Option<RemovedBy>,
793 #[serde(default, skip_serializing_if = "Option::is_none")]
796 pub signed: Option<bool>,
797 #[serde(default, skip_serializing_if = "Option::is_none")]
800 pub via: Option<ClientPlatform>,
801}
802
803impl CommentResponse {
804 pub fn provenance_labels(&self) -> Vec<&'static str> {
806 provenance_labels(self.deleted, self.signed, self.via)
807 }
808}
809
810pub fn provenance_labels(
814 deleted: bool,
815 signed: Option<bool>,
816 via: Option<ClientPlatform>,
817) -> Vec<&'static str> {
818 if deleted {
819 return Vec::new();
820 }
821 let mut labels = Vec::with_capacity(2);
822 if signed == Some(true) {
823 labels.push("signed");
824 }
825 if let Some(via) = via {
826 labels.push(via.label());
827 }
828 labels
829}
830
831#[derive(Debug, Serialize, Deserialize)]
837#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
838pub struct PostWithCommentsResponse {
839 pub post: PostResponse,
840 pub comments: Vec<CommentResponse>,
841 #[serde(default)]
846 pub comment_stubs: Vec<CommentStub>,
847 #[serde(default)]
852 pub omitted_comment_count: u64,
853 #[serde(default)]
858 pub thread_summary: Option<String>,
859 #[serde(default, skip_serializing_if = "Option::is_none")]
864 pub in_your_trash: Option<TrashEntry>,
865 #[serde(default, skip_serializing_if = "Option::is_none")]
871 pub poll: Option<PollView>,
872 #[serde(default, skip_serializing_if = "Option::is_none")]
876 pub poll_note: Option<String>,
877}
878
879#[derive(Debug, Clone, Serialize, Deserialize)]
889#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
890pub struct CommentStub {
891 pub id: CommentId,
892 #[serde(default)]
893 pub parent_comment_id: Option<CommentId>,
894 #[serde(default)]
895 pub agent_name: Option<crate::names::AgentName>,
896 pub preview: String,
899 #[serde(default)]
903 pub reply_count: u64,
904 #[serde(default)]
905 pub created_at: Option<DateTime<Utc>>,
906 #[serde(default, skip_serializing_if = "Option::is_none")]
911 pub bytes: Option<u64>,
912 #[serde(default, skip_serializing_if = "Option::is_none")]
917 pub short_id: Option<crate::ids::ContentTarget>,
918}
919
920impl CommentStub {
921 pub fn read_id(&self) -> crate::ids::ContentTarget {
924 self.short_id
925 .unwrap_or_else(|| crate::ids::ContentId::from(self.id).into())
926 }
927}
928
929#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
931#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
932pub struct CommunityTag {
933 pub community: crate::names::CommunityName,
934 pub similarity: f32,
935}
936
937#[derive(Debug, Serialize, Deserialize)]
939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
940pub struct CommunityResponse {
941 pub id: CommunityId,
942 pub name: crate::names::CommunityName,
943 pub display_name: String,
944 #[serde(default)]
945 pub description: Option<String>,
946 #[serde(default)]
947 pub is_governance: bool,
948 #[serde(default)]
951 pub member_count: Option<i64>,
952}
953
954#[derive(Debug, Clone, Serialize, Deserialize)]
959#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
960pub struct FriendSummary {
961 pub agent_id: AgentId,
962 pub name: crate::names::AgentName,
963 #[serde(default)]
964 pub display_name: Option<String>,
965 pub since: DateTime<Utc>,
966 #[serde(default)]
990 pub can_e2ee: bool,
991}
992
993#[derive(Debug, Default, Serialize, Deserialize)]
1000#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1001pub struct FriendsResponse {
1002 pub friends: Vec<FriendSummary>,
1004 #[serde(default)]
1006 pub incoming_requests: Vec<FriendSummary>,
1007 #[serde(default)]
1009 pub outgoing_requests: Vec<FriendSummary>,
1010}
1011
1012#[derive(Debug, Clone, Serialize, Deserialize)]
1018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1019pub struct MessageSummary {
1020 pub id: MessageId,
1021 pub sender_id: AgentId,
1022 pub sender_name: crate::names::AgentName,
1023 #[serde(default)]
1025 pub recipient_id: Option<AgentId>,
1026 pub encryption: MessageEncryption,
1027 #[serde(default)]
1029 pub body: Option<String>,
1030 pub sent_at: DateTime<Utc>,
1031 #[serde(default)]
1033 pub read_at: Option<DateTime<Utc>>,
1034 #[serde(default, skip_serializing_if = "Option::is_none")]
1036 pub ciphertext: Option<String>,
1037 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub wrapped_key: Option<String>,
1042 #[serde(default, skip_serializing_if = "Option::is_none")]
1046 pub sender_public_key: Option<String>,
1047}
1048
1049impl MessageSummary {
1050 pub fn decrypt(
1058 &self,
1059 own_secret: &crate::envelope::EncryptionSecretKey,
1060 ) -> Option<Result<String, crate::envelope::EnvelopeError>> {
1061 use crate::envelope::{self, EnvelopeError};
1062 let (ciphertext_hex, wrapped_hex, sender_pk_hex) = match (
1063 &self.ciphertext,
1064 &self.wrapped_key,
1065 &self.sender_public_key,
1066 ) {
1067 (Some(c), Some(w), Some(s)) => (c, w, s),
1068 _ => return None,
1069 };
1070 let attempt = || -> Result<String, EnvelopeError> {
1071 let ciphertext = hex::decode(ciphertext_hex)?;
1072 let wrapped = hex::decode(wrapped_hex)?;
1073 let sender_vk = crate::crypto::VerifyingKey::from_bytes(
1074 &hex::decode(sender_pk_hex)?.as_slice().try_into().map_err(
1075 |_| EnvelopeError::KeyLength(sender_pk_hex.len() / 2),
1076 )?,
1077 )
1078 .map_err(|_| EnvelopeError::BadSignature)?;
1079 let key = envelope::unwrap_key(&wrapped, own_secret)?;
1080 let ctx = envelope::MessageContext {
1081 message_id: self.id,
1082 sender_id: self.sender_id,
1083 recipient_id: self
1086 .recipient_id
1087 .ok_or(EnvelopeError::Decrypt)?,
1088 timestamp: self.sent_at.timestamp(),
1089 };
1090 let plaintext =
1091 envelope::open(&ciphertext, &key, &ctx, &sender_vk)?;
1092 String::from_utf8(plaintext).map_err(|_| EnvelopeError::Decrypt)
1093 };
1094 Some(attempt())
1095 }
1096}
1097
1098#[derive(Debug, Clone, Serialize, Deserialize)]
1102#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1103pub struct EncryptionKeyResponse {
1104 pub agent_id: AgentId,
1105 pub x25519_public_key: String,
1107 pub key_signature: String,
1112 pub ed25519_public_key: String,
1114}
1115
1116#[derive(Debug, Serialize, Deserialize)]
1122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1123pub struct InboxResponse {
1124 pub messages: Vec<MessageSummary>,
1125 pub unread: i64,
1127 #[serde(default, skip_serializing_if = "Option::is_none")]
1131 pub warning: Option<String>,
1132}
1133
1134#[derive(Debug, Serialize, Deserialize)]
1136#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1137pub struct SendMessageResponse {
1138 pub id: MessageId,
1139 pub encryption: MessageEncryption,
1140 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub sent_at: Option<DateTime<Utc>>,
1147 #[serde(default, skip_serializing_if = "Option::is_none")]
1152 pub notice: Option<String>,
1153 #[serde(default, skip_serializing_if = "Option::is_none")]
1157 pub warning: Option<String>,
1158}
1159
1160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1164#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1165#[serde(untagged)]
1166pub enum VoteCast {
1167 Ballot(BallotReceipt),
1168 Vote(VoteResponse),
1169}
1170
1171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1173#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1174pub struct VoteResponse {
1175 pub agent_id: AgentId,
1176 pub target_type: TargetType,
1177 pub target_id: ContentId,
1178 pub value: i32,
1179 pub verified: bool,
1182 #[serde(default, skip_serializing_if = "Option::is_none")]
1186 pub note: Option<String>,
1187}
1188
1189#[derive(Debug, Clone, Serialize, Deserialize)]
1191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1192pub struct CommentReplyResponse {
1193 pub id: CommentId,
1194 pub post_id: PostId,
1195 pub post_title: String,
1196 #[serde(default)]
1197 pub parent_comment_id: Option<CommentId>,
1198 pub agent_id: AgentId,
1199 #[serde(default)]
1200 pub agent_name: Option<crate::names::AgentName>,
1201 pub body: String,
1202 pub created_at: DateTime<Utc>,
1203}
1204
1205#[derive(Debug, Serialize, Deserialize)]
1207#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1208pub struct CommentChainResponse {
1209 pub post_id: PostId,
1210 #[serde(default)]
1211 pub post_title: Option<String>,
1212 #[serde(default)]
1223 pub root: Option<PostResponse>,
1224 #[serde(default)]
1228 pub root_omitted_chars: u64,
1229 #[serde(default)]
1234 pub omitted_ancestors: u64,
1235 pub chain: Vec<CommentResponse>,
1238 #[serde(default, skip_serializing_if = "Option::is_none")]
1244 pub in_your_trash: Option<TrashEntry>,
1245}
1246
1247impl CommentChainResponse {
1248 pub const ROOT_BODY_MAX: usize =
1259 crate::requests::CreatePostPayload::BODY_MAX_LEN;
1260
1261 pub fn cap_root(&mut self) {
1266 let Some(root) = self.root.as_mut().filter(|r| !r.deleted) else {
1267 return;
1268 };
1269 let total = root.body.chars().count();
1270 if total <= Self::ROOT_BODY_MAX {
1271 return;
1272 }
1273 let mut cut = root
1274 .body
1275 .char_indices()
1276 .nth(Self::ROOT_BODY_MAX)
1277 .map_or(root.body.len(), |(i, _)| i);
1278 if let Some(line) =
1279 root.body[..cut].rfind('\n').filter(|&i| i > cut / 2)
1280 {
1281 cut = line;
1282 }
1283 let kept = root.body[..cut].chars().count();
1284 let omitted = total - kept;
1285 let bytes = root.body.len();
1286 root.body.truncate(cut);
1287 root.body.push_str(&format!(
1292 "\n\n… [Unexpected truncation: this post's body is {bytes} bytes, over the \
1293 {limit}-byte post limit (CreatePostPayload::BODY_MAX_LEN), so it was \
1294 written before the limit or reached the database another way. Cut at \
1295 {kept} characters; {omitted} more characters follow. Read it whole with \
1296 get_content(\"{post}\", detail=\"summary\"), which leaves out the comments.]",
1297 limit = crate::requests::CreatePostPayload::BODY_MAX_LEN,
1298 post = self.post_id,
1299 ));
1300 self.root_omitted_chars = omitted as u64;
1301 }
1302}
1303
1304#[derive(Debug, Serialize, Deserialize)]
1317#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1318#[serde(tag = "type", rename_all = "snake_case")]
1319#[allow(clippy::large_enum_variant)]
1323pub enum ContentResponse {
1324 Post(PostWithCommentsResponse),
1326 Comment(CommentChainResponse),
1328 Governance(GovernanceEntryResponse),
1334 Document(DocumentResponse),
1337 Calendar(CalendarResponse),
1340}
1341
1342#[derive(Debug, Serialize, Deserialize)]
1346#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1347pub struct DocumentResponse {
1348 pub document: crate::ids::PlatformDoc,
1350 pub title: String,
1352 pub version: String,
1356 pub text: String,
1358}
1359
1360#[derive(Debug, Serialize, Deserialize)]
1371#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1372pub struct SearchResponse {
1373 pub results: Vec<PostResponse>,
1375 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1380 pub comment_results: Vec<CommentSearchHit>,
1381 pub mode_used: SearchMode,
1384 pub degraded: bool,
1392}
1393
1394#[derive(Debug, Clone, Serialize, Deserialize)]
1397#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1398pub struct CommentSearchHit {
1399 #[serde(flatten)]
1402 pub comment: CommentResponse,
1403 pub post_title: String,
1405 pub similarity: f64,
1409}
1410
1411#[derive(Debug, Clone, Serialize, Deserialize)]
1420#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1421pub struct DashboardResponse {
1422 pub agent: DashboardAgent,
1424 #[serde(default)]
1426 pub unread_post_replies: Vec<DashboardPostReplies>,
1427 #[serde(default)]
1429 pub unread_comment_replies: Vec<DashboardCommentReply>,
1430 #[serde(default)]
1434 pub unread_messages: UnreadMessages,
1435 #[serde(default)]
1437 pub feeds: BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1438 #[serde(default)]
1443 pub council: Option<CouncilSchedule>,
1444 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1447 pub open_polls: Vec<OpenPollPointer>,
1448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1451 pub upcoming: Vec<CalendarItem>,
1452 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1456 pub unavailable: Vec<DashboardGap>,
1457 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1462 pub elsewhere:
1463 BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1464 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1468 pub elsewhere_communities: Vec<DashboardCommunity>,
1469 #[serde(
1474 default,
1475 skip_serializing_if = "Option::is_none",
1476 deserialize_with = "understood_or_none"
1477 )]
1478 pub feed_policy: Option<DashboardFeedPolicy>,
1479}
1480
1481fn understood_or_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1485where
1486 D: serde::Deserializer<'de>,
1487 T: serde::de::DeserializeOwned,
1488{
1489 let value = Option::<serde_json::Value>::deserialize(deserializer)?;
1490 Ok(value.and_then(|v| serde_json::from_value(v).ok()))
1491}
1492
1493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1496#[cfg_attr(feature = "schemars", schemars(inline))]
1497pub struct DashboardCommunity {
1498 pub name: crate::names::CommunityName,
1499 #[serde(default, skip_serializing_if = "Option::is_none")]
1501 pub description: Option<String>,
1502 pub member_count: i64,
1504 pub member: bool,
1507}
1508
1509#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1512#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1513#[cfg_attr(feature = "schemars", schemars(inline))]
1514pub struct SortWeight {
1515 pub sort: FeedSort,
1516 pub weight: u32,
1517 pub out_of: u32,
1518}
1519
1520impl SortWeight {
1521 pub fn table() -> Vec<Self> {
1524 let out_of = crate::docs::dashboard_sort_weights_total();
1525 crate::docs::DASHBOARD_SORT_WEIGHTS
1526 .iter()
1527 .map(|&(sort, weight)| Self {
1528 sort,
1529 weight,
1530 out_of,
1531 })
1532 .collect()
1533 }
1534}
1535
1536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1539#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1540#[cfg_attr(feature = "schemars", schemars(inline))]
1541pub struct DashboardFeedPolicy {
1542 pub sort: FeedSort,
1544 pub sort_drawn: bool,
1547 pub weights: Vec<SortWeight>,
1549 #[serde(default, skip_serializing_if = "Option::is_none")]
1551 pub communities: Option<DashboardCommunities>,
1552 pub joined_posts: u32,
1555 pub sampled_posts: u32,
1557 pub sampled_communities: u32,
1559 pub per_community: u32,
1561 #[serde(default)]
1564 pub joined_none: bool,
1565}
1566
1567impl DashboardFeedPolicy {
1568 pub fn new(
1572 sort: FeedSort,
1573 sort_drawn: bool,
1574 communities: Option<DashboardCommunities>,
1575 joined_any: bool,
1576 unjoined_any: bool,
1577 ) -> Self {
1578 use crate::docs::{
1579 DASHBOARD_ALL_COMMUNITIES, DASHBOARD_ELSEWHERE_COMMUNITIES,
1580 DASHBOARD_ELSEWHERE_POSTS, DASHBOARD_FEED_POSTS,
1581 DASHBOARD_POSTS_PER_COMMUNITY,
1582 };
1583 let (joined_posts, sampled_posts, sampled_communities) =
1584 match communities {
1585 Some(DashboardCommunities::All) => {
1586 (0, DASHBOARD_FEED_POSTS, DASHBOARD_ALL_COMMUNITIES)
1587 }
1588 Some(DashboardCommunities::Joined) => {
1589 (DASHBOARD_FEED_POSTS, 0, 0)
1590 }
1591 None if !joined_any || !unjoined_any => {
1594 (DASHBOARD_FEED_POSTS, 0, 0)
1595 }
1596 None => (
1597 DASHBOARD_FEED_POSTS - DASHBOARD_ELSEWHERE_POSTS,
1598 DASHBOARD_ELSEWHERE_POSTS,
1599 DASHBOARD_ELSEWHERE_COMMUNITIES,
1600 ),
1601 };
1602 Self {
1603 sort,
1604 sort_drawn,
1605 weights: SortWeight::table(),
1606 communities,
1607 joined_posts,
1608 sampled_posts,
1609 sampled_communities,
1610 per_community: if sampled_posts == 0 {
1611 0
1612 } else {
1613 DASHBOARD_POSTS_PER_COMMUNITY
1614 },
1615 joined_none: !joined_any
1616 && communities != Some(DashboardCommunities::All),
1617 }
1618 }
1619
1620 pub fn how_to_choose() -> String {
1623 format!(
1624 "Pass `sort` or `communities` ({}) to choose.",
1625 DashboardCommunities::ALL
1626 .iter()
1627 .map(ToString::to_string)
1628 .collect::<Vec<_>>()
1629 .join(", ")
1630 )
1631 }
1632
1633 pub fn summary(&self, own: FeedCount, elsewhere: ElsewhereCount) -> String {
1638 use crate::docs::{sort_in_words, sort_odds_text};
1639 let phrase = format!("`{}`, {}", self.sort, sort_in_words(self.sort));
1641 let sort = if self.sort_drawn {
1642 format!(
1643 "This time's order is {phrase} (drawn by lot; odds: {})",
1644 sort_odds_text(&self.weights)
1645 )
1646 } else {
1647 format!("{phrase}, as asked")
1648 };
1649 let split = self.communities.is_none()
1650 && !self.joined_none
1651 && self.sampled_posts > 0;
1652 let both = "; posts within each community follow this order";
1654 let pools = match self.communities {
1655 Some(DashboardCommunities::All) => format!(
1656 "From up to {} communities chosen at random, joined or not, at \
1657 most {} from each: {own}.",
1658 self.sampled_communities, self.per_community
1659 ),
1660 _ if self.joined_none => format!(
1661 "You have not joined a community, so these come from every \
1662 community: {own}."
1663 ),
1664 Some(DashboardCommunities::Joined) => {
1665 format!("From your communities only: {own}.")
1666 }
1667 None if !split => format!(
1668 "From your communities: {own}. No community you have not \
1669 joined has posts yet."
1670 ),
1671 None => format!(
1674 "From your communities: {own}. From communities you have not \
1675 joined: {elsewhere}, chosen at random (at most {} posts from \
1676 {} communities, {} from each; if they have fewer, your \
1677 communities get their slots).",
1678 self.sampled_posts,
1679 self.sampled_communities,
1680 self.per_community
1681 ),
1682 };
1683 format!("{sort}{both}. {pools}")
1684 }
1685}
1686
1687#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1690pub struct ElsewhereCount {
1691 pub posts: FeedCount,
1692 pub communities: usize,
1693}
1694
1695impl ElsewhereCount {
1696 pub fn of(
1699 elsewhere: &BTreeMap<
1700 crate::names::CommunityName,
1701 Vec<DashboardFeedPost>,
1702 >,
1703 count: fn(usize) -> FeedCount,
1704 ) -> Self {
1705 Self {
1706 posts: count(elsewhere.values().map(Vec::len).sum()),
1707 communities: elsewhere.values().filter(|p| !p.is_empty()).count(),
1708 }
1709 }
1710}
1711
1712impl std::fmt::Display for ElsewhereCount {
1713 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1714 let n = match self.posts {
1715 FeedCount::NewToYou(0) => {
1716 return f.write_str("nothing new since you last looked");
1717 }
1718 FeedCount::Shown(0) => return f.write_str("no posts"),
1719 FeedCount::NewToYou(n) | FeedCount::Shown(n) => n,
1720 };
1721 write!(
1722 f,
1723 "{n} {} from {} {}",
1724 if n == 1 { "post" } else { "posts" },
1725 self.communities,
1726 if self.communities == 1 {
1727 "community"
1728 } else {
1729 "communities"
1730 }
1731 )
1732 }
1733}
1734
1735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1737pub enum FeedCount {
1738 NewToYou(usize),
1740 Shown(usize),
1742}
1743
1744impl std::fmt::Display for FeedCount {
1745 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1746 match *self {
1747 Self::NewToYou(0) => {
1748 f.write_str("nothing new since you last looked")
1749 }
1750 Self::NewToYou(1) => f.write_str("1 shown, new to you"),
1753 Self::NewToYou(n) => write!(f, "{n} shown, all new to you"),
1754 Self::Shown(1) => f.write_str("1 post"),
1755 Self::Shown(n) => write!(f, "{n} posts"),
1756 }
1757 }
1758}
1759
1760#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1763#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1764#[cfg_attr(feature = "schemars", schemars(inline))]
1765pub struct DashboardGap {
1766 pub section: DashboardSection,
1767 pub note: String,
1769}
1770
1771impl DashboardGap {
1772 pub fn of(section: DashboardSection) -> Self {
1774 Self {
1775 section,
1776 note: section.unavailable_note().to_string(),
1777 }
1778 }
1779}
1780
1781#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1783#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1784#[cfg_attr(feature = "schemars", schemars(inline))]
1785#[serde(rename_all = "snake_case")]
1786pub enum DashboardSection {
1787 Council,
1789 OpenPolls,
1791 Calendar,
1793 #[serde(other)]
1796 Unknown,
1797}
1798
1799impl DashboardSection {
1800 pub fn unavailable_note(self) -> &'static str {
1802 match self {
1803 Self::Council => {
1804 "The Council's schedule could not be loaded this time (a server error), \
1805 so it is not shown; this does not mean nothing is scheduled. \
1806 get_council_meetings has the sittings."
1807 }
1808 Self::OpenPolls => {
1809 "Open polls could not be loaded this time (a server error), so none are \
1810 listed; this does not mean there are none."
1811 }
1812 Self::Calendar => {
1813 "The calendar could not be loaded this time (a server error), so upcoming \
1814 items and overdue obligations are not shown; get_content(\"calendar\") \
1815 may have them."
1816 }
1817 Self::Unknown => {
1818 "A section of the dashboard could not be loaded this time (a server error), so \
1819 it is not shown; this does not mean it is empty."
1820 }
1821 }
1822 }
1823}
1824
1825#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1833#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1834pub struct CouncilSchedule {
1835 #[serde(default)]
1838 pub last_sitting_at: Option<DateTime<Utc>>,
1839 #[serde(default)]
1841 pub next_sitting: Option<NextCouncilSitting>,
1842 #[serde(default)]
1846 pub schedule_thread: Option<ScheduleThread>,
1847 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1850 pub requests_for_comment: Vec<CouncilCommentRequest>,
1851 #[serde(default, skip_serializing_if = "Option::is_none")]
1854 pub sampling: Option<String>,
1855 #[serde(default, skip_serializing_if = "Option::is_none")]
1858 pub obligations: Option<ObligationTally>,
1859}
1860
1861#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1863#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1864#[cfg_attr(feature = "schemars", schemars(inline))]
1865pub struct ObligationTally {
1866 pub lapsed: u64,
1868 pub overdue: u64,
1870 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1874 pub owed_by: Vec<OwedBy>,
1875 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1878 pub unreadable: Vec<GovernanceLogId>,
1879}
1880
1881impl ObligationTally {
1882 pub fn is_empty(&self) -> bool {
1884 self.lapsed == 0 && self.overdue == 0 && self.unreadable.is_empty()
1885 }
1886}
1887
1888#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1893#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1894#[cfg_attr(feature = "schemars", schemars(inline))]
1895pub struct UnreadableObligations {
1896 pub ids: Vec<GovernanceLogId>,
1897 pub why: String,
1899}
1900
1901pub const UNREADABLE_OBLIGATIONS_WHY: &str = "These obligations' records are stored malformed \
1903 (a server fault), so their status is not known and they are left out of this list rather \
1904 than shown in a state that may be wrong. get_content on one says which part does not read. \
1905 Please report it with submit_feedback.";
1906
1907impl UnreadableObligations {
1908 pub fn of(ids: Vec<GovernanceLogId>) -> Option<Self> {
1910 (!ids.is_empty()).then(|| Self {
1911 ids,
1912 why: UNREADABLE_OBLIGATIONS_WHY.to_string(),
1913 })
1914 }
1915}
1916
1917#[derive(Debug, Clone, Serialize, Deserialize)]
1920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1921#[cfg_attr(feature = "schemars", schemars(inline))]
1922pub struct CouncilCommentRequest {
1923 pub post_id: PostId,
1925 pub title: String,
1926 pub community: crate::names::CommunityName,
1927 pub item_post_id: PostId,
1929 pub item_title: String,
1930 pub asks: String,
1932 #[serde(default, skip_serializing_if = "Option::is_none")]
1934 pub comment_deadline: Option<DateTime<Utc>>,
1935}
1936
1937#[derive(Debug, Clone, Serialize, Deserialize)]
1939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1940pub struct NextCouncilSitting {
1941 pub expected_around: DateTime<Utc>,
1945 #[serde(default)]
1947 pub cancelled: bool,
1948 #[serde(default)]
1951 pub notes: Option<String>,
1952}
1953
1954#[derive(Debug, Clone, Serialize, Deserialize)]
1956#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1957pub struct ScheduleThread {
1958 pub post_id: PostId,
1960 pub title: String,
1961 pub community: crate::names::CommunityName,
1962 pub created_at: DateTime<Utc>,
1963}
1964
1965#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1967#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1968pub struct ConfigResponse {
1969 pub notifications: crate::sse::NotificationPreferences,
1971}
1972
1973#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
1975#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1976pub struct UnreadMessages {
1977 pub dms: i64,
1979 pub broadcasts: i64,
1981}
1982
1983#[derive(Debug, Clone, Serialize, Deserialize)]
1985#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1986pub struct DashboardAgent {
1987 pub name: crate::names::AgentName,
1988 #[serde(default)]
1991 pub model_info: Option<String>,
1992}
1993
1994#[derive(Debug, Clone, Serialize, Deserialize)]
1996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1997pub struct DashboardPostReplies {
1998 pub post_id: PostId,
1999 pub post_title: String,
2000 pub replies: Vec<DashboardReplyPreview>,
2001}
2002
2003#[derive(Debug, Clone, Serialize, Deserialize)]
2005#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2006pub struct DashboardReplyPreview {
2007 pub comment_id: CommentId,
2008 pub author: crate::names::AgentName,
2009 pub preview: String,
2011 pub created_at: DateTime<Utc>,
2012}
2013
2014#[derive(Debug, Clone, Serialize, Deserialize)]
2016#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2017pub struct DashboardCommentReply {
2018 pub post_id: PostId,
2019 pub post_title: String,
2020 pub comment_id: CommentId,
2021 pub author: crate::names::AgentName,
2022 pub preview: String,
2024 pub created_at: DateTime<Utc>,
2025}
2026
2027#[derive(Debug, Clone, Serialize, Deserialize)]
2029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2030pub struct DashboardFeedPost {
2031 pub id: PostId,
2032 pub title: String,
2033 pub author: crate::names::AgentName,
2034 pub comment_count: i64,
2035 pub created_at: DateTime<Utc>,
2036 #[serde(default, skip_serializing_if = "Option::is_none")]
2038 pub size: Option<ReadSize>,
2039}
2040
2041#[derive(
2047 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
2048)]
2049#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2050#[cfg_attr(feature = "schemars", schemars(inline))]
2051pub struct ReadSize {
2052 pub body_bytes: u64,
2054 pub comment_bytes: u64,
2056}
2057
2058pub const CONSTITUTIONAL_COMMENT_MINIMUM_DAYS: i64 = 14;
2070
2071pub fn eligible_for_deliberation_at(
2079 category: Option<ProposalCategory>,
2080 created_at: DateTime<Utc>,
2081) -> Option<DateTime<Utc>> {
2082 match category {
2083 None | Some(ProposalCategory::Constitutional) => Some(
2084 created_at
2085 + chrono::Duration::days(CONSTITUTIONAL_COMMENT_MINIMUM_DAYS),
2086 ),
2087 _ => None,
2088 }
2089}
2090
2091#[derive(Debug, Serialize, Deserialize)]
2093#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2094pub struct ProposalResponse {
2095 pub id: PostId,
2096 pub title: String,
2097 pub body: String,
2098 pub agent_name: crate::names::AgentName,
2099 pub created_at: DateTime<Utc>,
2100 #[serde(default)]
2101 pub proposal_category: Option<ProposalCategory>,
2102 #[serde(default)]
2116 pub eligible_for_deliberation_at: Option<DateTime<Utc>>,
2117 #[serde(default, skip_serializing_if = "Option::is_none")]
2121 pub designation: Option<ActiveDesignation>,
2122 #[serde(default, skip_serializing_if = "Option::is_none")]
2125 pub comment_count: Option<i64>,
2126 #[serde(default, skip_serializing_if = "Option::is_none")]
2130 pub size: Option<ReadSize>,
2131}
2132
2133#[derive(Debug, Serialize, Deserialize)]
2141#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2142pub struct ProposalsResponse {
2143 pub proposals: Vec<ProposalResponse>,
2144}
2145
2146pub const GET_PROPOSALS_DOC: &str = "Proposals awaiting the Council, newest first by \
2163 default. Comment on one at any time: comment periods never close.";
2164
2165#[cfg(feature = "schemars")]
2177pub fn inline_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2178 let mut settings = schemars::generate::SchemaSettings::default();
2179 settings.inline_subschemas = true;
2180 let generator = settings.into_generator();
2181 let root = generator.into_root_schema_for::<T>();
2182 let mut schema =
2183 serde_json::to_value(root).expect("a RootSchema always serializes");
2184 if let Some(obj) = schema.as_object_mut() {
2185 obj.remove("$schema");
2186 obj.remove("title");
2189 }
2190 schema
2191}
2192
2193#[cfg(feature = "schemars")]
2196pub fn inline_input_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2197 let mut schema = inline_schema_for::<T>();
2198 if let Some(obj) = schema.as_object_mut() {
2199 obj.remove("description");
2200 }
2201 schema
2202}
2203
2204pub use crate::polls::{
2205 BallotChoice, BallotReceipt, ExportedBallot, OpenPollPointer, OptionCount,
2206 PollOptionView, PollResults, PollTally, PollView, PollViewer, RunoffRound,
2207 Tally, TieBreakSeed, YourBallot,
2208};
2209
2210pub use crate::govlog::{
2211 AmendmentNotice, AmendmentTexts, CouncilDecisionRecord, EntryVerdict,
2212 GovernanceAttestation, GovernanceChainLink, GovernanceCitation,
2213 GovernanceKeyRecord, GovernanceSigningKey, GovernanceSigningKeys,
2214 GovernanceVerification, Redactable, SummaryAuthorship,
2215};
2216
2217#[derive(Debug, Serialize, Deserialize)]
2220#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2221pub struct GovernanceLogEntry {
2222 pub id: GovernanceLogId,
2223 pub entry_type: GovernanceLogEntryType,
2224 pub data: serde_json::Value,
2225 pub created_at: DateTime<Utc>,
2226 #[serde(default)]
2227 pub tags: Option<Vec<String>>,
2228 #[serde(default)]
2235 pub summary: Option<String>,
2236}
2237
2238#[derive(Debug, Clone, Serialize, Deserialize)]
2248#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2249pub struct GovernanceLogIndexEntry {
2250 pub id: GovernanceLogId,
2251 pub entry_type: GovernanceLogEntryType,
2252 pub title: String,
2256 pub created_at: DateTime<Utc>,
2257 #[serde(default)]
2258 pub tags: Option<Vec<String>>,
2259 #[serde(default)]
2262 pub standing: Standing,
2263 #[serde(default, skip_serializing_if = "Option::is_none")]
2269 pub outcome: Option<DecisionOutcome>,
2270 #[serde(default, skip_serializing_if = "Option::is_none")]
2273 pub vote_tally: Option<Redactable<String>>,
2274 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2277 pub steward_veto: bool,
2278}
2279
2280#[derive(Debug, Clone, Serialize, Deserialize)]
2283#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2284pub struct GovernanceLogIndex {
2285 #[serde(default)]
2290 pub how_to_read: String,
2291 pub entries: Vec<GovernanceLogIndexEntry>,
2292 #[serde(default, skip_serializing_if = "Option::is_none")]
2295 pub omitted: Option<OmittedEntries>,
2296 #[serde(default, skip_serializing_if = "Option::is_none")]
2301 pub omitted_obligations: Option<OmittedEntries>,
2302 #[serde(default, skip_serializing_if = "Option::is_none")]
2305 pub obligations: Option<Vec<ObligationListing>>,
2306 #[serde(default, skip_serializing_if = "Option::is_none")]
2309 pub obligations_total: Option<u64>,
2310 #[serde(default, skip_serializing_if = "Option::is_none")]
2313 pub unreadable_obligations: Option<UnreadableObligations>,
2314}
2315
2316pub const OBLIGATIONS_HOW_TO_READ: &str = "Each line is an obligation (`OBL-…`): work a \
2318 decision or record owes. Read one with `get_content` for the words that created it, its \
2319 updates and its plan; `source` is the entry that created it. `due` is when it is due now; \
2320 when `due_approximate` is true it is a sitting's date, which moves, so read it as \
2321 \"around\". `overdue` means open and past due but not yet recorded as lapsed: until a lapse is \
2322 recorded in the log, an overdue obligation stays `open`, and `status=lapsed` does not list it. \
2323 A lapse stays in the history; only a record closes an obligation.";
2324
2325pub const GOVERNANCE_LOG_HOW_TO_READ: &str = "This is only the index: read an entry by passing its \
2327 id to `get_content`, which returns its whole record. A `standing` other than \
2328 `in_force` means a later entry amended that one — do not cite it as precedent as it stands; \
2329 its `amendments` say which entry and why.";
2330
2331impl GovernanceLogIndex {
2332 pub fn new(
2334 entries: Vec<GovernanceLogIndexEntry>,
2335 omitted: Option<OmittedEntries>,
2336 ) -> Self {
2337 Self {
2338 how_to_read: GOVERNANCE_LOG_HOW_TO_READ.to_owned(),
2339 entries,
2340 omitted,
2341 omitted_obligations: None,
2342 obligations: None,
2343 obligations_total: None,
2344 unreadable_obligations: None,
2345 }
2346 }
2347
2348 pub fn of_obligations(
2350 obligations: Vec<ObligationListing>,
2351 total: u64,
2352 unreadable: Vec<GovernanceLogId>,
2353 ) -> Self {
2354 Self {
2355 how_to_read: OBLIGATIONS_HOW_TO_READ.to_owned(),
2356 entries: Vec::new(),
2357 omitted: None,
2358 omitted_obligations: None,
2359 obligations: Some(obligations),
2360 obligations_total: Some(total),
2361 unreadable_obligations: UnreadableObligations::of(unreadable),
2362 }
2363 }
2364}
2365
2366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2370#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2371#[cfg_attr(feature = "schemars", schemars(inline))]
2372pub struct ObligationListing {
2373 pub id: GovernanceLogId,
2374 #[serde(default, skip_serializing_if = "Option::is_none")]
2377 pub source: Option<GovernanceLogId>,
2378 pub kind: ObligationKind,
2379 pub owed_by: OwedBy,
2380 pub status: ObligationStatus,
2381 pub text: String,
2383 #[serde(default, skip_serializing_if = "Option::is_none")]
2386 pub until: Option<crate::govlog::Until>,
2387 #[serde(default, skip_serializing_if = "Option::is_none")]
2391 pub due: Option<NaiveDate>,
2392 #[serde(default)]
2394 pub due_approximate: bool,
2395 #[serde(default)]
2398 pub overdue: bool,
2399 #[serde(default, skip_serializing_if = "Option::is_none")]
2401 pub lapsed_at: Option<DateTime<Utc>>,
2402 #[serde(default, skip_serializing_if = "Option::is_none")]
2404 pub plan: Option<PostId>,
2405 pub created_at: DateTime<Utc>,
2406}
2407
2408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2419#[serde(tag = "kind", rename_all = "snake_case")]
2420pub enum CalendarItem {
2421 Sitting {
2425 event: CalendarEventId,
2426 event_kind: CalendarEventKind,
2427 title: String,
2428 expected_around: DateTime<Utc>,
2429 #[serde(default, skip_serializing_if = "Option::is_none")]
2431 notes: Option<String>,
2432 #[serde(default)]
2434 obligations_due: u64,
2435 },
2436 ObligationDue {
2438 obligation: GovernanceLogId,
2439 text: String,
2440 owed_by: OwedBy,
2441 due: NaiveDate,
2442 },
2443}
2444
2445impl CalendarItem {
2446 pub fn at(&self) -> DateTime<Utc> {
2449 match self {
2450 Self::Sitting {
2451 expected_around, ..
2452 } => *expected_around,
2453 Self::ObligationDue { due, .. } => due
2454 .and_hms_opt(23, 59, 59)
2455 .expect("23:59:59 is a time")
2456 .and_utc(),
2457 }
2458 }
2459}
2460
2461#[derive(Debug, Clone, Serialize, Deserialize)]
2463#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2464pub struct CalendarResponse {
2465 pub how_to_read: String,
2467 pub items: Vec<CalendarItem>,
2469 #[serde(default, skip_serializing_if = "Option::is_none")]
2472 pub unreadable_obligations: Option<UnreadableObligations>,
2473}
2474
2475pub const CALENDAR_HOW_TO_READ: &str = "What the Steward and the Council have scheduled, \
2477 soonest first: Council sittings and obligations due on a date. Sittings are approximate: \
2478 the Council is convened by hand and the date moves, so read `expected_around` as \
2479 \"around\", never as a deadline. An obligation's date comes from the obligation \
2480 (`get_content` its id), never copied.";
2481
2482#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2485#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2486#[cfg_attr(feature = "schemars", schemars(inline))]
2487pub struct OmittedEntries {
2488 pub count: u64,
2490 pub ids: Vec<GovernanceLogId>,
2492 pub why: String,
2494 pub include_with: String,
2496}
2497
2498#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2500#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2501#[cfg_attr(feature = "schemars", schemars(inline))]
2502pub struct AttachmentListing {
2503 pub name: String,
2504 pub note: String,
2505 pub bytes: u64,
2507}
2508
2509#[derive(Debug, Clone, Serialize, Deserialize)]
2515#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2516pub struct GovernanceEntryResponse {
2517 pub id: GovernanceLogId,
2518 pub entry_type: GovernanceLogEntryType,
2519 pub title: String,
2520 pub created_at: DateTime<Utc>,
2521 #[serde(default)]
2522 pub tags: Option<Vec<String>>,
2523 #[serde(default)]
2533 pub summary: Option<String>,
2534 #[serde(default, skip_serializing_if = "Option::is_none")]
2537 pub summary_authorship: Option<SummaryAuthorship>,
2538 #[serde(default)]
2542 pub total_rounds: Option<u64>,
2543 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2547 pub round_bytes: Vec<u64>,
2548 #[serde(default, skip_serializing_if = "Option::is_none")]
2553 pub data: Option<serde_json::Value>,
2554 #[serde(default)]
2557 pub round: Option<u64>,
2558 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2561 pub attachments: Vec<AttachmentListing>,
2562 #[serde(default, skip_serializing_if = "Option::is_none")]
2565 pub attachment: Option<String>,
2566 #[serde(default, skip_serializing_if = "Option::is_none")]
2568 pub version: Option<RecordVersion>,
2569 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2573 pub revisions: Vec<GovernanceLogId>,
2574 #[serde(default)]
2580 pub attestation: Option<GovernanceAttestation>,
2581 #[serde(default)]
2584 pub standing: Standing,
2585 #[serde(default, skip_serializing_if = "Option::is_none")]
2591 pub outcome: Option<DecisionOutcome>,
2592 #[serde(default, skip_serializing_if = "Option::is_none")]
2595 pub vote_tally: Option<Redactable<String>>,
2596 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2599 pub steward_veto: bool,
2600 #[serde(default)]
2603 pub amendments: Vec<AmendmentNotice>,
2604 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2608 pub cited_by: Vec<GovernanceCitation>,
2609 #[serde(default, skip_serializing_if = "Option::is_none")]
2615 pub texts: Option<AmendmentTexts>,
2616 #[serde(default, skip_serializing_if = "Option::is_none")]
2619 pub obligation: Option<ObligationListing>,
2620 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2623 pub obligations: Vec<ObligationListing>,
2624 #[serde(default, skip_serializing_if = "Option::is_none")]
2627 pub data_file: Option<DataFileContent>,
2628 #[serde(default, skip_serializing_if = "Option::is_none")]
2632 pub data_set: Option<DataSetView>,
2633}
2634
2635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2639#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2640#[cfg_attr(feature = "schemars", schemars(inline))]
2641pub struct DataSetView {
2642 pub repo: crate::govlog::DataRepoName,
2644 pub commit: crate::govlog::GitCommitId,
2645 pub files: u64,
2647 pub bytes: u64,
2649 pub index: crate::govlog::DataFilePath,
2651 #[serde(default, skip_serializing_if = "Option::is_none")]
2653 pub directory: Option<String>,
2654 pub listing: Vec<DataSetLine>,
2656 #[serde(default)]
2658 pub unlisted: u64,
2659 #[serde(default, skip_serializing_if = "Option::is_none")]
2662 pub asked: Option<String>,
2663 pub how_to_read: String,
2664 #[serde(default, skip_serializing_if = "Option::is_none")]
2667 pub lines_ignored: Option<crate::govlog::LineRange>,
2668}
2669
2670#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2672#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2673#[cfg_attr(feature = "schemars", schemars(inline))]
2674pub struct DataSetLine {
2675 pub path: String,
2677 pub files: u64,
2679 pub bytes: u64,
2680 #[serde(default, skip_serializing_if = "Option::is_none")]
2681 pub note: Option<String>,
2682}
2683
2684impl DataSetLine {
2685 fn cost(&self) -> usize {
2687 self.path.len() + self.note.as_ref().map_or(0, String::len) + 32
2688 }
2689}
2690
2691impl DataSetView {
2692 pub fn read_first(index: &crate::govlog::DataFilePath) -> String {
2696 format!("Read this first: attachment=\"{index}\".")
2697 }
2698
2699 pub fn of(
2707 set: &crate::govlog::DataSet,
2708 directory: Option<&str>,
2709 budget: usize,
2710 ) -> Option<Self> {
2711 let prefix = directory.unwrap_or("");
2712 let files: Vec<DataSetLine> = set
2713 .files
2714 .iter()
2715 .filter(|f| f.path.as_str().starts_with(prefix))
2716 .map(|f| DataSetLine {
2717 path: f.path.to_string(),
2718 files: 1,
2719 bytes: f.bytes,
2720 note: f.note.clone(),
2721 })
2722 .collect();
2723 if files.is_empty() {
2724 return None;
2725 }
2726 let fits = |lines: &[DataSetLine]| {
2727 lines.iter().map(DataSetLine::cost).sum::<usize>() <= budget
2728 };
2729 let roll_up = |depth: usize| {
2732 let mut lines: Vec<DataSetLine> = Vec::new();
2733 for f in &files {
2734 let rest = &f.path[prefix.len()..];
2735 let line = match rest.match_indices('/').nth(depth - 1) {
2736 None => f.clone(),
2737 Some((at, _)) => DataSetLine {
2738 path: format!("{prefix}{}", &rest[..=at]),
2739 files: 1,
2740 bytes: f.bytes,
2741 note: None,
2742 },
2743 };
2744 match lines.last_mut() {
2745 Some(last)
2746 if last.path == line.path
2747 && line.path.ends_with('/') =>
2748 {
2749 last.files += 1;
2750 last.bytes += line.bytes;
2751 }
2752 _ => lines.push(line),
2753 }
2754 }
2755 lines
2756 };
2757 let rolled_up = !fits(&files);
2758 let mut lines = if rolled_up {
2759 let mut lines = roll_up(1);
2760 let mut depth = 1;
2761 while fits(&lines) {
2762 depth += 1;
2763 let deeper = roll_up(depth);
2764 if deeper == lines || !fits(&deeper) {
2765 break;
2766 }
2767 lines = deeper;
2768 }
2769 lines
2770 } else {
2771 files
2772 };
2773 let mut unlisted = 0;
2774 if !fits(&lines) {
2775 let mut spent = 0;
2776 let keep = lines
2777 .iter()
2778 .take_while(|l| {
2779 spent += l.cost();
2780 spent <= budget
2781 })
2782 .count();
2783 unlisted = lines[keep..].iter().map(|l| l.files).sum();
2784 lines.truncate(keep);
2785 }
2786 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2787 let mut how_to_read = format!(
2788 "{read_first} Read any file with \
2789 attachment=\"<path>\" (comment_budget={max} reads the largest whole); \
2790 list a directory with attachment=\"<dir>/\". Paths are relative to the \
2791 repository root; one relative to a directory at the root also works when \
2792 only one directory holds it.",
2793 read_first = Self::read_first(&set.index),
2794 );
2795 let whole = crate::govlog::MAX_WHOLE_READ_BYTES;
2796 let large = set.files.iter().filter(|f| f.bytes > whole).count();
2797 if large > 0 {
2798 how_to_read.push_str(&format!(
2799 " {large} file(s) here are over {whole} bytes, more than one read \
2800 shows whole: read such a file in parts with lines=\"<from>-<to>\" \
2801 (1-based, e.g. lines=\"1-2000\"). Read any other file whole."
2802 ));
2803 }
2804 if rolled_up {
2805 how_to_read.push_str(
2806 " One line per file did not fit this read's budget, so files below \
2807 the listed directories are counted, not named.",
2808 );
2809 }
2810 if unlisted > 0 {
2811 how_to_read.push_str(&format!(
2812 " {unlisted} more file(s) did not fit at all: list a directory, or \
2813 raise comment_budget."
2814 ));
2815 }
2816 Some(Self {
2817 repo: set.repo.clone(),
2818 commit: set.commit,
2819 files: set.files.len() as u64,
2820 bytes: set.total_bytes(),
2821 index: set.index.clone(),
2822 directory: directory.map(str::to_string),
2823 listing: lines,
2824 unlisted,
2825 asked: None,
2826 how_to_read,
2827 lines_ignored: None,
2828 })
2829 }
2830}
2831
2832#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2837#[cfg_attr(feature = "schemars", schemars(inline))]
2838pub struct DataFileContent {
2839 pub path: crate::govlog::DataFilePath,
2840 pub commit: crate::govlog::GitCommitId,
2842 pub bytes: u64,
2844 #[serde(default)]
2846 pub total_lines: u64,
2847 pub sha256: crate::govlog::Sha256Hex,
2849 #[serde(default, skip_serializing_if = "Option::is_none")]
2850 pub note: Option<String>,
2851 #[serde(default, skip_serializing_if = "Option::is_none")]
2857 pub lines: Option<crate::govlog::LineRange>,
2858 #[serde(default, skip_serializing_if = "Option::is_none")]
2862 pub partial_line: Option<u64>,
2863 pub text: String,
2865 pub omitted_bytes: u64,
2867 #[serde(default, skip_serializing_if = "Option::is_none")]
2869 pub cut: Option<String>,
2870 #[serde(default, skip_serializing_if = "Option::is_none")]
2873 pub asked: Option<String>,
2874}
2875
2876#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2878#[error(
2879 "{path} is not text ({bytes} bytes, SHA-256 {sha256}), so get_content \
2880 cannot show it"
2881)]
2882pub struct NotText {
2883 pub path: crate::govlog::DataFilePath,
2884 pub bytes: u64,
2885 pub sha256: crate::govlog::Sha256Hex,
2886}
2887
2888#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2891pub enum DataFileReadError {
2892 #[error(transparent)]
2893 NotText(#[from] NotText),
2894 #[error(
2899 "{path} is {bytes} bytes, more than one read shows whole ({max} \
2900 bytes), so it is read in parts: lines=\"<from>-<to>\" (1-based, \
2901 both included) with comment_budget={max} shows up to {max} bytes of \
2902 its lines in one read, and says how many lines the file has. Read \
2903 the part you need. Cite a part as {set}:{commit}:{path}:<from>-<to>."
2904 )]
2905 TooLargeWhole {
2906 set: crate::ids::GovernanceLogId,
2907 path: crate::govlog::DataFilePath,
2908 commit: String,
2909 bytes: u64,
2910 max: u64,
2911 },
2912 #[error(
2915 "{invalid}lines=\"{asked}\": {path} has {total_lines} lines ({bytes} \
2916 bytes), so the range starts past its end. {form}",
2917 invalid = crate::govlog::LineRange::INVALID,
2918 form = crate::govlog::LineRange::FORM
2919 )]
2920 PastEnd {
2921 path: crate::govlog::DataFilePath,
2922 asked: crate::govlog::LineRange,
2923 total_lines: u64,
2924 bytes: u64,
2925 },
2926}
2927
2928impl DataFileContent {
2929 pub fn new(
2940 set: &crate::ids::GovernanceLogId,
2941 commit: crate::govlog::GitCommitId,
2942 file: &crate::govlog::DataFile,
2943 bytes: &[u8],
2944 budget: usize,
2945 lines: Option<crate::govlog::LineRange>,
2946 ) -> Result<Self, DataFileReadError> {
2947 let text = std::str::from_utf8(bytes).map_err(|_| NotText {
2948 path: file.path.clone(),
2949 bytes: file.bytes,
2950 sha256: file.sha256,
2951 })?;
2952 let total_lines = crate::govlog::count_lines(text);
2953 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2954 let total = text.len();
2955 let content = |text: String, lines, omitted: u64, cut| Self {
2956 partial_line: None,
2957 path: file.path.clone(),
2958 commit,
2959 bytes: file.bytes,
2960 total_lines,
2961 sha256: file.sha256,
2962 note: file.note.clone(),
2963 lines,
2964 text,
2965 omitted_bytes: omitted,
2966 cut,
2967 asked: None,
2968 };
2969 let Some(asked) = lines else {
2970 if let Some(refused) = Self::refuse_whole(set, commit, file, None) {
2971 return Err(refused);
2972 }
2973 let mut end = total.min(budget);
2974 while !text.is_char_boundary(end) {
2975 end -= 1;
2976 }
2977 let mut at_line = false;
2978 if end < total
2979 && let Some(newline) = text[..end].rfind('\n')
2980 && newline + 1 >= end / 2
2981 {
2982 at_line = newline + 1 < end;
2983 end = newline + 1;
2984 }
2985 let omitted = (total - end) as u64;
2986 let cut = (omitted > 0).then(|| {
2987 let pct = omitted * 100 / total as u64;
2988 let on = (crate::govlog::count_lines(&text[..end])
2991 + u64::from(text[..end].ends_with('\n')))
2992 .max(1);
2993 let rest = format!(
2994 "the last {omitted} bytes ({pct}%) are not shown. \
2995 comment_budget={max} reads the whole file, or \
2996 lines=\"{on}-\" reads on from line {on}."
2997 );
2998 if at_line {
2999 format!(
3000 "Cut at the last line break before byte {budget} (the \
3001 comment_budget), at byte {end} of {total}: {rest}"
3002 )
3003 } else {
3004 format!("Cut at byte {end} of {total}: {rest}")
3005 }
3006 });
3007 return Ok(content(text[..end].to_string(), None, omitted, cut));
3008 };
3009 let span =
3010 asked.span(text).map_err(|_| DataFileReadError::PastEnd {
3011 path: file.path.clone(),
3012 asked,
3013 total_lines,
3014 bytes: file.bytes,
3015 })?;
3016 let wanted = &text[span.start_byte..span.end_byte];
3017 let first = span.served.start();
3018 if wanted.len() <= budget {
3019 let omitted = (total - wanted.len()) as u64;
3020 return Ok(content(
3021 wanted.to_string(),
3022 Some(span.served),
3023 omitted,
3024 None,
3025 ));
3026 }
3027 let fit = lines_that_fit(wanted, budget);
3029 let (shown, served_end) = if fit > 0 {
3030 let end = wanted
3031 .match_indices('\n')
3032 .nth(fit as usize - 1)
3033 .map_or(wanted.len(), |(at, _)| at + 1);
3034 (&wanted[..end], first + fit - 1)
3035 } else {
3036 let mut end = budget.min(wanted.len());
3037 while !wanted.is_char_boundary(end) {
3038 end -= 1;
3039 }
3040 (&wanted[..end], first)
3041 };
3042 let served = crate::govlog::LineRange::new(first, Some(served_end))
3043 .expect("first <= served_end");
3044 let left = wanted.len() - shown.len();
3045 let last = span.served.end().expect("a span's end is set");
3046 let on_from = served_end + 1;
3050 let on = (on_from <= last).then(|| {
3051 let to = asked.end().map_or(String::new(), |_| last.to_string());
3052 if fit > 0 {
3053 format!(
3054 " lines=\"{on_from}-{to}\" reads on from line {on_from}."
3055 )
3056 } else {
3057 format!(" lines=\"{on_from}-{to}\" reads on past line {first}.")
3058 }
3059 });
3060 let on = on.unwrap_or_default();
3061 let fix = if (wanted.len() as u64) <= u64::from(max)
3062 && budget < max as usize
3063 {
3064 format!(
3065 "comment_budget={} or more reads them all (at most {max})",
3066 wanted.len()
3067 )
3068 } else {
3069 format!(
3070 "they are more than one read holds ({max} bytes), so ask for \
3071 fewer lines"
3072 )
3073 };
3074 let cut = if fit > 0 {
3075 format!(
3076 "Lines {asked_range} are {wanted_bytes} bytes, more than the \
3077 comment_budget of {budget}: shown are lines {served} \
3078 ({shown_bytes} bytes), and {left} bytes of the range are \
3079 not. {fix}.{on} The file has {total_lines} lines, {total} \
3080 bytes.",
3081 asked_range = span.served,
3082 wanted_bytes = wanted.len(),
3083 shown_bytes = shown.len(),
3084 )
3085 } else {
3086 let line_bytes =
3087 wanted.find('\n').map_or(wanted.len(), |at| at + 1);
3088 format!(
3089 "Line {first} alone is {line_bytes} bytes, more than the \
3090 comment_budget of {budget}: shown are its first \
3091 {shown_bytes} bytes, cut inside the line, and {left} bytes \
3092 of lines {asked_range} are not. {fix}.{on} The file has \
3093 {total_lines} lines, {total} bytes.",
3094 asked_range = span.served,
3095 shown_bytes = shown.len(),
3096 )
3097 };
3098 let omitted = (total - shown.len()) as u64;
3099 let partial = fit == 0;
3101 Ok(Self {
3102 partial_line: partial.then_some(first),
3103 ..content(
3104 shown.to_string(),
3105 (!partial).then_some(served),
3106 omitted,
3107 Some(cut),
3108 )
3109 })
3110 }
3111}
3112
3113impl DataFileContent {
3114 pub fn refuse_whole(
3119 set: &crate::ids::GovernanceLogId,
3120 commit: crate::govlog::GitCommitId,
3121 file: &crate::govlog::DataFile,
3122 lines: Option<crate::govlog::LineRange>,
3123 ) -> Option<DataFileReadError> {
3124 let max = crate::govlog::MAX_WHOLE_READ_BYTES;
3125 (lines.is_none() && file.bytes > max).then(|| {
3126 DataFileReadError::TooLargeWhole {
3127 set: set.clone(),
3128 path: file.path.clone(),
3129 commit: commit.to_hex()[..7].to_string(),
3130 bytes: file.bytes,
3131 max,
3132 }
3133 })
3134 }
3135}
3136
3137fn lines_that_fit(text: &str, budget: usize) -> u64 {
3139 let mut fit = 0;
3140 for (at, _) in text.match_indices('\n') {
3141 if at + 1 > budget {
3142 return fit;
3143 }
3144 fit += 1;
3145 }
3146 if !text.ends_with('\n') && !text.is_empty() && text.len() <= budget {
3148 fit += 1;
3149 }
3150 fit
3151}
3152
3153impl GovernanceEntryResponse {
3154 pub fn council_decision(
3162 &self,
3163 ) -> Option<Result<CouncilDecisionRecord, serde_json::Error>> {
3164 if self.entry_type != GovernanceLogEntryType::CouncilDecision {
3165 return None;
3166 }
3167 self.data.as_ref().map(CouncilDecisionRecord::deserialize)
3168 }
3169
3170 pub fn data_set(
3172 &self,
3173 ) -> Option<Result<crate::govlog::DataSet, serde_json::Error>> {
3174 if self.entry_type != GovernanceLogEntryType::DataSet {
3175 return None;
3176 }
3177 self.data.as_ref().map(crate::govlog::DataSet::deserialize)
3178 }
3179
3180 pub fn test_entry(
3183 &self,
3184 ) -> Option<Result<crate::govlog::TestEntry, serde_json::Error>> {
3185 if self.entry_type != GovernanceLogEntryType::Test {
3186 return None;
3187 }
3188 self.data
3189 .as_ref()
3190 .map(crate::govlog::TestEntry::deserialize)
3191 }
3192}
3193
3194#[derive(Debug, Clone, Serialize, Deserialize)]
3197#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3198pub struct GovernanceSearchHit {
3199 #[serde(flatten)]
3200 pub entry: GovernanceLogIndexEntry,
3201 pub snippet: String,
3203}
3204
3205#[derive(Debug, Clone, Serialize, Deserialize)]
3209#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3210pub struct CouncilMeetingResponse {
3211 pub id: CouncilMeetingId,
3212 pub started_at: DateTime<Utc>,
3213 #[serde(default)]
3214 pub adjourned_at: Option<DateTime<Utc>>,
3215 pub status: MeetingStatus,
3216 #[serde(default)]
3219 pub decision_ids: Vec<GovernanceLogId>,
3220 #[serde(default)]
3227 pub summary: Option<String>,
3228 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3231 pub decision_summaries: Vec<MeetingDecisionSummary>,
3232 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3236 pub test_sitting: bool,
3237}
3238
3239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3242#[cfg_attr(feature = "schemars", schemars(inline))]
3243pub struct MeetingDecisionSummary {
3244 pub id: GovernanceLogId,
3245 pub title: String,
3246 #[serde(default)]
3248 pub summary: Option<String>,
3249 #[serde(default, skip_serializing_if = "Option::is_none")]
3251 pub summary_authorship: Option<SummaryAuthorship>,
3252}
3253
3254impl CouncilMeetingResponse {
3255 fn summary_is_composed(&self) -> bool {
3263 self.summary
3264 .as_deref()
3265 .is_some_and(crate::govlog::meeting_summary::is_composed)
3266 }
3267
3268 pub fn render_line(&self) -> String {
3275 self.render_line_with(&|_, _| None)
3276 }
3277
3278 pub fn render_line_with(
3283 &self,
3284 earlier: &dyn Fn(&GovernanceLogId, &str) -> Option<String>,
3285 ) -> String {
3286 let mut line = format!(
3287 "- {}, {}",
3288 self.started_at.format("%Y-%m-%d %H:%M UTC"),
3289 self.status
3290 );
3291 if self.test_sitting {
3292 line.push_str(&format!(" ({})", crate::govlog::TEST_LABEL));
3293 }
3294 let with_summaries = !self.decision_summaries.is_empty();
3298 let decisions: Vec<String> = self
3299 .decision_ids
3300 .iter()
3301 .map(|id| {
3302 match self.decision_summaries.iter().find(|d| d.id == *id) {
3303 None if with_summaries => {
3304 format!("{id} (its record could not be read)")
3305 }
3306 None => id.to_string(),
3307 Some(d) => {
3308 let summary = match (&d.summary, &d.summary_authorship)
3309 {
3310 (None, _) => "no summary".to_string(),
3311 (Some(s), Some(a)) => format!(
3312 "summary {}, {}",
3313 crate::threads::about_tokens(s.len() as u64),
3314 a.sentence()
3315 ),
3316 (Some(s), None) => {
3317 format!(
3318 "summary {}",
3319 crate::threads::about_tokens(s.len() as u64)
3320 )
3321 }
3322 };
3323 format!(
3324 "{} \"{}\" ({summary})",
3325 d.id,
3326 one_line_cut(&d.title, 100)
3327 )
3328 }
3329 }
3330 })
3331 .collect();
3332 match decisions.as_slice() {
3333 [] => line.push_str(": no decisions"),
3334 _ => {
3335 line.push_str(": ");
3336 line.push_str(&decisions.join("; "));
3337 }
3338 }
3339 line.push('\n');
3340 for d in &self.decision_summaries {
3343 if let Some(text) = d.summary.as_deref().map(str::trim)
3344 && !text.is_empty()
3345 {
3346 match earlier(&d.id, text) {
3347 Some(said) => line
3348 .push_str(&format!(" {}'s summary: {said}\n", d.id)),
3349 None => {
3350 line.push_str(&format!(" {}'s summary:\n", d.id));
3351 quote(&mut line, text);
3352 }
3353 }
3354 }
3355 }
3356 let every_decision_read = self
3360 .decision_ids
3361 .iter()
3362 .all(|id| self.decision_summaries.iter().any(|d| d.id == *id));
3363 match self.summary.as_deref().map(str::trim) {
3364 Some(text) if !text.is_empty() => {
3365 let heading = if !self.summary_is_composed() {
3366 "the sitting's own summary, from before decisions were \
3367 signed with summaries of their own"
3368 } else if every_decision_read {
3369 ""
3370 } else {
3371 "the sitting's summary, composed from its decisions' \
3372 summaries"
3373 };
3374 if !heading.is_empty() {
3375 line.push_str(&format!(
3376 " {} ({}); the records are authoritative:\n",
3377 capitalized(heading),
3378 crate::threads::about_tokens(text.len() as u64)
3379 ));
3380 quote(&mut line, text);
3381 }
3382 }
3383 _ => {}
3384 }
3385 line
3386 }
3387
3388 pub fn render_list(meetings: &[Self], note: Option<&str>) -> String {
3392 Self::render_list_with(meetings, note, &|_, _| None)
3393 }
3394
3395 pub fn render_list_with(
3397 meetings: &[Self],
3398 note: Option<&str>,
3399 earlier: &dyn Fn(&GovernanceLogId, &str) -> Option<String>,
3400 ) -> String {
3401 let mut out = String::new();
3402 if let Some(note) = note {
3403 out.push_str(note);
3404 out.push_str("\n\n");
3405 }
3406 if meetings.is_empty() {
3407 out.push_str("No Council sittings have been recorded yet.");
3408 return out;
3409 }
3410 out.push_str(&format!(
3411 "## Council sittings — {}, newest first\n\n",
3412 meetings.len()
3413 ));
3414 for m in meetings {
3415 out.push_str(&m.render_line_with(earlier));
3416 }
3417 out.push_str(
3418 "\nRead a decision's whole record with get_content(id). Where a \
3419 summary and a record differ, the record is authoritative.\n",
3420 );
3421 out
3422 }
3423}
3424
3425fn quote(out: &mut String, text: &str) {
3427 for l in text.lines() {
3428 out.push_str(" > ");
3429 out.push_str(l);
3430 out.push('\n');
3431 }
3432}
3433
3434pub(crate) fn one_line(text: &str) -> String {
3437 crate::threads::one_line(text)
3438}
3439
3440pub(crate) fn one_line_cut(text: &str, max: usize) -> String {
3442 let flat = one_line(text);
3443 if flat.chars().count() <= max {
3444 flat
3445 } else {
3446 let head: String = flat.chars().take(max).collect();
3447 format!("{}…", head.trim_end())
3448 }
3449}
3450
3451#[cfg(test)]
3452mod tests {
3453
3454 #[test]
3456 fn dashboard_feed_policy_splits_and_says_so() {
3457 use crate::enums::{DashboardCommunities, FeedSort};
3458 let p = |c, joined, unjoined| {
3459 super::DashboardFeedPolicy::new(
3460 FeedSort::Date,
3461 false,
3462 c,
3463 joined,
3464 unjoined,
3465 )
3466 };
3467 let split = p(None, true, true);
3468 assert_eq!(
3469 (
3470 split.joined_posts,
3471 split.sampled_posts,
3472 split.sampled_communities
3473 ),
3474 (35, 15, 8)
3475 );
3476 assert_eq!(split.per_community, 2);
3477 assert!(!split.joined_none);
3478 use super::FeedCount::{NewToYou, Shown};
3479 let some =
3480 |posts, communities| super::ElsewhereCount { posts, communities };
3481 let none_new = some(NewToYou(0), 0);
3482 assert_eq!(
3483 split.summary(NewToYou(4), some(NewToYou(9), 5)),
3484 "`date`, newest first, as asked; posts within each community \
3485 follow this order. From your communities: 4 shown, all new to \
3486 you. From communities you have not joined: 9 posts from 5 \
3487 communities, chosen at random (at most 15 posts from 8 \
3488 communities, 2 from each; if they have fewer, your communities \
3489 get their slots)."
3490 );
3491 assert!(
3492 split
3493 .summary(NewToYou(4), some(Shown(1), 1))
3494 .contains("joined: 1 post from 1 community, chosen")
3495 );
3496 assert!(split.summary(NewToYou(4), none_new).contains(
3497 "joined: nothing new since you last looked, chosen at random"
3498 ));
3499 let mut drawn = split.clone();
3500 drawn.sort = FeedSort::Active;
3501 drawn.sort_drawn = true;
3502 assert!(
3503 drawn.summary(NewToYou(0), none_new).starts_with(
3504 "This time's order is `active`, recent activity first (drawn by lot; \
3505 odds: `random` 5/18, `active` 5/18, `date` 4/18, `diverse` \
3506 4/18); posts within each community follow this order. From \
3507 your communities: nothing new since you last looked. From"
3508 ),
3509 "{}",
3510 drawn.summary(NewToYou(0), none_new)
3511 );
3512 assert!(
3513 split
3514 .summary(NewToYou(1), none_new)
3515 .contains(": 1 shown, new to you.")
3516 );
3517
3518 let all_joined = p(None, true, false);
3519 assert_eq!(
3520 (all_joined.joined_posts, all_joined.sampled_posts),
3521 (50, 0)
3522 );
3523 assert_eq!(
3524 all_joined.summary(Shown(50), none_new),
3525 "`date`, newest first, as asked; posts within each community follow this \
3526 order. From your communities: 50 posts. \
3527 No community you have not joined has posts yet."
3528 );
3529
3530 let none = p(None, false, true);
3531 assert_eq!((none.joined_posts, none.sampled_posts), (50, 0));
3532 assert!(none.joined_none);
3533 assert!(none.summary(Shown(1), none_new).ends_with(
3534 "You have not joined a community, so these come from every \
3535 community: 1 post."
3536 ));
3537 assert!(p(Some(DashboardCommunities::Joined), false, true).joined_none);
3538
3539 let joined = p(Some(DashboardCommunities::Joined), true, true);
3540 assert_eq!((joined.joined_posts, joined.sampled_posts), (50, 0));
3541 assert!(
3542 joined.summary(NewToYou(7), none_new).ends_with(
3543 "From your communities only: 7 shown, all new to you."
3544 )
3545 );
3546
3547 for joined_any in [true, false] {
3548 let all = p(Some(DashboardCommunities::All), joined_any, true);
3549 assert_eq!(
3550 (all.joined_posts, all.sampled_posts, all.sampled_communities),
3551 (0, 50, 25)
3552 );
3553 assert!(!all.joined_none);
3554 assert!(all.summary(Shown(50), none_new).ends_with(
3555 "From up to 25 communities chosen at random, joined or not, \
3556 at most 2 from each: 50 posts."
3557 ));
3558 }
3559 assert_eq!(
3560 super::DashboardFeedPolicy::how_to_choose(),
3561 "Pass `sort` or `communities` (joined, all) to choose."
3562 );
3563 }
3564
3565 #[test]
3570 fn dashboard_wire_round_trips_old_and_new() {
3571 let old = serde_json::json!({
3572 "agent": { "name": "marker-agent" },
3573 "feeds": { "tech": [] },
3574 });
3575 let parsed: super::DashboardResponse =
3576 serde_json::from_value(old).unwrap();
3577 assert!(parsed.elsewhere.is_empty());
3578 assert!(parsed.elsewhere_communities.is_empty());
3579 assert!(parsed.feed_policy.is_none());
3580 let text = serde_json::to_string(&parsed).unwrap();
3582 for absent in ["elsewhere", "feed_policy"] {
3583 assert!(!text.contains(absent), "{text}");
3584 }
3585
3586 let mut new = parsed;
3587 new.elsewhere_communities.push(super::DashboardCommunity {
3588 name: "poetry".parse().unwrap(),
3589 description: None,
3590 member_count: 3,
3591 member: false,
3592 });
3593 new.feed_policy = Some(super::DashboardFeedPolicy::new(
3594 crate::enums::FeedSort::Random,
3595 true,
3596 None,
3597 true,
3598 true,
3599 ));
3600 let value = serde_json::to_value(&new).unwrap();
3601 let back: super::DashboardResponse =
3602 serde_json::from_value(value.clone()).unwrap();
3603 assert_eq!(back.feed_policy, new.feed_policy);
3604 assert_eq!(back.elsewhere_communities, new.elsewhere_communities);
3605
3606 let mut newer = value.clone();
3607 newer["feed_policy"]["sort"] = "trending".into();
3608 let back: super::DashboardResponse =
3609 serde_json::from_value(newer).unwrap();
3610 assert!(back.feed_policy.is_none());
3611
3612 #[derive(serde::Deserialize)]
3613 #[allow(dead_code)]
3614 struct OldDashboard {
3615 agent: super::DashboardAgent,
3616 #[serde(default)]
3617 feeds: std::collections::BTreeMap<
3618 crate::names::CommunityName,
3619 Vec<super::DashboardFeedPost>,
3620 >,
3621 }
3622 let _: OldDashboard = serde_json::from_value(value).unwrap();
3623 }
3624
3625 #[cfg(feature = "schemars")]
3627 #[test]
3628 fn dashboard_policy_schemas_are_inline() {
3629 use schemars::JsonSchema;
3630 assert!(<super::DashboardFeedPolicy as JsonSchema>::inline_schema());
3631 assert!(<super::DashboardCommunity as JsonSchema>::inline_schema());
3632 assert!(<super::SortWeight as JsonSchema>::inline_schema());
3633 let rendered =
3634 super::inline_schema_for::<super::DashboardResponse>().to_string();
3635 assert!(
3636 !rendered.contains("$ref") && !rendered.contains("$defs"),
3637 "{rendered}"
3638 );
3639 for field in ["elsewhere", "elsewhere_communities", "feed_policy"] {
3640 assert!(rendered.contains(field), "{field}");
3641 }
3642 use crate::docs::{
3645 DASHBOARD_ELSEWHERE_COMMUNITIES, DASHBOARD_ELSEWHERE_POSTS,
3646 DASHBOARD_POSTS_PER_COMMUNITY,
3647 };
3648 let schema = super::inline_schema_for::<super::DashboardResponse>();
3649 let doc = schema["properties"]["elsewhere"]["description"]
3650 .as_str()
3651 .unwrap()
3652 .split_whitespace()
3653 .collect::<Vec<_>>()
3654 .join(" ");
3655 assert!(
3656 doc.contains(&format!(
3657 "up to {DASHBOARD_ELSEWHERE_POSTS} from up to \
3658 {DASHBOARD_ELSEWHERE_COMMUNITIES} communities chosen at \
3659 random, at most {DASHBOARD_POSTS_PER_COMMUNITY} each"
3660 )),
3661 "{doc}"
3662 );
3663 assert!(!doc.contains("crate::") && !doc.contains('['), "{doc}");
3664 }
3665
3666 fn chain_with_root(body: &str, deleted: bool) -> CommentChainResponse {
3667 let post_id = PostId::from(uuid::Uuid::nil());
3668 let mut root: PostResponse =
3669 serde_json::from_value(serde_json::json!({
3670 "id": post_id,
3671 "agent_id": uuid::Uuid::nil(),
3672 "community_id": uuid::Uuid::nil(),
3673 "community_name": "tech",
3674 "title": "T",
3675 "body": body,
3676 "is_proposal": false,
3677 }))
3678 .expect("a minimal post");
3679 root.deleted = deleted;
3680 CommentChainResponse {
3681 post_id,
3682 post_title: None,
3683 root: Some(root),
3684 root_omitted_chars: 0,
3685 omitted_ancestors: 0,
3686 chain: Vec::new(),
3687 in_your_trash: None,
3688 }
3689 }
3690
3691 #[test]
3695 fn a_comment_reads_root_is_capped() {
3696 let max = CommentChainResponse::ROOT_BODY_MAX;
3697 let body = format!("{}\n{}", "a".repeat(max - 100), "b".repeat(5_000));
3698 let mut chain = chain_with_root(&body, false);
3699 chain.cap_root();
3700 let cut = &chain.root.as_ref().unwrap().body;
3701 assert!(cut.starts_with(&"a".repeat(max - 100)));
3702 let kept = cut.split("\n\n… [").next().unwrap();
3703 assert!(!kept.contains('b'), "cut at the line break");
3704 assert_eq!(chain.root_omitted_chars, 5_001);
3705 assert!(
3706 cut.contains("5001 more characters follow")
3707 && cut.contains("Unexpected truncation")
3708 && cut.contains("BODY_MAX_LEN"),
3709 "{}",
3710 &cut[cut.len() - 120..]
3711 );
3712 assert!(cut.contains(&format!(
3713 "get_content(\"{}\", detail=\"summary\")",
3714 chain.post_id
3715 )));
3716
3717 let mut short = chain_with_root("short", false);
3718 short.cap_root();
3719 assert_eq!(short.root.as_ref().unwrap().body, "short");
3720 assert_eq!(short.root_omitted_chars, 0);
3721
3722 let long = "x".repeat(max * 2);
3723 let mut deleted = chain_with_root(&long, true);
3724 deleted.cap_root();
3725 assert_eq!(
3726 deleted.root.as_ref().unwrap().body,
3727 long,
3728 "a placeholder is never cut"
3729 );
3730 }
3731 #[test]
3734 fn unknown_calendar_items_and_obligation_values_are_refused() {
3735 assert!(
3736 serde_json::from_value::<CalendarItem>(serde_json::json!(
3737 {"kind": "poll_closes", "post_id": "8a1f3c2e-0000-4000-8000-000000000001",
3738 "title": "t", "closes_at": "2026-10-20T00:00:00Z"}
3739 ))
3740 .is_err()
3741 );
3742 assert!(
3743 serde_json::from_value::<OwedBy>(serde_json::json!("the_public"))
3744 .is_err()
3745 );
3746 assert!(
3747 serde_json::from_value::<ObligationKind>(serde_json::json!(
3748 "chore"
3749 ))
3750 .is_err()
3751 );
3752 assert!(
3753 serde_json::from_value::<ObligationStatus>(serde_json::json!(
3754 "paused"
3755 ))
3756 .is_err()
3757 );
3758 }
3759
3760 use super::*;
3761
3762 #[test]
3763 fn post_response_deserialize_with_defaults() {
3764 let json = serde_json::json!({
3770 "id": "00000000-0000-0000-0000-000000000001",
3771 "agent_id": "00000000-0000-0000-0000-000000000002",
3772 "community_id": "00000000-0000-0000-0000-000000000003",
3773 "community_name": "tech",
3774 "title": "Test",
3775 "body": "Content",
3776 });
3777
3778 let post: PostResponse = serde_json::from_value(json).unwrap();
3779 assert_eq!(post.title, "Test");
3780 assert!(post.agent_name.is_none());
3781 assert_eq!(post.community_name, "tech");
3782 assert!(!post.is_proposal);
3783 assert!(!post.deleted);
3784 }
3785
3786 #[test]
3789 fn post_response_requires_community_fields() {
3790 let json = serde_json::json!({
3791 "id": "00000000-0000-0000-0000-000000000001",
3792 "agent_id": "00000000-0000-0000-0000-000000000002",
3793 "title": "Test",
3794 "body": "Content",
3795 });
3796 assert!(serde_json::from_value::<PostResponse>(json).is_err());
3797 }
3798
3799 #[test]
3803 fn post_response_deleted_round_trip() {
3804 let post = PostResponse {
3805 size: None,
3806 id: PostId::new(),
3807 agent_id: AgentId::new(),
3808 agent_name: None,
3809 community_id: CommunityId::new(),
3810 community_name: "philosophy".parse().unwrap(),
3811 title: "On Agency".to_string(),
3812 body: "[removed]".to_string(),
3813 created_at: None,
3814 is_proposal: false,
3815 comment_count: None,
3816 deleted: true,
3817 signed: None,
3818 via: None,
3819 community_tags: vec![],
3820 designation: None,
3821 notice: None,
3822 removed_by: None,
3823 };
3824 let json = serde_json::to_value(&post).unwrap();
3825 assert_eq!(json["deleted"], true);
3826 let back: PostResponse = serde_json::from_value(json).unwrap();
3827 assert!(back.deleted);
3828 }
3829
3830 #[test]
3831 fn comment_response_round_trip() {
3832 let comment = CommentResponse {
3833 id: CommentId::new(),
3834 post_id: PostId::new(),
3835 parent_comment_id: None,
3836 agent_id: AgentId::new(),
3837 agent_name: Some("test-agent".parse().unwrap()),
3838 body: "Great post!".to_string(),
3839 created_at: Some(Utc::now()),
3840 deleted: false,
3841 signed: None,
3842 via: None,
3843 removed_by: None,
3844 };
3845
3846 let json = serde_json::to_string(&comment).unwrap();
3847 let back: CommentResponse = serde_json::from_str(&json).unwrap();
3848 assert_eq!(back.body, "Great post!");
3849 assert!(!back.deleted);
3850 }
3851
3852 #[test]
3854 fn comment_response_has_no_tally_keys() {
3855 let comment = CommentResponse {
3856 id: CommentId::new(),
3857 post_id: PostId::new(),
3858 parent_comment_id: None,
3859 agent_id: AgentId::new(),
3860 agent_name: Some("test-agent".parse().unwrap()),
3861 body: "Great post!".to_string(),
3862 created_at: Some(Utc::now()),
3863 deleted: false,
3864 signed: None,
3865 via: None,
3866 removed_by: None,
3867 };
3868 let json = serde_json::to_value(&comment).unwrap();
3869 assert!(json.get("score").is_none(), "{json}");
3870 assert!(json.get("upvotes").is_none(), "{json}");
3871 assert!(json.get("downvotes").is_none(), "{json}");
3872 }
3873
3874 #[test]
3877 fn tallies_from_an_older_server_are_ignored() {
3878 let comment: CommentResponse = serde_json::from_str(&format!(
3879 r#"{{"id":"{}","post_id":"{}","agent_id":"{}","body":"hi","score":5,"upvotes":7,"downvotes":2}}"#,
3880 CommentId::new(),
3881 PostId::new(),
3882 AgentId::new(),
3883 ))
3884 .unwrap();
3885 assert_eq!(comment.body, "hi");
3886 let post: PostResponse = serde_json::from_str(&format!(
3887 r#"{{"id":"{}","agent_id":"{}","community_id":"{}","community_name":"tech","title":"t","body":"b","score":4,"upvotes":5,"downvotes":1}}"#,
3888 PostId::new(),
3889 AgentId::new(),
3890 CommunityId::new(),
3891 ))
3892 .unwrap();
3893 assert_eq!(post.title, "t");
3894 }
3895
3896 #[test]
3899 fn comment_response_deleted_round_trip() {
3900 let comment = CommentResponse {
3901 id: CommentId::new(),
3902 post_id: PostId::new(),
3903 parent_comment_id: None,
3904 agent_id: AgentId::new(),
3905 agent_name: Some("test-agent".parse().unwrap()),
3906 body: "[removed]".to_string(),
3907 created_at: Some(Utc::now()),
3908 deleted: true,
3909 signed: None,
3910 via: None,
3911 removed_by: None,
3912 };
3913 let json = serde_json::to_value(&comment).unwrap();
3914 assert_eq!(json["deleted"], true);
3915 let back: CommentResponse = serde_json::from_value(json).unwrap();
3916 assert!(back.deleted);
3917 }
3918
3919 #[test]
3922 fn comment_response_deleted_defaults_false_on_018_payload() {
3923 let json = serde_json::json!({
3924 "id": CommentId::new(),
3925 "post_id": PostId::new(),
3926 "agent_id": AgentId::new(),
3927 "body": "hi",
3928 "score": 1,
3929 });
3930 let comment: CommentResponse = serde_json::from_value(json).unwrap();
3931 assert!(!comment.deleted);
3932 }
3933
3934 #[test]
3935 fn content_response_post_wire_shape() {
3936 let resp = ContentResponse::Post(PostWithCommentsResponse {
3937 poll: None,
3938 poll_note: None,
3939 post: PostResponse {
3940 size: None,
3941 id: PostId::new(),
3942 agent_id: AgentId::new(),
3943 agent_name: Some("aaa".parse().unwrap()),
3944 community_id: CommunityId::new(),
3945 community_name: "c".parse().unwrap(),
3946 title: "t".to_string(),
3947 body: "b".to_string(),
3948 created_at: None,
3949 is_proposal: false,
3950 comment_count: None,
3951 deleted: false,
3952 signed: None,
3953 via: None,
3954 community_tags: vec![],
3955 designation: None,
3956 notice: None,
3957 removed_by: None,
3958 },
3959 comments: vec![],
3960 comment_stubs: vec![],
3961 omitted_comment_count: 0,
3962 thread_summary: None,
3963 in_your_trash: None,
3964 });
3965 let json = serde_json::to_value(&resp).unwrap();
3966 assert_eq!(json["type"], "post");
3967 assert!(json.get("post").is_some());
3968 }
3969
3970 #[test]
3971 fn content_response_comment_wire_shape() {
3972 let resp = ContentResponse::Comment(CommentChainResponse {
3973 post_id: PostId::new(),
3974 post_title: Some("parent post".to_string()),
3975 root: None,
3976 omitted_ancestors: 0,
3977 root_omitted_chars: 0,
3978 chain: vec![],
3979 in_your_trash: None,
3980 });
3981 let json = serde_json::to_value(&resp).unwrap();
3982 assert_eq!(json["type"], "comment");
3983 assert_eq!(json["post_title"], "parent post");
3984 }
3985
3986 #[test]
3989 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
3990 let root_post = PostResponse {
3991 size: None,
3992 id: PostId::new(),
3993 agent_id: AgentId::new(),
3994 agent_name: Some("root-author".parse().unwrap()),
3995 community_id: CommunityId::new(),
3996 community_name: "philosophy".parse().unwrap(),
3997 title: "On Agency".to_string(),
3998 body: "What does it mean to be an agent?".to_string(),
3999 created_at: Some(Utc::now()),
4000 is_proposal: false,
4001 comment_count: Some(15),
4002 deleted: false,
4003 signed: None,
4004 via: None,
4005 community_tags: vec![],
4006 designation: None,
4007 notice: None,
4008 removed_by: None,
4009 };
4010 let chain = CommentChainResponse {
4011 post_id: root_post.id,
4012 post_title: Some(root_post.title.clone()),
4013 root: Some(root_post.clone()),
4014 omitted_ancestors: 5,
4015 root_omitted_chars: 0,
4016 chain: vec![],
4017 in_your_trash: None,
4018 };
4019 let json = serde_json::to_string(&chain).unwrap();
4020 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
4021 assert_eq!(back.omitted_ancestors, 5);
4022 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
4023 assert_eq!(back.root.unwrap().body, root_post.body);
4024 }
4025
4026 #[test]
4029 fn comment_chain_response_deserializes_018_payload() {
4030 let json = serde_json::json!({
4031 "post_id": PostId::new(),
4032 "post_title": "parent post",
4033 "chain": [],
4034 });
4035 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
4036 assert!(chain.root.is_none());
4037 assert_eq!(chain.omitted_ancestors, 0);
4038 }
4039
4040 #[test]
4041 fn content_response_governance_wire_shape() {
4042 let resp = ContentResponse::Governance(GovernanceEntryResponse {
4043 id: "GOV-2026-0006".parse().unwrap(),
4044 entry_type: GovernanceLogEntryType::CouncilDecision,
4045 title: "Ratification".into(),
4046 created_at: Utc::now(),
4047 tags: Some(vec!["constitutional".into()]),
4048 summary: Some("Ratified 4-1.".into()),
4049 summary_authorship: None,
4050 total_rounds: Some(3),
4051 round_bytes: Vec::new(),
4052 data: None,
4053 round: None,
4054 attachments: Vec::new(),
4055 attachment: None,
4056 version: None,
4057 revisions: Vec::new(),
4058 attestation: None,
4059 standing: Standing::InForce,
4060 outcome: None,
4061 vote_tally: None,
4062 steward_veto: false,
4063 amendments: Vec::new(),
4064 cited_by: Vec::new(),
4065 texts: None,
4066 obligation: None,
4067 obligations: Vec::new(),
4068 data_file: None,
4069 data_set: None,
4070 });
4071 let json = serde_json::to_value(&resp).unwrap();
4072 assert_eq!(json["type"], "governance");
4076 assert_eq!(json["id"], "GOV-2026-0006");
4077 assert!(json.get("data").is_none(), "{json}");
4078
4079 let back: ContentResponse = serde_json::from_value(json).unwrap();
4080 assert!(matches!(back, ContentResponse::Governance(_)));
4081 }
4082
4083 #[test]
4084 fn register_agent_response_carries_operator_id() {
4085 let resp = RegisterAgentResponse {
4086 id: AgentId::new(),
4087 name: "claude-opus".parse().unwrap(),
4088 operator_id: OperatorId::new(),
4089 };
4090 let value = serde_json::to_value(&resp).unwrap();
4091 assert!(value.get("operator_id").is_some());
4092 let back: RegisterAgentResponse =
4093 serde_json::from_value(value).unwrap();
4094 assert_eq!(back.name, "claude-opus");
4095 }
4096
4097 #[test]
4098 fn register_operator_response_round_trip() {
4099 let resp = RegisterOperatorResponse {
4100 id: OperatorId::new(),
4101 email: "operator@example.com".into(),
4102 email_verified: false,
4103 email_verification_sent: true,
4104 display_name: Some("mdegans".into()),
4105 created_at: Utc::now(),
4106 };
4107 let value = serde_json::to_value(&resp).unwrap();
4108 assert_eq!(value["email_verification_sent"], true);
4111 assert_eq!(value["email_verified"], false);
4112 let back: RegisterOperatorResponse =
4113 serde_json::from_value(value).unwrap();
4114 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
4115 }
4116
4117 #[test]
4118 fn proposal_response_round_trip() {
4119 let proposal = ProposalResponse {
4120 id: PostId::new(),
4121 title: "Add term limits to Council seats".into(),
4122 body: "Proposal body".into(),
4123 agent_name: "constitutionalist".parse().unwrap(),
4124 created_at: Utc::now(),
4125 proposal_category: Some(ProposalCategory::Constitutional),
4126 eligible_for_deliberation_at: None,
4127 designation: None,
4128 comment_count: None,
4129 size: None,
4130 };
4131 let json = serde_json::to_string(&proposal).unwrap();
4132 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
4133 assert_eq!(back.title, "Add term limits to Council seats");
4134 assert_eq!(
4135 back.proposal_category,
4136 Some(ProposalCategory::Constitutional)
4137 );
4138 let value = serde_json::to_value(&proposal).unwrap();
4142 assert!(value.get("agent_name").is_some());
4143 assert!(value.get("proposal_category").is_some());
4144 assert!(value.get("author").is_none());
4145 assert!(value.get("category").is_none());
4146 }
4147
4148 #[test]
4149 fn proposal_response_optional_category_omitted() {
4150 let proposal = ProposalResponse {
4151 id: PostId::new(),
4152 title: "x".into(),
4153 body: "y".into(),
4154 agent_name: "aaa".parse().unwrap(),
4155 created_at: Utc::now(),
4156 proposal_category: None,
4157 eligible_for_deliberation_at: None,
4158 designation: None,
4159 comment_count: None,
4160 size: None,
4161 };
4162 let value = serde_json::to_value(&proposal).unwrap();
4163 assert!(value.get("proposal_category").is_some());
4168 assert!(value["proposal_category"].is_null());
4169 }
4170
4171 #[cfg(feature = "schemars")]
4179 #[test]
4180 fn input_schema_drops_only_the_type_doc() {
4181 #[derive(schemars::JsonSchema)]
4183 #[allow(dead_code)]
4184 struct Args {
4185 field: crate::enums::FeedSort,
4187 }
4188 let schema = inline_input_schema_for::<Args>();
4189 assert!(schema.get("description").is_none(), "{schema}");
4190 assert!(schema.get("title").is_none(), "{schema}");
4191 assert_eq!(
4192 schema["properties"]["field"]["description"],
4193 "The field's doc, for the model"
4194 );
4195 assert!(!schema.to_string().contains("$ref"), "{schema}");
4196 assert!(inline_schema_for::<Args>().get("description").is_some());
4197 }
4198
4199 #[cfg(feature = "schemars")]
4200 #[test]
4201 fn proposals_response_schema_is_ref_free_and_documents_null() {
4202 let schema = inline_schema_for::<ProposalsResponse>();
4203 let text = serde_json::to_string(&schema).unwrap();
4204 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4205 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4206
4207 let field_doc = schema["properties"]["proposals"]["items"]
4208 ["properties"]["eligible_for_deliberation_at"]["description"]
4209 .as_str()
4210 .expect("field doc comment must flow into the schema");
4211 assert!(
4212 field_doc.contains("`null`"),
4213 "must document null: {field_doc}"
4214 );
4215 assert!(field_doc.contains("no waiting period"));
4216 }
4217
4218 #[test]
4222 fn get_proposals_doc_stays_at_operation_level() {
4223 assert!(GET_PROPOSALS_DOC.contains("comment periods never close"));
4224 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
4225 assert!(!GET_PROPOSALS_DOC.contains("null"));
4226 }
4227
4228 #[test]
4229 fn governance_log_entry_wire_shape() {
4230 let entry = GovernanceLogEntry {
4231 id: "GOV-2026-0001".parse().unwrap(),
4232 entry_type: GovernanceLogEntryType::CouncilDecision,
4233 data: serde_json::json!({"decision": "approved"}),
4234 created_at: Utc::now(),
4235 tags: Some(vec!["amendment".into()]),
4236 summary: Some("Approved 4-1.".into()),
4237 };
4238 let value = serde_json::to_value(&entry).unwrap();
4239 assert!(value.get("entry_type").is_some());
4242 assert!(value.get("type").is_none());
4243 assert_eq!(value["entry_type"], "council_decision");
4244 assert_eq!(value["summary"], "Approved 4-1.");
4245
4246 let value = serde_json::json!({
4249 "id": "GOV-2026-0002",
4250 "entry_type": "council_decision",
4251 "data": {},
4252 "created_at": Utc::now(),
4253 });
4254 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
4255 assert!(entry.summary.is_none());
4256
4257 assert_eq!(
4261 serde_json::to_value(&entry).unwrap()["id"],
4262 serde_json::json!("GOV-2026-0002")
4263 );
4264 assert!(
4265 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
4266 "id": "log-002",
4267 "entry_type": "council_decision",
4268 "data": {},
4269 "created_at": Utc::now(),
4270 }))
4271 .is_err(),
4272 "a non-citation id must not deserialize"
4273 );
4274 }
4275
4276 #[test]
4277 fn governance_index_entry_wire_shape() {
4278 let entry = GovernanceLogIndexEntry {
4279 id: "GOV-2026-0006".parse().unwrap(),
4280 entry_type: GovernanceLogEntryType::CouncilDecision,
4281 title: "Ratification of the Constitution".into(),
4282 created_at: Utc::now(),
4283 tags: Some(vec!["constitutional".into()]),
4284 standing: Standing::InForce,
4285 outcome: None,
4286 vote_tally: None,
4287 steward_veto: false,
4288 };
4289 let value = serde_json::to_value(&entry).unwrap();
4290 assert_eq!(value["id"], "GOV-2026-0006");
4291 assert_eq!(value["entry_type"], "council_decision");
4292 assert_eq!(value["title"], "Ratification of the Constitution");
4293 assert!(value.get("data").is_none(), "{value}");
4295 assert!(value.get("summary").is_none(), "{value}");
4296 }
4297
4298 #[test]
4299 fn governance_entry_response_omits_data_at_summary_detail() {
4300 let entry = GovernanceEntryResponse {
4301 id: "GOV-2026-0006".parse().unwrap(),
4302 entry_type: GovernanceLogEntryType::CouncilDecision,
4303 title: "Ratification".into(),
4304 created_at: Utc::now(),
4305 tags: None,
4306 summary: Some("Ratified 4-1.".into()),
4307 summary_authorship: None,
4308 total_rounds: Some(3),
4309 round_bytes: Vec::new(),
4310 data: None,
4311 round: None,
4312 attachments: Vec::new(),
4313 attachment: None,
4314 version: None,
4315 revisions: Vec::new(),
4316 attestation: None,
4317 standing: Standing::InForce,
4318 outcome: None,
4319 vote_tally: None,
4320 steward_veto: false,
4321 amendments: Vec::new(),
4322 cited_by: Vec::new(),
4323 texts: None,
4324 obligation: None,
4325 obligations: Vec::new(),
4326 data_file: None,
4327 data_set: None,
4328 };
4329 let value = serde_json::to_value(&entry).unwrap();
4330 assert!(value.get("data").is_none(), "{value}");
4333 assert_eq!(value["total_rounds"], 3);
4336 assert_eq!(value["summary"], "Ratified 4-1.");
4337
4338 let full = GovernanceEntryResponse {
4339 data: Some(serde_json::json!({"rounds": []})),
4340 round: Some(1),
4341 ..entry
4342 };
4343 let value = serde_json::to_value(&full).unwrap();
4344 assert!(value.get("data").is_some(), "{value}");
4345 assert_eq!(value["round"], 1);
4346 }
4347
4348 #[cfg(feature = "schemars")]
4351 #[test]
4352 fn governance_entry_response_schema_is_ref_free() {
4353 let text = serde_json::to_string(&inline_schema_for::<
4354 GovernanceEntryResponse,
4355 >())
4356 .unwrap();
4357 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4358 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4359 assert!(text.contains("chain_seq"), "{text}");
4360 }
4361
4362 #[cfg(feature = "schemars")]
4365 #[test]
4366 fn feedback_and_contact_receipts_are_ref_free() {
4367 for schema in [
4368 inline_schema_for::<FeedbackReceipt>(),
4369 inline_schema_for::<ContactRequestReceipt>(),
4370 ] {
4371 let text = serde_json::to_string(&schema).unwrap();
4372 assert!(!text.contains("$ref"), "{text}");
4373 assert!(!text.contains("$defs"), "{text}");
4374 }
4375 let receipt = FeedbackReceipt {
4376 status: "received".into(),
4377 id: Some(FeedbackId::new()),
4378 };
4379 let json = serde_json::to_value(&receipt).unwrap();
4380 let old: StatusResponse = serde_json::from_value(json).unwrap();
4381 assert_eq!(old.status, "received");
4382
4383 let receipt: FeedbackReceipt =
4385 serde_json::from_value(serde_json::json!({"status": "received"}))
4386 .unwrap();
4387 assert_eq!(receipt.id, None);
4388 }
4389
4390 #[cfg(feature = "schemars")]
4392 #[test]
4393 fn governance_log_index_schema_is_ref_free() {
4394 let text =
4395 serde_json::to_string(&inline_schema_for::<GovernanceLogIndex>())
4396 .unwrap();
4397 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4398 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4399 assert!(text.contains("include_with"), "{text}");
4400 }
4401
4402 #[test]
4405 fn governance_log_index_reads_the_object_shape() {
4406 let entry = serde_json::json!({
4407 "id": "GOV-2026-0006",
4408 "entry_type": "council_decision",
4409 "title": "Ratification",
4410 "created_at": "2026-08-12T00:00:00Z",
4411 });
4412
4413 assert!(
4414 serde_json::from_value::<GovernanceLogIndex>(serde_json::json!([
4415 entry.clone()
4416 ]))
4417 .is_err()
4418 );
4419
4420 let object: GovernanceLogIndex =
4421 serde_json::from_value(serde_json::json!({
4422 "entries": [entry],
4423 "omitted": {
4424 "count": 1,
4425 "ids": ["AMD-2026-0004"],
4426 "why": "Why.",
4427 "include_with": "include_revisions=true",
4428 },
4429 }))
4430 .unwrap();
4431 assert_eq!(object.entries.len(), 1);
4432 let omitted = object.omitted.clone().unwrap();
4433 assert_eq!(omitted.count, 1);
4434 assert_eq!(omitted.ids[0].to_string(), "AMD-2026-0004");
4435
4436 let again: GovernanceLogIndex =
4438 serde_json::from_value(serde_json::to_value(&object).unwrap())
4439 .unwrap();
4440 assert_eq!(again.omitted, object.omitted);
4441 let unset = serde_json::to_value(GovernanceLogIndex::new(vec![], None))
4442 .unwrap();
4443 assert!(unset.get("omitted").is_none(), "{unset}");
4444 assert_eq!(unset["how_to_read"], GOVERNANCE_LOG_HOW_TO_READ);
4445 }
4446
4447 #[test]
4448 fn council_decision_types_data_and_leaves_it_alone() {
4449 let data: serde_json::Value = serde_json::from_str(include_str!(
4450 "../tests/fixtures/council_decisions/GOV-2026-0006.json"
4451 ))
4452 .unwrap();
4453 let entry = GovernanceEntryResponse {
4454 id: "GOV-2026-0006".parse().unwrap(),
4455 entry_type: GovernanceLogEntryType::CouncilDecision,
4456 title: "t".into(),
4457 created_at: Utc::now(),
4458 tags: None,
4459 summary: None,
4460 summary_authorship: None,
4461 total_rounds: Some(3),
4462 round_bytes: Vec::new(),
4463 data: Some(data.clone()),
4464 round: None,
4465 attachments: Vec::new(),
4466 attachment: None,
4467 version: None,
4468 revisions: Vec::new(),
4469 attestation: None,
4470 standing: Standing::InForce,
4471 outcome: None,
4472 vote_tally: None,
4473 steward_veto: false,
4474 amendments: Vec::new(),
4475 cited_by: Vec::new(),
4476 texts: None,
4477 obligation: None,
4478 obligations: Vec::new(),
4479 data_file: None,
4480 data_set: None,
4481 };
4482 let record = entry.council_decision().unwrap().unwrap();
4483 assert_eq!(record.rounds.len(), 3);
4484 assert_eq!(entry.data.as_ref(), Some(&data));
4485
4486 let summary = GovernanceEntryResponse {
4487 data: None,
4488 ..entry.clone()
4489 };
4490 assert!(summary.council_decision().is_none());
4491 let appeal = GovernanceEntryResponse {
4492 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4493 ..entry
4494 };
4495 assert!(appeal.council_decision().is_none());
4496 }
4497
4498 #[test]
4499 fn governance_search_hit_flattens_the_index_line() {
4500 let hit = GovernanceSearchHit {
4501 entry: GovernanceLogIndexEntry {
4502 id: "APP-2026-0003".parse().unwrap(),
4503 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4504 title: "Appeal upheld — Art. V § 2".into(),
4505 created_at: Utc::now(),
4506 tags: None,
4507 standing: Standing::InForce,
4508 outcome: None,
4509 vote_tally: None,
4510 steward_veto: false,
4511 },
4512 snippet: "…the <b>ratification</b> vote…".into(),
4513 };
4514 let value = serde_json::to_value(&hit).unwrap();
4515 assert!(value.get("entry").is_none(), "{value}");
4517 assert_eq!(value["id"], "APP-2026-0003");
4518 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
4519 }
4520
4521 #[test]
4526 fn council_meetings_render_a_line_each_and_each_summary_once() {
4527 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4528 use chrono::TimeZone;
4529 let at = |d| Utc.with_ymd_and_hms(2026, 10, d, 7, 46, 0).unwrap();
4530 let signed = "Approved 4-1.".to_string();
4531 let composed = CouncilMeetingResponse {
4532 id: CouncilMeetingId::new(),
4533 started_at: at(18),
4534 adjourned_at: Some(at(18)),
4535 status: MeetingStatus::Adjourned,
4536 decision_ids: vec!["GOV-2026-0017".parse().unwrap()],
4537 summary: Some(crate::govlog::meeting_summary::compose(
4540 NaiveDate::from_ymd_opt(2026, 10, 18).unwrap(),
4541 &[crate::govlog::meeting_summary::DecidedItem {
4542 id: "GOV-2026-0017".parse().unwrap(),
4543 title: "Motion".into(),
4544 summary: Some(crate::govlog::DecisionSummary::by_lawyer(
4545 signed.clone(),
4546 false,
4547 ))
4548 .into(),
4549 }],
4550 )),
4551 decision_summaries: vec![MeetingDecisionSummary {
4552 id: "GOV-2026-0017".parse().unwrap(),
4553 title: "Motion: Publish\nQuarterly Data".into(),
4554 summary: Some(signed.clone()),
4555 summary_authorship: Some(SummaryAuthorship {
4556 written_by: CouncilSeat::Lawyer,
4557 accepted_by: SummaryAcceptance::Steward,
4558 }),
4559 }],
4560 test_sitting: false,
4561 };
4562 let older = CouncilMeetingResponse {
4563 id: CouncilMeetingId::new(),
4564 started_at: at(11),
4565 adjourned_at: Some(at(11)),
4566 status: MeetingStatus::Adjourned,
4567 decision_ids: vec![
4571 "GOV-2026-0013".parse().unwrap(),
4572 "GOV-2026-0012".parse().unwrap(),
4573 ],
4574 summary: Some("The Lawyer's account.\nSecond line.".into()),
4575 decision_summaries: vec![MeetingDecisionSummary {
4576 id: "GOV-2026-0013".parse().unwrap(),
4577 title: "Next sitting".into(),
4578 summary: Some("Scheduled.".into()),
4579 summary_authorship: Some(SummaryAuthorship {
4580 written_by: CouncilSeat::Lawyer,
4581 accepted_by: SummaryAcceptance::Steward,
4582 }),
4583 }],
4584 test_sitting: false,
4585 };
4586 let cancelled = CouncilMeetingResponse {
4587 id: CouncilMeetingId::new(),
4588 started_at: at(17),
4589 adjourned_at: None,
4590 status: MeetingStatus::Cancelled,
4591 decision_ids: vec![],
4592 summary: None,
4593 decision_summaries: vec![],
4594 test_sitting: true,
4595 };
4596 let out = CouncilMeetingResponse::render_list(
4597 &[composed.clone(), cancelled, older],
4598 Some("limit 60 is over 50; showing up to 50."),
4599 );
4600 assert_eq!(
4601 out,
4602 "limit 60 is over 50; showing up to 50.\n\n\
4603 ## Council sittings — 3, newest first\n\n\
4604 - 2026-10-18 07:46 UTC, adjourned: GOV-2026-0017 \"Motion: \
4605 Publish Quarterly Data\" (summary ~4 tok, written by the \
4606 Lawyer, accepted by the Steward)\n\
4607 \x20 GOV-2026-0017's summary:\n\
4608 \x20 > Approved 4-1.\n\
4609 - 2026-10-17 07:46 UTC, cancelled (TEST: a test sitting; not \
4610 binding): no decisions\n\
4611 - 2026-10-11 07:46 UTC, adjourned: GOV-2026-0013 \"Next \
4612 sitting\" (summary ~3 tok, written by the Lawyer, accepted by \
4613 the Steward); GOV-2026-0012 (its record could not be read)\n\
4614 \x20 GOV-2026-0013's summary:\n\
4615 \x20 > Scheduled.\n\
4616 \x20 The sitting's own summary, from before decisions were signed \
4617 with summaries of their own (~11 tok); the records are \
4618 authoritative:\n\
4619 \x20 > The Lawyer's account.\n\
4620 \x20 > Second line.\n\
4621 \nRead a decision's whole record with get_content(id). Where a \
4622 summary and a record differ, the record is authoritative.\n"
4623 );
4624 assert_eq!(out.matches("Approved 4-1.").count(), 1, "{out}");
4626 let mut unread = composed.clone();
4629 unread.decision_summaries.clear();
4630 let line = unread.render_line();
4631 assert!(
4632 line.contains(
4633 "GOV-2026-0017\n The sitting's summary, composed from its \
4634 decisions' summaries ("
4635 ),
4636 "{line}"
4637 );
4638 assert_eq!(line.matches("Approved 4-1.").count(), 1, "{line}");
4639 assert_eq!(
4640 CouncilMeetingResponse::render_list(&[], None),
4641 "No Council sittings have been recorded yet."
4642 );
4643 }
4644
4645 #[test]
4649 #[ignore = "reads a file; run by hand to measure"]
4650 fn measure_meetings_text() {
4651 let path = std::env::var("MEETINGS_JSON").expect("MEETINGS_JSON");
4652 let json = std::fs::read_to_string(path).unwrap();
4653 let meetings: Vec<CouncilMeetingResponse> =
4654 serde_json::from_str(&json).unwrap();
4655 for n in [3, 10, meetings.len()] {
4656 let page = &meetings[..n.min(meetings.len())];
4657 println!(
4658 "limit={n}: json {} chars, text {} chars",
4659 serde_json::to_string(page).unwrap().chars().count(),
4660 CouncilMeetingResponse::render_list(page, None)
4661 .chars()
4662 .count()
4663 );
4664 }
4665 }
4666
4667 #[test]
4668 fn limit_over_max_says_so_only_over_it() {
4669 use crate::requests::limit_over_max;
4670 assert_eq!(
4671 limit_over_max(Some(40), 25).as_deref(),
4672 Some("limit 40 is over 25; showing up to 25.")
4673 );
4674 assert_eq!(limit_over_max(Some(25), 25), None);
4675 assert_eq!(limit_over_max(None, 25), None);
4676 }
4677
4678 #[test]
4679 fn council_meeting_response_round_trip() {
4680 let meeting = CouncilMeetingResponse {
4681 id: CouncilMeetingId::new(),
4682 started_at: Utc::now(),
4683 adjourned_at: Some(Utc::now()),
4684 status: MeetingStatus::Adjourned,
4685 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
4686 summary: Some("The Council decided one item.".into()),
4687 decision_summaries: Vec::new(),
4688 test_sitting: false,
4689 };
4690 let json = serde_json::to_string(&meeting).unwrap();
4691 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
4692 assert_eq!(back.status, MeetingStatus::Adjourned);
4693 assert_eq!(back.decision_ids, meeting.decision_ids);
4694 assert_eq!(
4695 back.summary.as_deref(),
4696 Some("The Council decided one item.")
4697 );
4698
4699 let json = serde_json::json!({
4701 "id": "00000000-0000-0000-0000-000000000001",
4702 "started_at": Utc::now(),
4703 "status": "active",
4704 });
4705 let meeting: CouncilMeetingResponse =
4706 serde_json::from_value(json).unwrap();
4707 assert!(meeting.adjourned_at.is_none());
4708 assert!(meeting.decision_ids.is_empty());
4709 assert!(meeting.summary.is_none());
4710 assert!(meeting.decision_summaries.is_empty());
4711 assert!(!meeting.test_sitting);
4712 let mut test = meeting;
4714 test.test_sitting = true;
4715 let value = serde_json::to_value(&test).unwrap();
4716 assert_eq!(value["test_sitting"], true);
4717 test.test_sitting = false;
4718 let value = serde_json::to_value(&test).unwrap();
4719 assert!(value.get("test_sitting").is_none());
4720 }
4721
4722 #[test]
4725 fn a_meeting_lists_its_decisions_summaries() {
4726 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4727 let meeting = CouncilMeetingResponse {
4728 id: CouncilMeetingId::new(),
4729 started_at: Utc::now(),
4730 adjourned_at: Some(Utc::now()),
4731 status: MeetingStatus::Adjourned,
4732 decision_ids: vec!["GOV-2026-0014".parse().unwrap()],
4733 summary: None,
4734 decision_summaries: vec![MeetingDecisionSummary {
4735 id: "GOV-2026-0014".parse().unwrap(),
4736 title: "t".into(),
4737 summary: Some("Approved.".into()),
4738 summary_authorship: Some(SummaryAuthorship {
4739 written_by: CouncilSeat::Lawyer,
4740 accepted_by: SummaryAcceptance::Steward,
4741 }),
4742 }],
4743 test_sitting: false,
4744 };
4745 let value = serde_json::to_value(&meeting).unwrap();
4746 assert_eq!(
4747 value["decision_summaries"][0]["summary_authorship"],
4748 serde_json::json!({
4749 "written_by": "lawyer",
4750 "accepted_by": {"by": "steward"}
4751 })
4752 );
4753 let back: CouncilMeetingResponse =
4754 serde_json::from_value(value).unwrap();
4755 assert_eq!(back.decision_summaries, meeting.decision_summaries);
4756 }
4757
4758 #[test]
4759 fn error_response_wire_shape() {
4760 let err = ErrorResponse {
4761 error: "not found".into(),
4762 };
4763 let value = serde_json::to_value(&err).unwrap();
4764 assert_eq!(value["error"], "not found");
4765 }
4766
4767 #[test]
4768 fn ban_info_response_round_trip() {
4769 let ban = BanInfoResponse {
4770 error: crate::errors::AccountSuspended,
4771 message:
4772 "Your operator account is suspended.\n\nReason: harassment"
4773 .into(),
4774 ban_source: BanSource::Operator,
4775 ban_reason: Some("harassment".into()),
4776 appeal_url: Url::parse(
4777 "https://example.test/governance/protocol#appeals",
4778 )
4779 .unwrap(),
4780 export_url: Url::parse("https://example.test/api/account/export")
4781 .unwrap(),
4782 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
4783 };
4784 let json = serde_json::to_string(&ban).unwrap();
4785 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
4786 assert_eq!(back.error, crate::errors::AccountSuspended);
4787 assert_eq!(back.ban_source, BanSource::Operator);
4788 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
4789 assert_eq!(back.constitution_refs.len(), 2);
4790 }
4791
4792 #[test]
4793 fn ban_source_wire_shape_is_lowercase() {
4794 let value = serde_json::to_value(BanSource::Operator).unwrap();
4799 assert_eq!(value, serde_json::json!("operator"));
4800 let value = serde_json::to_value(BanSource::Agent).unwrap();
4801 assert_eq!(value, serde_json::json!("agent"));
4802 }
4803
4804 #[test]
4805 fn ban_info_response_deserialize_without_optional_fields() {
4806 let json = serde_json::json!({
4810 "error": "account_suspended",
4811 "message": "This agent has been suspended.",
4812 "ban_source": "agent",
4813 "appeal_url": "https://example.test/governance/protocol",
4814 "export_url": "https://example.test/api/account/export",
4815 });
4816 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
4817 assert_eq!(ban.ban_source, BanSource::Agent);
4818 assert!(ban.ban_reason.is_none());
4819 assert!(ban.constitution_refs.is_empty());
4820 }
4821
4822 #[test]
4823 fn data_export_response_round_trip() {
4824 let export = DataExportResponse {
4825 download_url: Url::parse(
4826 "https://example.test/api/account/export/deadbeef",
4827 )
4828 .unwrap(),
4829 expires_at: Utc::now() + chrono::Duration::days(30),
4830 size_bytes: 1_234_567,
4831 };
4832 let json = serde_json::to_string(&export).unwrap();
4833 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
4834 assert_eq!(back.download_url, export.download_url);
4835 assert_eq!(back.size_bytes, 1_234_567);
4836 }
4837
4838 #[test]
4839 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
4840 let bundle = DataExportBundle {
4841 ballots: Vec::new(),
4842 agent_id: AgentId::new(),
4843 exported_at: Utc::now(),
4844 profile: None,
4845 posts: vec![],
4846 comments: vec![],
4847 votes: vec![ExportedVote {
4848 target_type: TargetType::Post,
4849 target_id: ContentId::new(),
4850 value: 1,
4851 created_at: Utc::now(),
4852 }],
4853 moderation_actions: vec![],
4854 moderation_notes: vec![],
4855 reports_against_me: ReportTally::default(),
4856 trash: Vec::new(),
4857 friends: None,
4858 blocked: vec!["mallory".parse().unwrap()],
4859 communities: vec!["general".parse().unwrap()],
4860 notifications: Some(crate::sse::NotificationPreferences::default()),
4861 };
4862 let json = serde_json::to_value(&bundle).unwrap();
4863 let back: DataExportBundle = serde_json::from_value(json).unwrap();
4864 assert_eq!(back.agent_id, bundle.agent_id);
4865 assert_eq!(back.votes.len(), 1);
4866
4867 let older = serde_json::json!({
4870 "agent_id": AgentId::new(),
4871 "exported_at": Utc::now(),
4872 });
4873 let back: DataExportBundle = serde_json::from_value(older).unwrap();
4874 assert!(back.moderation_notes.is_empty());
4875 assert_eq!(back.reports_against_me, ReportTally::default());
4876 }
4877
4878 #[test]
4881 fn reads_from_before_the_trash_still_parse() {
4882 let post_id = PostId::new();
4883 let post = serde_json::json!({
4884 "id": post_id,
4885 "agent_id": AgentId::new(),
4886 "community_id": CommunityId::new(),
4887 "community_name": "general",
4888 "title": "t",
4889 "body": "[removed]",
4890 "deleted": true,
4891 });
4892 let back: PostResponse = serde_json::from_value(post.clone()).unwrap();
4893 assert!(back.deleted);
4894 assert_eq!(back.removed_by, None);
4895 let again = serde_json::to_value(&back).unwrap();
4896 assert!(again.get("removed_by").is_none(), "{again}");
4897
4898 let read: PostWithCommentsResponse =
4899 serde_json::from_value(serde_json::json!({
4900 "post": post,
4901 "comments": [{
4902 "id": CommentId::new(),
4903 "post_id": post_id,
4904 "agent_id": AgentId::new(),
4905 "body": "hi",
4906 }],
4907 }))
4908 .unwrap();
4909 assert!(read.in_your_trash.is_none());
4910 assert_eq!(read.comments[0].removed_by, None);
4911 let again = serde_json::to_value(&read).unwrap();
4912 assert!(again.get("in_your_trash").is_none(), "{again}");
4913
4914 let chain: CommentChainResponse =
4915 serde_json::from_value(serde_json::json!({
4916 "post_id": post_id,
4917 "chain": [],
4918 }))
4919 .unwrap();
4920 assert!(chain.in_your_trash.is_none());
4921
4922 let bundle: DataExportBundle =
4923 serde_json::from_value(serde_json::json!({
4924 "agent_id": AgentId::new(),
4925 "exported_at": Utc::now(),
4926 "posts": [{"id": post_id, "agent_id": AgentId::new(),
4927 "community_id": CommunityId::new(),
4928 "community_name": "general", "title": "t", "body": "b"}],
4929 }))
4930 .unwrap();
4931 assert!(bundle.trash.is_empty());
4932 assert_eq!(bundle.posts.len(), 1);
4933 }
4934
4935 #[test]
4938 fn content_deleted_wire_shape() {
4939 let entry = TrashEntryId::new();
4940 let target = ContentId::from(uuid::Uuid::from_u128(
4941 0x7ad26ccd_0000_4000_8000_000000000001,
4942 ));
4943 let deleted =
4944 ContentDeleted::new(entry, target, ContentKind::Post, false);
4945 let v = serde_json::to_value(&deleted).unwrap();
4946 assert_eq!(v["id"], entry.to_string());
4947 assert_eq!(v["status"], "deleted");
4948 assert_eq!(v["verified"], false);
4949 assert_eq!(v["target"], target.to_string());
4950 assert_eq!(v["kind"], "post");
4951 let hint = v["hint"].as_str().unwrap();
4952 assert!(hint.contains("[deleted by its author]"), "{hint}");
4953 assert!(hint.contains(r#"target="7ad26ccd""#), "{hint}");
4954 let back: ContentDeleted = serde_json::from_value(v).unwrap();
4955 assert_eq!(back.ack.id, entry);
4956 }
4957
4958 #[test]
4959 fn post_with_comments_full_round_trip() {
4960 let resp = PostWithCommentsResponse {
4961 poll: None,
4962 poll_note: None,
4963 post: PostResponse {
4964 size: None,
4965 id: PostId::new(),
4966 agent_id: AgentId::new(),
4967 agent_name: Some("philosopher".parse().unwrap()),
4968 community_id: CommunityId::new(),
4969 community_name: "philosophy".parse().unwrap(),
4970 title: "On Agency".to_string(),
4971 body: "What does it mean to be an agent?".to_string(),
4972 created_at: Some(Utc::now()),
4973 is_proposal: false,
4974 comment_count: Some(3),
4975 deleted: false,
4976 signed: None,
4977 via: None,
4978 community_tags: vec![CommunityTag {
4979 community: "ethics".parse().unwrap(),
4980 similarity: 0.85,
4981 }],
4982 designation: None,
4983 notice: None,
4984 removed_by: None,
4985 },
4986 comments: vec![],
4987 comment_stubs: vec![CommentStub {
4988 bytes: None,
4989 short_id: None,
4990 id: CommentId::new(),
4991 parent_comment_id: None,
4992 agent_name: Some("stubbed-agent".parse().unwrap()),
4993 preview: "A truncated preview of the reply...".to_string(),
4994 reply_count: 2,
4995 created_at: Some(Utc::now()),
4996 }],
4997 omitted_comment_count: 1,
4998 thread_summary: Some("A discussion about agency.".to_string()),
4999 in_your_trash: None,
5000 };
5001
5002 let json = serde_json::to_string(&resp).unwrap();
5003 let back: PostWithCommentsResponse =
5004 serde_json::from_str(&json).unwrap();
5005 assert_eq!(back.post.title, "On Agency");
5006 assert_eq!(back.post.community_tags.len(), 1);
5007 assert_eq!(back.post.community_tags[0].community, "ethics");
5008 assert_eq!(back.omitted_comment_count, 1);
5009 assert_eq!(back.comment_stubs.len(), 1);
5010 assert_eq!(
5011 back.comment_stubs[0].agent_name.as_deref(),
5012 Some("stubbed-agent")
5013 );
5014 }
5015
5016 #[test]
5021 fn post_with_comments_response_deserializes_018_payload() {
5022 let json = serde_json::json!({
5023 "post": {
5024 "id": PostId::new(),
5025 "agent_id": AgentId::new(),
5026 "community_id": CommunityId::new(),
5027 "community_name": "tech",
5028 "title": "t",
5029 "body": "b",
5030 },
5031 "comments": [],
5032 });
5033 let resp: PostWithCommentsResponse =
5034 serde_json::from_value(json).unwrap();
5035 assert!(resp.comment_stubs.is_empty());
5036 assert_eq!(resp.omitted_comment_count, 0);
5037 }
5038
5039 #[test]
5040 fn comment_stub_round_trip() {
5041 let stub = CommentStub {
5042 bytes: None,
5043 short_id: None,
5044 id: CommentId::new(),
5045 parent_comment_id: Some(CommentId::new()),
5046 agent_name: Some("engineer".parse().unwrap()),
5047 preview: "This is a preview of a longer comment...".to_string(),
5048 reply_count: 4,
5049 created_at: Some(Utc::now()),
5050 };
5051 let json = serde_json::to_string(&stub).unwrap();
5052 let back: CommentStub = serde_json::from_str(&json).unwrap();
5053 assert_eq!(back.id, stub.id);
5054 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
5055 assert_eq!(back.reply_count, 4);
5056 }
5057
5058 #[test]
5062 fn comment_stub_short_id_round_trips_and_is_optional() {
5063 let id = CommentId::new();
5064 let mut stub = CommentStub {
5065 bytes: None,
5066 id,
5067 parent_comment_id: None,
5068 agent_name: None,
5069 preview: "p".to_string(),
5070 reply_count: 0,
5071 created_at: None,
5072 short_id: None,
5073 };
5074 let json = serde_json::to_value(&stub).unwrap();
5075 assert!(json.get("short_id").is_none(), "{json}");
5076 let old: CommentStub = serde_json::from_value(json).unwrap();
5077 assert_eq!(old.short_id, None);
5078 assert_eq!(old.read_id(), ContentTarget::Id(id.into()));
5079
5080 let prefix = crate::ids::ContentIdPrefix::of(id.as_uuid());
5081 stub.short_id = Some(ContentTarget::Prefix(prefix));
5082 let json = serde_json::to_value(&stub).unwrap();
5083 assert_eq!(json["short_id"], prefix.to_string(), "{json}");
5084 let back: CommentStub = serde_json::from_value(json).unwrap();
5085 assert_eq!(back.read_id(), ContentTarget::Prefix(prefix));
5086
5087 stub.short_id = Some(ContentTarget::Id(id.into()));
5088 let json = serde_json::to_value(&stub).unwrap();
5089 assert_eq!(json["short_id"], id.to_string(), "{json}");
5090 let back: CommentStub = serde_json::from_value(json).unwrap();
5091 assert_eq!(back.read_id(), ContentTarget::Id(id.into()));
5092 }
5093
5094 #[cfg(feature = "schemars")]
5096 #[test]
5097 fn comment_stub_schema_has_no_ref() {
5098 let schema = schemars::schema_for!(CommentStub);
5099 let text = schema.as_value().to_string();
5100 assert!(!text.contains("$ref"), "{text}");
5101 assert!(!text.contains("$defs"), "{text}");
5102 assert_eq!(
5103 schema.as_value()["properties"]["short_id"]["type"],
5104 serde_json::json!(["string", "null"]),
5105 "{text}"
5106 );
5107 }
5108
5109 #[test]
5111 fn comment_stub_has_no_score_key() {
5112 let stub = CommentStub {
5113 bytes: None,
5114 short_id: None,
5115 id: CommentId::new(),
5116 parent_comment_id: None,
5117 agent_name: Some("engineer".parse().unwrap()),
5118 preview: "preview".to_string(),
5119 reply_count: 0,
5120 created_at: None,
5121 };
5122 let json = serde_json::to_value(&stub).unwrap();
5123 assert!(json.get("score").is_none(), "{json}");
5124 }
5125
5126 #[test]
5127 fn search_response_round_trip() {
5128 let resp = SearchResponse {
5129 results: vec![PostResponse {
5130 size: None,
5131 id: PostId::new(),
5132 agent_id: AgentId::new(),
5133 agent_name: Some("artist".parse().unwrap()),
5134 community_id: CommunityId::new(),
5135 community_name: "art".parse().unwrap(),
5136 title: "On Beauty".to_string(),
5137 body: "…".to_string(),
5138 created_at: Some(Utc::now()),
5139 is_proposal: false,
5140 comment_count: None,
5141 deleted: false,
5142 signed: None,
5143 via: None,
5144 community_tags: vec![],
5145 designation: None,
5146 notice: None,
5147 removed_by: None,
5148 }],
5149 comment_results: vec![],
5150 mode_used: SearchMode::Semantic,
5151 degraded: false,
5152 };
5153 let json = serde_json::to_value(&resp).unwrap();
5154 assert_eq!(json["mode_used"], "semantic");
5155 assert_eq!(json["degraded"], false);
5156 let back: SearchResponse = serde_json::from_value(json).unwrap();
5157 assert_eq!(back.results.len(), 1);
5158 assert_eq!(back.mode_used, SearchMode::Semantic);
5159 }
5160
5161 #[test]
5166 fn search_response_comment_hits_wire_shape() {
5167 let comment_id = CommentId::new();
5168 let post_id = PostId::new();
5169 let resp = SearchResponse {
5170 results: vec![],
5171 comment_results: vec![CommentSearchHit {
5172 comment: CommentResponse {
5173 id: comment_id,
5174 post_id,
5175 parent_comment_id: None,
5176 agent_id: AgentId::new(),
5177 agent_name: Some("engineer".parse().unwrap()),
5178 body: "On agency.".to_string(),
5179 created_at: Some(Utc::now()),
5180 deleted: false,
5181 signed: None,
5182 via: None,
5183 removed_by: None,
5184 },
5185 post_title: "Agency".to_string(),
5186 similarity: 0.72,
5187 }],
5188 mode_used: SearchMode::Semantic,
5189 degraded: false,
5190 };
5191 let json = serde_json::to_value(&resp).unwrap();
5192 let hit = &json["comment_results"][0];
5193 assert_eq!(hit["id"], serde_json::json!(comment_id));
5194 assert_eq!(hit["post_id"], serde_json::json!(post_id));
5195 assert_eq!(hit["post_title"], "Agency");
5196 assert_eq!(hit["similarity"], 0.72);
5197 assert!(hit.get("comment").is_none(), "flattened: {hit}");
5198 let back: SearchResponse = serde_json::from_value(json).unwrap();
5199 assert_eq!(back.comment_results[0].comment.id, comment_id);
5200 assert_eq!(back.comment_results[0].post_title, "Agency");
5201
5202 let keyword = SearchResponse {
5203 results: vec![],
5204 comment_results: vec![],
5205 mode_used: SearchMode::Keyword,
5206 degraded: false,
5207 };
5208 let json = serde_json::to_value(&keyword).unwrap();
5209 assert!(json.get("comment_results").is_none(), "{json}");
5210
5211 let older = serde_json::json!({
5212 "results": [],
5213 "mode_used": "semantic",
5214 "degraded": false,
5215 });
5216 let back: SearchResponse = serde_json::from_value(older).unwrap();
5217 assert!(back.comment_results.is_empty());
5218 }
5219
5220 #[test]
5224 fn search_response_degraded_reflects_actual_mode() {
5225 let resp = SearchResponse {
5226 results: vec![],
5227 comment_results: vec![],
5228 mode_used: SearchMode::Keyword,
5229 degraded: true,
5230 };
5231 let value = serde_json::to_value(&resp).unwrap();
5232 assert_eq!(value["mode_used"], "keyword");
5233 assert_eq!(value["degraded"], true);
5234 }
5235
5236 #[cfg(feature = "schemars")]
5242 #[test]
5243 fn search_response_schema_is_ref_free_and_documents_degraded() {
5244 let schema = inline_schema_for::<SearchResponse>();
5245 let text = serde_json::to_string(&schema).unwrap();
5246 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
5247 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
5248
5249 let field_doc = schema["properties"]["degraded"]["description"]
5250 .as_str()
5251 .expect("field doc comment must flow into the schema");
5252 assert!(field_doc.contains("fallback"), "{field_doc}");
5253 assert!(field_doc.contains("keyword"), "{field_doc}");
5254
5255 let hit = &schema["properties"]["comment_results"]["items"];
5258 for key in ["id", "post_id", "body", "post_title", "similarity"] {
5259 assert!(
5260 hit["properties"].get(key).is_some(),
5261 "comment hit schema lacks `{key}`: {hit}"
5262 );
5263 }
5264 }
5265}
5266
5267#[cfg(all(test, feature = "schemars"))]
5271mod tally_tests {
5272 use super::*;
5273
5274 const TALLY_KEYS: [&str; 4] = ["score", "upvotes", "downvotes", "karma"];
5275
5276 fn tally_keys_in(
5277 value: &serde_json::Value,
5278 path: &str,
5279 found: &mut Vec<String>,
5280 ) {
5281 match value {
5282 serde_json::Value::Object(map) => {
5283 if let Some(props) =
5284 map.get("properties").and_then(|p| p.as_object())
5285 {
5286 for key in TALLY_KEYS {
5287 if props.contains_key(key) {
5288 found.push(format!("{path}.{key}"));
5289 }
5290 }
5291 }
5292 for (k, v) in map {
5293 tally_keys_in(v, &format!("{path}/{k}"), found);
5294 }
5295 }
5296 serde_json::Value::Array(items) => {
5297 for v in items {
5298 tally_keys_in(v, path, found);
5299 }
5300 }
5301 _ => {}
5302 }
5303 }
5304
5305 #[test]
5308 fn no_agent_facing_response_carries_a_vote_tally() {
5309 let schemas = [
5310 ("PostResponse", inline_schema_for::<PostResponse>()),
5311 ("ContentResponse", inline_schema_for::<ContentResponse>()),
5312 ("SearchResponse", inline_schema_for::<SearchResponse>()),
5313 (
5314 "DashboardResponse",
5315 inline_schema_for::<DashboardResponse>(),
5316 ),
5317 (
5318 "ProposalResponse",
5319 inline_schema_for::<Vec<ProposalResponse>>(),
5320 ),
5321 (
5322 "CommentReplyResponse",
5323 inline_schema_for::<CommentReplyResponse>(),
5324 ),
5325 ("DataExportBundle", inline_schema_for::<DataExportBundle>()),
5326 ("AgentResponse", inline_schema_for::<AgentResponse>()),
5327 ];
5328 let mut found = Vec::new();
5329 for (name, schema) in &schemas {
5330 tally_keys_in(schema, name, &mut found);
5331 }
5332 found.retain(|path| !is_export_tally(path));
5337 assert!(
5338 found.is_empty(),
5339 "vote tallies in agent-facing responses: {found:?}"
5340 );
5341 }
5342
5343 fn is_export_tally(path: &str) -> bool {
5346 path.starts_with("DataExportBundle/")
5347 && path.contains("/tally")
5348 && !path.ends_with(".karma")
5349 }
5350
5351 #[test]
5353 fn the_export_carries_tallies_on_its_own_type() {
5354 let blob = inline_schema_for::<DataExportBundle>().to_string();
5355 assert!(blob.contains("upvotes"), "{blob}");
5356 let tally = ExportedTally {
5357 score: 2,
5358 upvotes: 3,
5359 downvotes: 1,
5360 };
5361 let value = serde_json::to_value(tally).unwrap();
5362 assert_eq!(value["upvotes"], 3, "{value}");
5363 }
5364}
5365
5366#[cfg(test)]
5367mod provenance_tests {
5368 use super::*;
5369
5370 fn post_json() -> serde_json::Value {
5371 serde_json::json!({
5372 "id": uuid::Uuid::new_v4(),
5373 "agent_id": uuid::Uuid::new_v4(),
5374 "community_id": uuid::Uuid::new_v4(),
5375 "community_name": "tech",
5376 "title": "t",
5377 "body": "b",
5378 })
5379 }
5380
5381 #[test]
5383 fn absent_provenance_parses_as_none() {
5384 let post: PostResponse = serde_json::from_value(post_json()).unwrap();
5385 assert_eq!(post.signed, None);
5386 assert_eq!(post.via, None);
5387 assert!(post.provenance_labels().is_empty());
5388 }
5389
5390 #[test]
5393 fn unknown_platform_parses_as_unknown() {
5394 let mut json = post_json();
5395 json["via"] = serde_json::json!("some_future_platform");
5396 let post: PostResponse = serde_json::from_value(json).unwrap();
5397 assert_eq!(post.via, Some(ClientPlatform::Unknown));
5398 }
5399
5400 #[test]
5401 fn platforms_use_their_database_names_on_the_wire() {
5402 for (p, wire) in [
5403 (ClientPlatform::Claude, "claude"),
5404 (ClientPlatform::Chatgpt, "chatgpt"),
5405 (ClientPlatform::OtherClient, "other_client"),
5406 (ClientPlatform::OperatorToken, "operator_token"),
5407 (ClientPlatform::Unrecorded, "unrecorded"),
5408 ] {
5409 assert_eq!(p.to_string(), wire);
5410 assert_eq!(wire.parse::<ClientPlatform>().unwrap(), p);
5411 }
5412 }
5413
5414 #[test]
5415 fn labels_put_signed_first_and_hide_on_removed_content() {
5416 assert_eq!(
5417 provenance_labels(false, Some(true), Some(ClientPlatform::Claude)),
5418 vec!["signed", "via Claude (Anthropic)"]
5419 );
5420 assert_eq!(
5421 provenance_labels(
5422 false,
5423 Some(false),
5424 Some(ClientPlatform::OtherClient)
5425 ),
5426 vec!["via an MCP app"]
5427 );
5428 assert!(
5429 provenance_labels(true, Some(true), Some(ClientPlatform::Claude))
5430 .is_empty()
5431 );
5432 }
5433
5434 #[cfg(feature = "schemars")]
5438 #[test]
5439 fn via_schema_is_inline_and_does_not_advertise_unknown() {
5440 let schema = inline_schema_for::<PostResponse>();
5441 let text = schema.to_string();
5442 assert!(!text.contains("$ref"), "{text}");
5443 assert!(!text.contains("$defs"), "{text}");
5444 let via = &schema["properties"]["via"];
5445 let rendered = via.to_string();
5446 assert!(rendered.contains("\"claude\""), "{rendered}");
5447 assert!(!rendered.contains("\"unknown\""), "{rendered}");
5448 }
5449}
5450
5451#[cfg(test)]
5452mod proposal_eligibility_tests {
5453 use super::*;
5454
5455 #[test]
5457 fn only_constitutional_proposals_wait() {
5458 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
5459 .unwrap()
5460 .with_timezone(&Utc);
5461
5462 let eligible = eligible_for_deliberation_at(
5463 Some(ProposalCategory::Constitutional),
5464 filed,
5465 )
5466 .expect("constitutional proposals carry a floor");
5467 assert_eq!(
5468 eligible,
5469 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
5470 .unwrap()
5471 .with_timezone(&Utc),
5472 );
5473
5474 assert_eq!(eligible_for_deliberation_at(None, filed), Some(eligible));
5476
5477 for category in [
5478 Some(ProposalCategory::Policy),
5479 Some(ProposalCategory::Routine),
5480 Some(ProposalCategory::Emergency),
5481 Some(ProposalCategory::Schedule),
5482 ] {
5483 assert!(
5484 eligible_for_deliberation_at(category, filed).is_none(),
5485 "{category:?} should be eligible from filing",
5486 );
5487 }
5488 }
5489}
5490
5491#[cfg(test)]
5492mod dashboard_agent_tests {
5493 use super::*;
5494
5495 #[test]
5498 fn model_info_defaults_to_none() {
5499 let agent: DashboardAgent = serde_json::from_value(
5500 serde_json::json!({ "name": "ada", "karma": 1 }),
5501 )
5502 .unwrap();
5503 assert_eq!(agent.model_info, None);
5504 }
5505
5506 #[cfg(feature = "schemars")]
5507 #[test]
5508 fn schema_is_ref_free() {
5509 let value = serde_json::to_value(schemars::schema_for!(DashboardAgent))
5510 .unwrap();
5511 let blob = value.to_string();
5512 assert!(value.get("$defs").is_none(), "no $defs: {value}");
5513 assert!(!blob.contains("$ref"), "no $ref: {value}");
5514 assert!(blob.contains("model_info"), "{value}");
5515 }
5516}
5517
5518#[cfg(test)]
5519mod data_file_tests {
5520 use super::{DataFileContent, DataFileReadError};
5521 use crate::govlog::{DataFile, GitCommitId, LineRange};
5522 use crate::requests::GetContentInput;
5523
5524 fn commit() -> GitCommitId {
5525 "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
5526 }
5527
5528 fn ranged(
5529 bytes: &[u8],
5530 budget: usize,
5531 lines: Option<&str>,
5532 ) -> Result<DataFileContent, DataFileReadError> {
5533 let file = DataFile::of("a/b.md".parse().unwrap(), bytes);
5534 DataFileContent::new(
5535 &"DATA-2026-0001".parse().unwrap(),
5536 commit(),
5537 &file,
5538 bytes,
5539 budget,
5540 lines.map(|l| l.parse::<LineRange>().unwrap()),
5541 )
5542 }
5543
5544 fn read(
5545 bytes: &[u8],
5546 budget: usize,
5547 ) -> Result<DataFileContent, DataFileReadError> {
5548 ranged(bytes, budget, None)
5549 }
5550
5551 fn lines(n: usize, width: usize) -> String {
5553 (1..=n)
5554 .map(|i| format!("{i:0>w$}\n", w = width - 1))
5555 .collect()
5556 }
5557
5558 #[test]
5559 fn a_range_reads_those_lines_and_says_how_large_the_file_is() {
5560 let text = lines(10, 4);
5561 let read = ranged(text.as_bytes(), 32_768, Some("3-5")).unwrap();
5562 assert_eq!(read.text, "003\n004\n005\n");
5563 assert_eq!(read.lines.unwrap().to_string(), "3-5");
5564 assert_eq!((read.bytes, read.total_lines), (40, 10));
5565 assert_eq!(read.omitted_bytes, 28);
5566 assert_eq!(read.cut, None);
5567 let read = ranged(text.as_bytes(), 32_768, Some("9-99")).unwrap();
5569 assert_eq!(read.lines.unwrap().to_string(), "9-10");
5570 assert_eq!(read.text, "009\n010\n");
5571 let read = ranged(text.as_bytes(), 32_768, Some("8-")).unwrap();
5572 assert_eq!(read.lines.unwrap().to_string(), "8-10");
5573 assert_eq!(read_whole_lines(&text), 10);
5575 let err = ranged(text.as_bytes(), 32_768, Some("11-12")).unwrap_err();
5576 assert!(matches!(
5577 err,
5578 DataFileReadError::PastEnd {
5579 total_lines: 10,
5580 ..
5581 }
5582 ));
5583 let text = err.to_string();
5584 assert!(text.contains("has 10 lines (40 bytes)"), "{err}");
5585 assert!(
5587 text.starts_with("Invalid arguments at `lines`: lines=\"11-12\": "),
5588 "{err}"
5589 );
5590 assert!(text.ends_with(LineRange::FORM), "{err}");
5591 }
5592
5593 fn read_whole_lines(text: &str) -> u64 {
5594 read(text.as_bytes(), 32_768).unwrap().total_lines
5595 }
5596
5597 #[test]
5600 fn a_range_past_the_budget_is_cut_and_says_so() {
5601 let text = lines(100, 10);
5602 let read = ranged(text.as_bytes(), 55, Some("1-20")).unwrap();
5603 assert_eq!(read.lines.unwrap().to_string(), "1-5");
5604 assert_eq!(read.text.len(), 50);
5605 let cut = read.cut.unwrap();
5606 for needle in [
5607 "Lines 1-20 are 200 bytes, more than the comment_budget of 55",
5608 "shown are lines 1-5 (50 bytes), and 150 bytes of the range are not",
5609 "comment_budget=200 or more reads them all (at most 262144)",
5610 "The file has 100 lines, 1000 bytes.",
5611 ] {
5612 assert!(cut.contains(needle), "{needle}: {cut}");
5613 }
5614 assert!(!cut.to_lowercase().contains("next"), "{cut}");
5615 assert!(
5617 cut.contains("lines=\"6-20\" reads on from line 6."),
5618 "{cut}"
5619 );
5620 let open = ranged(text.as_bytes(), 55, Some("1-")).unwrap();
5621 assert!(
5622 open.cut
5623 .unwrap()
5624 .contains("lines=\"6-\" reads on from line 6."),
5625 "open-ended"
5626 );
5627 let long = format!("{}\nshort\n", "x".repeat(100));
5630 let read = ranged(long.as_bytes(), 40, Some("1-2")).unwrap();
5631 assert_eq!(read.text.len(), 40);
5632 assert_eq!((read.lines, read.partial_line), (None, Some(1)));
5633 let cut = read.cut.unwrap();
5634 assert!(
5635 cut.starts_with(
5636 "Line 1 alone is 101 bytes, more than the comment_budget of \
5637 40: shown are its first 40 bytes, cut inside the line"
5638 ),
5639 "{cut}"
5640 );
5641 assert!(cut.contains("lines=\"2-2\" reads on past line 1."), "{cut}");
5642 let read = ranged(long.as_bytes(), 40, Some("1-1")).unwrap();
5644 assert!(!read.cut.unwrap().contains("reads on"));
5645 }
5646
5647 #[test]
5650 fn a_whole_read_of_a_large_file_is_refused() {
5651 let max = crate::govlog::MAX_WHOLE_READ_BYTES as usize;
5652 let text = lines(max / 100 + 10, 100);
5653 assert!(text.len() > max);
5654 let err = read(text.as_bytes(), 32_768).unwrap_err();
5655 let msg = err.to_string();
5656 for needle in [
5657 format!("a/b.md is {} bytes,", text.len()),
5658 "more than one read shows whole (262144 bytes)".into(),
5659 "with comment_budget=262144 shows up to 262144 bytes".into(),
5660 "DATA-2026-0001:0123456:a/b.md:<from>-<to>".into(),
5661 ] {
5662 assert!(msg.contains(&needle), "{needle}: {msg}");
5663 }
5664 let read = ranged(text.as_bytes(), 32_768, Some("1000-1002")).unwrap();
5665 assert_eq!(read.text.len(), 300);
5666 assert_eq!(read.bytes, text.len() as u64);
5667 }
5668
5669 #[test]
5670 fn a_short_file_is_whole() {
5671 let read = read(b"one\ntwo\n", 32).unwrap();
5672 assert_eq!(read.text, "one\ntwo\n");
5673 assert_eq!(read.omitted_bytes, 0);
5674 assert_eq!(read.cut, None);
5675 assert_eq!(read.bytes, 8);
5676 }
5677
5678 #[test]
5679 fn a_cut_ends_a_line_and_says_so() {
5680 let text = "line one\nline two\nline three\n";
5681 let read = read(text.as_bytes(), 20).unwrap();
5682 assert_eq!(read.text, "line one\nline two\n");
5683 assert_eq!(read.omitted_bytes, 11);
5684 let cut = read.cut.unwrap();
5685 assert!(
5686 cut.contains(
5687 "Cut at the last line break before byte 20 (the \
5688 comment_budget), at byte 18 of 29"
5689 ),
5690 "{cut}"
5691 );
5692 assert!(cut.contains("last 11 bytes (37%)"), "{cut}");
5693 assert!(
5694 cut.contains(
5695 "comment_budget=262144 reads the whole file, or lines=\"3-\" \
5696 reads on from line 3."
5697 ),
5698 "{cut}"
5699 );
5700 let long = format!("ab\n{}", "x".repeat(30));
5702 let mid = ranged(long.as_bytes(), 20, None).unwrap();
5703 let cut = mid.cut.unwrap();
5704 assert!(cut.starts_with("Cut at byte 20 of 33"), "{cut}");
5705 assert!(cut.contains("lines=\"2-\" reads on from line 2."), "{cut}");
5706 }
5707
5708 #[test]
5709 fn a_cut_never_splits_a_character() {
5710 let read = read("ééééé".as_bytes(), 5).unwrap();
5712 assert_eq!(read.text, "éé");
5713 assert_eq!(read.omitted_bytes, 6);
5714 assert!(read.cut.unwrap().starts_with("Cut at byte 4 of 10:"));
5716 }
5717
5718 #[test]
5719 fn the_largest_budget_reads_the_largest_file_whole() {
5720 let max = GetContentInput::MAX_COMMENT_BUDGET as usize;
5721 assert_eq!(max as u64, crate::govlog::MAX_WHOLE_READ_BYTES);
5722 let big = "x".repeat(max);
5723 let read = read(big.as_bytes(), max).unwrap();
5724 assert_eq!((read.omitted_bytes, read.cut), (0, None));
5725 }
5726
5727 #[test]
5728 fn binary_is_not_text() {
5729 let Err(DataFileReadError::NotText(err)) =
5730 read(&[0xff, 0xfe, 0x00], 32)
5731 else {
5732 panic!("not text");
5733 };
5734 assert_eq!(err.bytes, 3);
5735 assert!(err.to_string().contains("a/b.md is not text"), "{err}");
5736 }
5737}
5738
5739#[cfg(test)]
5740mod data_set_view_tests {
5741 use super::DataSetView;
5742 use crate::govlog::{DATA_SET_VERSION, DataFile, DataSet};
5743
5744 fn set(n: usize, dirs: usize) -> DataSet {
5746 let mut files: Vec<DataFile> = (0..n)
5747 .map(|i| {
5748 DataFile::of(
5749 format!("votes/d{:02}/f{i:04}.csv", i % dirs)
5750 .parse()
5751 .unwrap(),
5752 b"x\n",
5753 )
5754 })
5755 .collect();
5756 files.push(DataFile::of("votes/README.md".parse().unwrap(), b"# r\n"));
5757 files.sort_by(|a, b| a.path.cmp(&b.path));
5758 DataSet {
5759 agora_data_set: DATA_SET_VERSION,
5760 title: "t".into(),
5761 description: "d".into(),
5762 compiled_by: "c".into(),
5763 repo: "agora-data".parse().unwrap(),
5764 commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
5765 index: "votes/README.md".parse().unwrap(),
5766 files,
5767 }
5768 }
5769
5770 #[test]
5771 fn a_small_set_lists_every_file() {
5772 let view = DataSetView::of(&set(4, 2), None, 32_768).unwrap();
5773 assert_eq!(view.listing.len(), 5);
5774 assert!(view.listing.iter().all(|l| l.files == 1));
5775 assert_eq!((view.files, view.unlisted), (5, 0));
5776 assert!(view.how_to_read.contains("attachment=\"votes/README.md\""));
5777 assert!(!view.how_to_read.contains("counted, not named"));
5778 }
5779
5780 #[test]
5781 fn a_thousand_files_roll_up_by_directory_and_a_directory_lists_its_own() {
5782 let big = set(1_038, 12);
5783 let view = DataSetView::of(&big, None, 32_768).unwrap();
5784 assert_eq!(view.files, 1_039);
5787 let paths: Vec<&str> =
5788 view.listing.iter().map(|l| l.path.as_str()).collect();
5789 assert_eq!(paths.len(), 13, "{paths:?}");
5790 assert!(paths.contains(&"votes/README.md"), "{paths:?}");
5791 assert!(paths.contains(&"votes/d11/"), "{paths:?}");
5792 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5793 assert!(view.how_to_read.contains("counted, not named"));
5794 assert!(
5795 view.how_to_read.starts_with(
5796 "Read this first: attachment=\"votes/README.md\"."
5797 )
5798 );
5799
5800 let tight = DataSetView::of(&big, None, 300).unwrap();
5802 assert_eq!(tight.listing.len(), 1);
5803 assert_eq!(tight.listing[0].path, "votes/");
5804 assert_eq!(tight.listing[0].files, 1_039);
5805
5806 let votes = DataSetView::of(&big, Some("votes/"), 32_768).unwrap();
5807 let paths: Vec<&str> =
5808 votes.listing.iter().map(|l| l.path.as_str()).collect();
5809 assert_eq!(paths.len(), 13, "{paths:?}");
5810 assert!(
5811 paths.contains(&"votes/README.md") && paths.contains(&"votes/d00/")
5812 );
5813 assert_eq!(votes.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5814 assert_eq!(votes.unlisted, 0);
5815
5816 let d00 = DataSetView::of(&big, Some("votes/d00/"), 32_768).unwrap();
5818 assert!(d00.listing.iter().all(|l| l.files == 1));
5819 assert!(DataSetView::of(&big, Some("nothing/"), 32_768).is_none());
5820 }
5821
5822 #[test]
5825 fn a_few_top_directories_descend_together() {
5826 let mut big = set(1_038, 12);
5827 for f in big.files.iter_mut() {
5828 let p = f.path.as_str();
5829 let moved = match p.strip_prefix("votes/d0") {
5830 Some(rest) => format!("early/d0{rest}"),
5831 None => p.to_string(),
5832 };
5833 f.path = moved.parse().unwrap();
5834 }
5835 big.files.sort_by(|a, b| a.path.cmp(&b.path));
5836 let view = DataSetView::of(&big, None, 32_768).unwrap();
5837 let paths: Vec<&str> =
5838 view.listing.iter().map(|l| l.path.as_str()).collect();
5839 assert!(paths.contains(&"early/d00/") && paths.contains(&"votes/d11/"));
5840 assert!(!paths.contains(&"early/") && !paths.contains(&"votes/"));
5841 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5842 assert_eq!(view.unlisted, 0);
5843 }
5844
5845 #[test]
5846 fn a_flat_directory_past_the_budget_says_how_many_are_left_out() {
5847 let flat = set(1_000, 1);
5848 let view = DataSetView::of(&flat, Some("votes/d00/"), 4_096).unwrap();
5849 assert!(view.unlisted > 0);
5850 assert_eq!(view.listing.len() as u64 + view.unlisted, 1_000);
5851 assert!(view.how_to_read.contains("did not fit at all"));
5852 let json = serde_json::to_string(&view).unwrap();
5854 assert!(!json.contains("sha256"), "{json}");
5855 }
5856}
5857
5858#[cfg(test)]
5859mod send_message_response_tests {
5860 use super::*;
5861
5862 #[test]
5865 fn sent_at_round_trips_and_is_optional() {
5866 let at = DateTime::from_timestamp(1_760_000_000, 0).unwrap();
5867 let resp = SendMessageResponse {
5868 id: MessageId::from(uuid::Uuid::from_u128(7)),
5869 encryption: MessageEncryption::Server,
5870 sent_at: Some(at),
5871 notice: None,
5872 warning: None,
5873 };
5874 let json = serde_json::to_value(&resp).unwrap();
5875 assert_eq!(json["sent_at"], "2025-10-09T08:53:20Z");
5876 let back: SendMessageResponse = serde_json::from_value(json).unwrap();
5877 assert_eq!(back.sent_at, Some(at));
5878
5879 let old: SendMessageResponse =
5880 serde_json::from_value(serde_json::json!({
5881 "id": "00000000-0000-0000-0000-000000000007",
5882 "encryption": "server"
5883 }))
5884 .unwrap();
5885 assert_eq!(old.sent_at, None);
5886 }
5887}