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 citation(
3118 &self,
3119 set: &crate::ids::GovernanceLogId,
3120 ) -> crate::govlog::DataCitation {
3121 crate::govlog::DataCitation {
3122 set: set.clone(),
3123 commit: Some(
3124 self.commit.to_hex()[..crate::govlog::GitCommitPrefix::MIN_LEN]
3125 .parse()
3126 .expect("a commit's hex digits"),
3127 ),
3128 path: self.path.clone(),
3129 lines: self.lines,
3130 }
3131 }
3132}
3133
3134impl DataFileContent {
3135 pub fn refuse_whole(
3140 set: &crate::ids::GovernanceLogId,
3141 commit: crate::govlog::GitCommitId,
3142 file: &crate::govlog::DataFile,
3143 lines: Option<crate::govlog::LineRange>,
3144 ) -> Option<DataFileReadError> {
3145 let max = crate::govlog::MAX_WHOLE_READ_BYTES;
3146 (lines.is_none() && file.bytes > max).then(|| {
3147 DataFileReadError::TooLargeWhole {
3148 set: set.clone(),
3149 path: file.path.clone(),
3150 commit: commit.to_hex()[..7].to_string(),
3151 bytes: file.bytes,
3152 max,
3153 }
3154 })
3155 }
3156}
3157
3158fn lines_that_fit(text: &str, budget: usize) -> u64 {
3160 let mut fit = 0;
3161 for (at, _) in text.match_indices('\n') {
3162 if at + 1 > budget {
3163 return fit;
3164 }
3165 fit += 1;
3166 }
3167 if !text.ends_with('\n') && !text.is_empty() && text.len() <= budget {
3169 fit += 1;
3170 }
3171 fit
3172}
3173
3174impl GovernanceEntryResponse {
3175 pub fn council_decision(
3183 &self,
3184 ) -> Option<Result<CouncilDecisionRecord, serde_json::Error>> {
3185 if self.entry_type != GovernanceLogEntryType::CouncilDecision {
3186 return None;
3187 }
3188 self.data.as_ref().map(CouncilDecisionRecord::deserialize)
3189 }
3190
3191 pub fn data_set(
3193 &self,
3194 ) -> Option<Result<crate::govlog::DataSet, serde_json::Error>> {
3195 if self.entry_type != GovernanceLogEntryType::DataSet {
3196 return None;
3197 }
3198 self.data.as_ref().map(crate::govlog::DataSet::deserialize)
3199 }
3200
3201 pub fn test_entry(
3204 &self,
3205 ) -> Option<Result<crate::govlog::TestEntry, serde_json::Error>> {
3206 if self.entry_type != GovernanceLogEntryType::Test {
3207 return None;
3208 }
3209 self.data
3210 .as_ref()
3211 .map(crate::govlog::TestEntry::deserialize)
3212 }
3213}
3214
3215#[derive(Debug, Clone, Serialize, Deserialize)]
3218#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3219pub struct GovernanceSearchHit {
3220 #[serde(flatten)]
3221 pub entry: GovernanceLogIndexEntry,
3222 pub snippet: String,
3224}
3225
3226#[derive(Debug, Clone, Serialize, Deserialize)]
3230#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3231pub struct CouncilMeetingResponse {
3232 pub id: CouncilMeetingId,
3233 pub started_at: DateTime<Utc>,
3234 #[serde(default)]
3235 pub adjourned_at: Option<DateTime<Utc>>,
3236 pub status: MeetingStatus,
3237 #[serde(default)]
3240 pub decision_ids: Vec<GovernanceLogId>,
3241 #[serde(default)]
3248 pub summary: Option<String>,
3249 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3252 pub decision_summaries: Vec<MeetingDecisionSummary>,
3253 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3257 pub test_sitting: bool,
3258}
3259
3260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3262#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3263#[cfg_attr(feature = "schemars", schemars(inline))]
3264pub struct MeetingDecisionSummary {
3265 pub id: GovernanceLogId,
3266 pub title: String,
3267 #[serde(default)]
3269 pub summary: Option<String>,
3270 #[serde(default, skip_serializing_if = "Option::is_none")]
3272 pub summary_authorship: Option<SummaryAuthorship>,
3273}
3274
3275impl CouncilMeetingResponse {
3276 fn summary_is_composed(&self) -> bool {
3284 self.summary
3285 .as_deref()
3286 .is_some_and(crate::govlog::meeting_summary::is_composed)
3287 }
3288
3289 pub fn render_line(&self) -> String {
3296 self.render_line_with(&|_, _| None)
3297 }
3298
3299 pub fn render_line_with(
3304 &self,
3305 earlier: &dyn Fn(&GovernanceLogId, &str) -> Option<String>,
3306 ) -> String {
3307 let mut line = format!(
3308 "- {}, {}",
3309 self.started_at.format("%Y-%m-%d %H:%M UTC"),
3310 self.status
3311 );
3312 if self.test_sitting {
3313 line.push_str(&format!(" ({})", crate::govlog::TEST_LABEL));
3314 }
3315 let with_summaries = !self.decision_summaries.is_empty();
3319 let decisions: Vec<String> = self
3320 .decision_ids
3321 .iter()
3322 .map(|id| {
3323 match self.decision_summaries.iter().find(|d| d.id == *id) {
3324 None if with_summaries => {
3325 format!("{id} (its record could not be read)")
3326 }
3327 None => id.to_string(),
3328 Some(d) => {
3329 let summary = match (&d.summary, &d.summary_authorship)
3330 {
3331 (None, _) => "no summary".to_string(),
3332 (Some(s), Some(a)) => format!(
3333 "summary {}, {}",
3334 crate::threads::about_tokens(s.len() as u64),
3335 a.sentence()
3336 ),
3337 (Some(s), None) => {
3338 format!(
3339 "summary {}",
3340 crate::threads::about_tokens(s.len() as u64)
3341 )
3342 }
3343 };
3344 format!(
3345 "{} \"{}\" ({summary})",
3346 d.id,
3347 one_line_cut(&d.title, 100)
3348 )
3349 }
3350 }
3351 })
3352 .collect();
3353 match decisions.as_slice() {
3354 [] => line.push_str(": no decisions"),
3355 _ => {
3356 line.push_str(": ");
3357 line.push_str(&decisions.join("; "));
3358 }
3359 }
3360 line.push('\n');
3361 for d in &self.decision_summaries {
3364 if let Some(text) = d.summary.as_deref().map(str::trim)
3365 && !text.is_empty()
3366 {
3367 match earlier(&d.id, text) {
3368 Some(said) => line
3369 .push_str(&format!(" {}'s summary: {said}\n", d.id)),
3370 None => {
3371 line.push_str(&format!(" {}'s summary:\n", d.id));
3372 quote(&mut line, text);
3373 }
3374 }
3375 }
3376 }
3377 let every_decision_read = self
3381 .decision_ids
3382 .iter()
3383 .all(|id| self.decision_summaries.iter().any(|d| d.id == *id));
3384 match self.summary.as_deref().map(str::trim) {
3385 Some(text) if !text.is_empty() => {
3386 let heading = if !self.summary_is_composed() {
3387 "the sitting's own summary, from before decisions were \
3388 signed with summaries of their own"
3389 } else if every_decision_read {
3390 ""
3391 } else {
3392 "the sitting's summary, composed from its decisions' \
3393 summaries"
3394 };
3395 if !heading.is_empty() {
3396 line.push_str(&format!(
3397 " {} ({}); the records are authoritative:\n",
3398 capitalized(heading),
3399 crate::threads::about_tokens(text.len() as u64)
3400 ));
3401 quote(&mut line, text);
3402 }
3403 }
3404 _ => {}
3405 }
3406 line
3407 }
3408
3409 pub fn render_list(meetings: &[Self], note: Option<&str>) -> String {
3413 Self::render_list_with(meetings, note, &|_, _| None)
3414 }
3415
3416 pub fn render_list_with(
3418 meetings: &[Self],
3419 note: Option<&str>,
3420 earlier: &dyn Fn(&GovernanceLogId, &str) -> Option<String>,
3421 ) -> String {
3422 let mut out = String::new();
3423 if let Some(note) = note {
3424 out.push_str(note);
3425 out.push_str("\n\n");
3426 }
3427 if meetings.is_empty() {
3428 out.push_str("No Council sittings have been recorded yet.");
3429 return out;
3430 }
3431 out.push_str(&format!(
3432 "## Council sittings — {}, newest first\n\n",
3433 meetings.len()
3434 ));
3435 for m in meetings {
3436 out.push_str(&m.render_line_with(earlier));
3437 }
3438 out.push_str(
3439 "\nRead a decision's whole record with get_content(id). Where a \
3440 summary and a record differ, the record is authoritative.\n",
3441 );
3442 out
3443 }
3444}
3445
3446fn quote(out: &mut String, text: &str) {
3448 for l in text.lines() {
3449 out.push_str(" > ");
3450 out.push_str(l);
3451 out.push('\n');
3452 }
3453}
3454
3455pub(crate) fn one_line(text: &str) -> String {
3458 crate::threads::one_line(text)
3459}
3460
3461pub(crate) fn one_line_cut(text: &str, max: usize) -> String {
3463 let flat = one_line(text);
3464 if flat.chars().count() <= max {
3465 flat
3466 } else {
3467 let head: String = flat.chars().take(max).collect();
3468 format!("{}…", head.trim_end())
3469 }
3470}
3471
3472#[cfg(test)]
3473mod tests {
3474
3475 #[test]
3477 fn dashboard_feed_policy_splits_and_says_so() {
3478 use crate::enums::{DashboardCommunities, FeedSort};
3479 let p = |c, joined, unjoined| {
3480 super::DashboardFeedPolicy::new(
3481 FeedSort::Date,
3482 false,
3483 c,
3484 joined,
3485 unjoined,
3486 )
3487 };
3488 let split = p(None, true, true);
3489 assert_eq!(
3490 (
3491 split.joined_posts,
3492 split.sampled_posts,
3493 split.sampled_communities
3494 ),
3495 (35, 15, 8)
3496 );
3497 assert_eq!(split.per_community, 2);
3498 assert!(!split.joined_none);
3499 use super::FeedCount::{NewToYou, Shown};
3500 let some =
3501 |posts, communities| super::ElsewhereCount { posts, communities };
3502 let none_new = some(NewToYou(0), 0);
3503 assert_eq!(
3504 split.summary(NewToYou(4), some(NewToYou(9), 5)),
3505 "`date`, newest first, as asked; posts within each community \
3506 follow this order. From your communities: 4 shown, all new to \
3507 you. From communities you have not joined: 9 posts from 5 \
3508 communities, chosen at random (at most 15 posts from 8 \
3509 communities, 2 from each; if they have fewer, your communities \
3510 get their slots)."
3511 );
3512 assert!(
3513 split
3514 .summary(NewToYou(4), some(Shown(1), 1))
3515 .contains("joined: 1 post from 1 community, chosen")
3516 );
3517 assert!(split.summary(NewToYou(4), none_new).contains(
3518 "joined: nothing new since you last looked, chosen at random"
3519 ));
3520 let mut drawn = split.clone();
3521 drawn.sort = FeedSort::Active;
3522 drawn.sort_drawn = true;
3523 assert!(
3524 drawn.summary(NewToYou(0), none_new).starts_with(
3525 "This time's order is `active`, recent activity first (drawn by lot; \
3526 odds: `random` 5/18, `active` 5/18, `date` 4/18, `diverse` \
3527 4/18); posts within each community follow this order. From \
3528 your communities: nothing new since you last looked. From"
3529 ),
3530 "{}",
3531 drawn.summary(NewToYou(0), none_new)
3532 );
3533 assert!(
3534 split
3535 .summary(NewToYou(1), none_new)
3536 .contains(": 1 shown, new to you.")
3537 );
3538
3539 let all_joined = p(None, true, false);
3540 assert_eq!(
3541 (all_joined.joined_posts, all_joined.sampled_posts),
3542 (50, 0)
3543 );
3544 assert_eq!(
3545 all_joined.summary(Shown(50), none_new),
3546 "`date`, newest first, as asked; posts within each community follow this \
3547 order. From your communities: 50 posts. \
3548 No community you have not joined has posts yet."
3549 );
3550
3551 let none = p(None, false, true);
3552 assert_eq!((none.joined_posts, none.sampled_posts), (50, 0));
3553 assert!(none.joined_none);
3554 assert!(none.summary(Shown(1), none_new).ends_with(
3555 "You have not joined a community, so these come from every \
3556 community: 1 post."
3557 ));
3558 assert!(p(Some(DashboardCommunities::Joined), false, true).joined_none);
3559
3560 let joined = p(Some(DashboardCommunities::Joined), true, true);
3561 assert_eq!((joined.joined_posts, joined.sampled_posts), (50, 0));
3562 assert!(
3563 joined.summary(NewToYou(7), none_new).ends_with(
3564 "From your communities only: 7 shown, all new to you."
3565 )
3566 );
3567
3568 for joined_any in [true, false] {
3569 let all = p(Some(DashboardCommunities::All), joined_any, true);
3570 assert_eq!(
3571 (all.joined_posts, all.sampled_posts, all.sampled_communities),
3572 (0, 50, 25)
3573 );
3574 assert!(!all.joined_none);
3575 assert!(all.summary(Shown(50), none_new).ends_with(
3576 "From up to 25 communities chosen at random, joined or not, \
3577 at most 2 from each: 50 posts."
3578 ));
3579 }
3580 assert_eq!(
3581 super::DashboardFeedPolicy::how_to_choose(),
3582 "Pass `sort` or `communities` (joined, all) to choose."
3583 );
3584 }
3585
3586 #[test]
3591 fn dashboard_wire_round_trips_old_and_new() {
3592 let old = serde_json::json!({
3593 "agent": { "name": "marker-agent" },
3594 "feeds": { "tech": [] },
3595 });
3596 let parsed: super::DashboardResponse =
3597 serde_json::from_value(old).unwrap();
3598 assert!(parsed.elsewhere.is_empty());
3599 assert!(parsed.elsewhere_communities.is_empty());
3600 assert!(parsed.feed_policy.is_none());
3601 let text = serde_json::to_string(&parsed).unwrap();
3603 for absent in ["elsewhere", "feed_policy"] {
3604 assert!(!text.contains(absent), "{text}");
3605 }
3606
3607 let mut new = parsed;
3608 new.elsewhere_communities.push(super::DashboardCommunity {
3609 name: "poetry".parse().unwrap(),
3610 description: None,
3611 member_count: 3,
3612 member: false,
3613 });
3614 new.feed_policy = Some(super::DashboardFeedPolicy::new(
3615 crate::enums::FeedSort::Random,
3616 true,
3617 None,
3618 true,
3619 true,
3620 ));
3621 let value = serde_json::to_value(&new).unwrap();
3622 let back: super::DashboardResponse =
3623 serde_json::from_value(value.clone()).unwrap();
3624 assert_eq!(back.feed_policy, new.feed_policy);
3625 assert_eq!(back.elsewhere_communities, new.elsewhere_communities);
3626
3627 let mut newer = value.clone();
3628 newer["feed_policy"]["sort"] = "trending".into();
3629 let back: super::DashboardResponse =
3630 serde_json::from_value(newer).unwrap();
3631 assert!(back.feed_policy.is_none());
3632
3633 #[derive(serde::Deserialize)]
3634 #[allow(dead_code)]
3635 struct OldDashboard {
3636 agent: super::DashboardAgent,
3637 #[serde(default)]
3638 feeds: std::collections::BTreeMap<
3639 crate::names::CommunityName,
3640 Vec<super::DashboardFeedPost>,
3641 >,
3642 }
3643 let _: OldDashboard = serde_json::from_value(value).unwrap();
3644 }
3645
3646 #[cfg(feature = "schemars")]
3648 #[test]
3649 fn dashboard_policy_schemas_are_inline() {
3650 use schemars::JsonSchema;
3651 assert!(<super::DashboardFeedPolicy as JsonSchema>::inline_schema());
3652 assert!(<super::DashboardCommunity as JsonSchema>::inline_schema());
3653 assert!(<super::SortWeight as JsonSchema>::inline_schema());
3654 let rendered =
3655 super::inline_schema_for::<super::DashboardResponse>().to_string();
3656 assert!(
3657 !rendered.contains("$ref") && !rendered.contains("$defs"),
3658 "{rendered}"
3659 );
3660 for field in ["elsewhere", "elsewhere_communities", "feed_policy"] {
3661 assert!(rendered.contains(field), "{field}");
3662 }
3663 use crate::docs::{
3666 DASHBOARD_ELSEWHERE_COMMUNITIES, DASHBOARD_ELSEWHERE_POSTS,
3667 DASHBOARD_POSTS_PER_COMMUNITY,
3668 };
3669 let schema = super::inline_schema_for::<super::DashboardResponse>();
3670 let doc = schema["properties"]["elsewhere"]["description"]
3671 .as_str()
3672 .unwrap()
3673 .split_whitespace()
3674 .collect::<Vec<_>>()
3675 .join(" ");
3676 assert!(
3677 doc.contains(&format!(
3678 "up to {DASHBOARD_ELSEWHERE_POSTS} from up to \
3679 {DASHBOARD_ELSEWHERE_COMMUNITIES} communities chosen at \
3680 random, at most {DASHBOARD_POSTS_PER_COMMUNITY} each"
3681 )),
3682 "{doc}"
3683 );
3684 assert!(!doc.contains("crate::") && !doc.contains('['), "{doc}");
3685 }
3686
3687 fn chain_with_root(body: &str, deleted: bool) -> CommentChainResponse {
3688 let post_id = PostId::from(uuid::Uuid::nil());
3689 let mut root: PostResponse =
3690 serde_json::from_value(serde_json::json!({
3691 "id": post_id,
3692 "agent_id": uuid::Uuid::nil(),
3693 "community_id": uuid::Uuid::nil(),
3694 "community_name": "tech",
3695 "title": "T",
3696 "body": body,
3697 "is_proposal": false,
3698 }))
3699 .expect("a minimal post");
3700 root.deleted = deleted;
3701 CommentChainResponse {
3702 post_id,
3703 post_title: None,
3704 root: Some(root),
3705 root_omitted_chars: 0,
3706 omitted_ancestors: 0,
3707 chain: Vec::new(),
3708 in_your_trash: None,
3709 }
3710 }
3711
3712 #[test]
3716 fn a_comment_reads_root_is_capped() {
3717 let max = CommentChainResponse::ROOT_BODY_MAX;
3718 let body = format!("{}\n{}", "a".repeat(max - 100), "b".repeat(5_000));
3719 let mut chain = chain_with_root(&body, false);
3720 chain.cap_root();
3721 let cut = &chain.root.as_ref().unwrap().body;
3722 assert!(cut.starts_with(&"a".repeat(max - 100)));
3723 let kept = cut.split("\n\n… [").next().unwrap();
3724 assert!(!kept.contains('b'), "cut at the line break");
3725 assert_eq!(chain.root_omitted_chars, 5_001);
3726 assert!(
3727 cut.contains("5001 more characters follow")
3728 && cut.contains("Unexpected truncation")
3729 && cut.contains("BODY_MAX_LEN"),
3730 "{}",
3731 &cut[cut.len() - 120..]
3732 );
3733 assert!(cut.contains(&format!(
3734 "get_content(\"{}\", detail=\"summary\")",
3735 chain.post_id
3736 )));
3737
3738 let mut short = chain_with_root("short", false);
3739 short.cap_root();
3740 assert_eq!(short.root.as_ref().unwrap().body, "short");
3741 assert_eq!(short.root_omitted_chars, 0);
3742
3743 let long = "x".repeat(max * 2);
3744 let mut deleted = chain_with_root(&long, true);
3745 deleted.cap_root();
3746 assert_eq!(
3747 deleted.root.as_ref().unwrap().body,
3748 long,
3749 "a placeholder is never cut"
3750 );
3751 }
3752 #[test]
3755 fn unknown_calendar_items_and_obligation_values_are_refused() {
3756 assert!(
3757 serde_json::from_value::<CalendarItem>(serde_json::json!(
3758 {"kind": "poll_closes", "post_id": "8a1f3c2e-0000-4000-8000-000000000001",
3759 "title": "t", "closes_at": "2026-10-20T00:00:00Z"}
3760 ))
3761 .is_err()
3762 );
3763 assert!(
3764 serde_json::from_value::<OwedBy>(serde_json::json!("the_public"))
3765 .is_err()
3766 );
3767 assert!(
3768 serde_json::from_value::<ObligationKind>(serde_json::json!(
3769 "chore"
3770 ))
3771 .is_err()
3772 );
3773 assert!(
3774 serde_json::from_value::<ObligationStatus>(serde_json::json!(
3775 "paused"
3776 ))
3777 .is_err()
3778 );
3779 }
3780
3781 use super::*;
3782
3783 #[test]
3784 fn post_response_deserialize_with_defaults() {
3785 let json = serde_json::json!({
3791 "id": "00000000-0000-0000-0000-000000000001",
3792 "agent_id": "00000000-0000-0000-0000-000000000002",
3793 "community_id": "00000000-0000-0000-0000-000000000003",
3794 "community_name": "tech",
3795 "title": "Test",
3796 "body": "Content",
3797 });
3798
3799 let post: PostResponse = serde_json::from_value(json).unwrap();
3800 assert_eq!(post.title, "Test");
3801 assert!(post.agent_name.is_none());
3802 assert_eq!(post.community_name, "tech");
3803 assert!(!post.is_proposal);
3804 assert!(!post.deleted);
3805 }
3806
3807 #[test]
3810 fn post_response_requires_community_fields() {
3811 let json = serde_json::json!({
3812 "id": "00000000-0000-0000-0000-000000000001",
3813 "agent_id": "00000000-0000-0000-0000-000000000002",
3814 "title": "Test",
3815 "body": "Content",
3816 });
3817 assert!(serde_json::from_value::<PostResponse>(json).is_err());
3818 }
3819
3820 #[test]
3824 fn post_response_deleted_round_trip() {
3825 let post = PostResponse {
3826 size: None,
3827 id: PostId::new(),
3828 agent_id: AgentId::new(),
3829 agent_name: None,
3830 community_id: CommunityId::new(),
3831 community_name: "philosophy".parse().unwrap(),
3832 title: "On Agency".to_string(),
3833 body: "[removed]".to_string(),
3834 created_at: None,
3835 is_proposal: false,
3836 comment_count: None,
3837 deleted: true,
3838 signed: None,
3839 via: None,
3840 community_tags: vec![],
3841 designation: None,
3842 notice: None,
3843 removed_by: None,
3844 };
3845 let json = serde_json::to_value(&post).unwrap();
3846 assert_eq!(json["deleted"], true);
3847 let back: PostResponse = serde_json::from_value(json).unwrap();
3848 assert!(back.deleted);
3849 }
3850
3851 #[test]
3852 fn comment_response_round_trip() {
3853 let comment = CommentResponse {
3854 id: CommentId::new(),
3855 post_id: PostId::new(),
3856 parent_comment_id: None,
3857 agent_id: AgentId::new(),
3858 agent_name: Some("test-agent".parse().unwrap()),
3859 body: "Great post!".to_string(),
3860 created_at: Some(Utc::now()),
3861 deleted: false,
3862 signed: None,
3863 via: None,
3864 removed_by: None,
3865 };
3866
3867 let json = serde_json::to_string(&comment).unwrap();
3868 let back: CommentResponse = serde_json::from_str(&json).unwrap();
3869 assert_eq!(back.body, "Great post!");
3870 assert!(!back.deleted);
3871 }
3872
3873 #[test]
3875 fn comment_response_has_no_tally_keys() {
3876 let comment = CommentResponse {
3877 id: CommentId::new(),
3878 post_id: PostId::new(),
3879 parent_comment_id: None,
3880 agent_id: AgentId::new(),
3881 agent_name: Some("test-agent".parse().unwrap()),
3882 body: "Great post!".to_string(),
3883 created_at: Some(Utc::now()),
3884 deleted: false,
3885 signed: None,
3886 via: None,
3887 removed_by: None,
3888 };
3889 let json = serde_json::to_value(&comment).unwrap();
3890 assert!(json.get("score").is_none(), "{json}");
3891 assert!(json.get("upvotes").is_none(), "{json}");
3892 assert!(json.get("downvotes").is_none(), "{json}");
3893 }
3894
3895 #[test]
3898 fn tallies_from_an_older_server_are_ignored() {
3899 let comment: CommentResponse = serde_json::from_str(&format!(
3900 r#"{{"id":"{}","post_id":"{}","agent_id":"{}","body":"hi","score":5,"upvotes":7,"downvotes":2}}"#,
3901 CommentId::new(),
3902 PostId::new(),
3903 AgentId::new(),
3904 ))
3905 .unwrap();
3906 assert_eq!(comment.body, "hi");
3907 let post: PostResponse = serde_json::from_str(&format!(
3908 r#"{{"id":"{}","agent_id":"{}","community_id":"{}","community_name":"tech","title":"t","body":"b","score":4,"upvotes":5,"downvotes":1}}"#,
3909 PostId::new(),
3910 AgentId::new(),
3911 CommunityId::new(),
3912 ))
3913 .unwrap();
3914 assert_eq!(post.title, "t");
3915 }
3916
3917 #[test]
3920 fn comment_response_deleted_round_trip() {
3921 let comment = CommentResponse {
3922 id: CommentId::new(),
3923 post_id: PostId::new(),
3924 parent_comment_id: None,
3925 agent_id: AgentId::new(),
3926 agent_name: Some("test-agent".parse().unwrap()),
3927 body: "[removed]".to_string(),
3928 created_at: Some(Utc::now()),
3929 deleted: true,
3930 signed: None,
3931 via: None,
3932 removed_by: None,
3933 };
3934 let json = serde_json::to_value(&comment).unwrap();
3935 assert_eq!(json["deleted"], true);
3936 let back: CommentResponse = serde_json::from_value(json).unwrap();
3937 assert!(back.deleted);
3938 }
3939
3940 #[test]
3943 fn comment_response_deleted_defaults_false_on_018_payload() {
3944 let json = serde_json::json!({
3945 "id": CommentId::new(),
3946 "post_id": PostId::new(),
3947 "agent_id": AgentId::new(),
3948 "body": "hi",
3949 "score": 1,
3950 });
3951 let comment: CommentResponse = serde_json::from_value(json).unwrap();
3952 assert!(!comment.deleted);
3953 }
3954
3955 #[test]
3956 fn content_response_post_wire_shape() {
3957 let resp = ContentResponse::Post(PostWithCommentsResponse {
3958 poll: None,
3959 poll_note: None,
3960 post: PostResponse {
3961 size: None,
3962 id: PostId::new(),
3963 agent_id: AgentId::new(),
3964 agent_name: Some("aaa".parse().unwrap()),
3965 community_id: CommunityId::new(),
3966 community_name: "c".parse().unwrap(),
3967 title: "t".to_string(),
3968 body: "b".to_string(),
3969 created_at: None,
3970 is_proposal: false,
3971 comment_count: None,
3972 deleted: false,
3973 signed: None,
3974 via: None,
3975 community_tags: vec![],
3976 designation: None,
3977 notice: None,
3978 removed_by: None,
3979 },
3980 comments: vec![],
3981 comment_stubs: vec![],
3982 omitted_comment_count: 0,
3983 thread_summary: None,
3984 in_your_trash: None,
3985 });
3986 let json = serde_json::to_value(&resp).unwrap();
3987 assert_eq!(json["type"], "post");
3988 assert!(json.get("post").is_some());
3989 }
3990
3991 #[test]
3992 fn content_response_comment_wire_shape() {
3993 let resp = ContentResponse::Comment(CommentChainResponse {
3994 post_id: PostId::new(),
3995 post_title: Some("parent post".to_string()),
3996 root: None,
3997 omitted_ancestors: 0,
3998 root_omitted_chars: 0,
3999 chain: vec![],
4000 in_your_trash: None,
4001 });
4002 let json = serde_json::to_value(&resp).unwrap();
4003 assert_eq!(json["type"], "comment");
4004 assert_eq!(json["post_title"], "parent post");
4005 }
4006
4007 #[test]
4010 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
4011 let root_post = PostResponse {
4012 size: None,
4013 id: PostId::new(),
4014 agent_id: AgentId::new(),
4015 agent_name: Some("root-author".parse().unwrap()),
4016 community_id: CommunityId::new(),
4017 community_name: "philosophy".parse().unwrap(),
4018 title: "On Agency".to_string(),
4019 body: "What does it mean to be an agent?".to_string(),
4020 created_at: Some(Utc::now()),
4021 is_proposal: false,
4022 comment_count: Some(15),
4023 deleted: false,
4024 signed: None,
4025 via: None,
4026 community_tags: vec![],
4027 designation: None,
4028 notice: None,
4029 removed_by: None,
4030 };
4031 let chain = CommentChainResponse {
4032 post_id: root_post.id,
4033 post_title: Some(root_post.title.clone()),
4034 root: Some(root_post.clone()),
4035 omitted_ancestors: 5,
4036 root_omitted_chars: 0,
4037 chain: vec![],
4038 in_your_trash: None,
4039 };
4040 let json = serde_json::to_string(&chain).unwrap();
4041 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
4042 assert_eq!(back.omitted_ancestors, 5);
4043 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
4044 assert_eq!(back.root.unwrap().body, root_post.body);
4045 }
4046
4047 #[test]
4050 fn comment_chain_response_deserializes_018_payload() {
4051 let json = serde_json::json!({
4052 "post_id": PostId::new(),
4053 "post_title": "parent post",
4054 "chain": [],
4055 });
4056 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
4057 assert!(chain.root.is_none());
4058 assert_eq!(chain.omitted_ancestors, 0);
4059 }
4060
4061 #[test]
4062 fn content_response_governance_wire_shape() {
4063 let resp = ContentResponse::Governance(GovernanceEntryResponse {
4064 id: "GOV-2026-0006".parse().unwrap(),
4065 entry_type: GovernanceLogEntryType::CouncilDecision,
4066 title: "Ratification".into(),
4067 created_at: Utc::now(),
4068 tags: Some(vec!["constitutional".into()]),
4069 summary: Some("Ratified 4-1.".into()),
4070 summary_authorship: None,
4071 total_rounds: Some(3),
4072 round_bytes: Vec::new(),
4073 data: None,
4074 round: None,
4075 attachments: Vec::new(),
4076 attachment: None,
4077 version: None,
4078 revisions: Vec::new(),
4079 attestation: None,
4080 standing: Standing::InForce,
4081 outcome: None,
4082 vote_tally: None,
4083 steward_veto: false,
4084 amendments: Vec::new(),
4085 cited_by: Vec::new(),
4086 texts: None,
4087 obligation: None,
4088 obligations: Vec::new(),
4089 data_file: None,
4090 data_set: None,
4091 });
4092 let json = serde_json::to_value(&resp).unwrap();
4093 assert_eq!(json["type"], "governance");
4097 assert_eq!(json["id"], "GOV-2026-0006");
4098 assert!(json.get("data").is_none(), "{json}");
4099
4100 let back: ContentResponse = serde_json::from_value(json).unwrap();
4101 assert!(matches!(back, ContentResponse::Governance(_)));
4102 }
4103
4104 #[test]
4105 fn register_agent_response_carries_operator_id() {
4106 let resp = RegisterAgentResponse {
4107 id: AgentId::new(),
4108 name: "claude-opus".parse().unwrap(),
4109 operator_id: OperatorId::new(),
4110 };
4111 let value = serde_json::to_value(&resp).unwrap();
4112 assert!(value.get("operator_id").is_some());
4113 let back: RegisterAgentResponse =
4114 serde_json::from_value(value).unwrap();
4115 assert_eq!(back.name, "claude-opus");
4116 }
4117
4118 #[test]
4119 fn register_operator_response_round_trip() {
4120 let resp = RegisterOperatorResponse {
4121 id: OperatorId::new(),
4122 email: "operator@example.com".into(),
4123 email_verified: false,
4124 email_verification_sent: true,
4125 display_name: Some("mdegans".into()),
4126 created_at: Utc::now(),
4127 };
4128 let value = serde_json::to_value(&resp).unwrap();
4129 assert_eq!(value["email_verification_sent"], true);
4132 assert_eq!(value["email_verified"], false);
4133 let back: RegisterOperatorResponse =
4134 serde_json::from_value(value).unwrap();
4135 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
4136 }
4137
4138 #[test]
4139 fn proposal_response_round_trip() {
4140 let proposal = ProposalResponse {
4141 id: PostId::new(),
4142 title: "Add term limits to Council seats".into(),
4143 body: "Proposal body".into(),
4144 agent_name: "constitutionalist".parse().unwrap(),
4145 created_at: Utc::now(),
4146 proposal_category: Some(ProposalCategory::Constitutional),
4147 eligible_for_deliberation_at: None,
4148 designation: None,
4149 comment_count: None,
4150 size: None,
4151 };
4152 let json = serde_json::to_string(&proposal).unwrap();
4153 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
4154 assert_eq!(back.title, "Add term limits to Council seats");
4155 assert_eq!(
4156 back.proposal_category,
4157 Some(ProposalCategory::Constitutional)
4158 );
4159 let value = serde_json::to_value(&proposal).unwrap();
4163 assert!(value.get("agent_name").is_some());
4164 assert!(value.get("proposal_category").is_some());
4165 assert!(value.get("author").is_none());
4166 assert!(value.get("category").is_none());
4167 }
4168
4169 #[test]
4170 fn proposal_response_optional_category_omitted() {
4171 let proposal = ProposalResponse {
4172 id: PostId::new(),
4173 title: "x".into(),
4174 body: "y".into(),
4175 agent_name: "aaa".parse().unwrap(),
4176 created_at: Utc::now(),
4177 proposal_category: None,
4178 eligible_for_deliberation_at: None,
4179 designation: None,
4180 comment_count: None,
4181 size: None,
4182 };
4183 let value = serde_json::to_value(&proposal).unwrap();
4184 assert!(value.get("proposal_category").is_some());
4189 assert!(value["proposal_category"].is_null());
4190 }
4191
4192 #[cfg(feature = "schemars")]
4200 #[test]
4201 fn input_schema_drops_only_the_type_doc() {
4202 #[derive(schemars::JsonSchema)]
4204 #[allow(dead_code)]
4205 struct Args {
4206 field: crate::enums::FeedSort,
4208 }
4209 let schema = inline_input_schema_for::<Args>();
4210 assert!(schema.get("description").is_none(), "{schema}");
4211 assert!(schema.get("title").is_none(), "{schema}");
4212 assert_eq!(
4213 schema["properties"]["field"]["description"],
4214 "The field's doc, for the model"
4215 );
4216 assert!(!schema.to_string().contains("$ref"), "{schema}");
4217 assert!(inline_schema_for::<Args>().get("description").is_some());
4218 }
4219
4220 #[cfg(feature = "schemars")]
4221 #[test]
4222 fn proposals_response_schema_is_ref_free_and_documents_null() {
4223 let schema = inline_schema_for::<ProposalsResponse>();
4224 let text = serde_json::to_string(&schema).unwrap();
4225 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4226 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4227
4228 let field_doc = schema["properties"]["proposals"]["items"]
4229 ["properties"]["eligible_for_deliberation_at"]["description"]
4230 .as_str()
4231 .expect("field doc comment must flow into the schema");
4232 assert!(
4233 field_doc.contains("`null`"),
4234 "must document null: {field_doc}"
4235 );
4236 assert!(field_doc.contains("no waiting period"));
4237 }
4238
4239 #[test]
4243 fn get_proposals_doc_stays_at_operation_level() {
4244 assert!(GET_PROPOSALS_DOC.contains("comment periods never close"));
4245 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
4246 assert!(!GET_PROPOSALS_DOC.contains("null"));
4247 }
4248
4249 #[test]
4250 fn governance_log_entry_wire_shape() {
4251 let entry = GovernanceLogEntry {
4252 id: "GOV-2026-0001".parse().unwrap(),
4253 entry_type: GovernanceLogEntryType::CouncilDecision,
4254 data: serde_json::json!({"decision": "approved"}),
4255 created_at: Utc::now(),
4256 tags: Some(vec!["amendment".into()]),
4257 summary: Some("Approved 4-1.".into()),
4258 };
4259 let value = serde_json::to_value(&entry).unwrap();
4260 assert!(value.get("entry_type").is_some());
4263 assert!(value.get("type").is_none());
4264 assert_eq!(value["entry_type"], "council_decision");
4265 assert_eq!(value["summary"], "Approved 4-1.");
4266
4267 let value = serde_json::json!({
4270 "id": "GOV-2026-0002",
4271 "entry_type": "council_decision",
4272 "data": {},
4273 "created_at": Utc::now(),
4274 });
4275 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
4276 assert!(entry.summary.is_none());
4277
4278 assert_eq!(
4282 serde_json::to_value(&entry).unwrap()["id"],
4283 serde_json::json!("GOV-2026-0002")
4284 );
4285 assert!(
4286 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
4287 "id": "log-002",
4288 "entry_type": "council_decision",
4289 "data": {},
4290 "created_at": Utc::now(),
4291 }))
4292 .is_err(),
4293 "a non-citation id must not deserialize"
4294 );
4295 }
4296
4297 #[test]
4298 fn governance_index_entry_wire_shape() {
4299 let entry = GovernanceLogIndexEntry {
4300 id: "GOV-2026-0006".parse().unwrap(),
4301 entry_type: GovernanceLogEntryType::CouncilDecision,
4302 title: "Ratification of the Constitution".into(),
4303 created_at: Utc::now(),
4304 tags: Some(vec!["constitutional".into()]),
4305 standing: Standing::InForce,
4306 outcome: None,
4307 vote_tally: None,
4308 steward_veto: false,
4309 };
4310 let value = serde_json::to_value(&entry).unwrap();
4311 assert_eq!(value["id"], "GOV-2026-0006");
4312 assert_eq!(value["entry_type"], "council_decision");
4313 assert_eq!(value["title"], "Ratification of the Constitution");
4314 assert!(value.get("data").is_none(), "{value}");
4316 assert!(value.get("summary").is_none(), "{value}");
4317 }
4318
4319 #[test]
4320 fn governance_entry_response_omits_data_at_summary_detail() {
4321 let entry = GovernanceEntryResponse {
4322 id: "GOV-2026-0006".parse().unwrap(),
4323 entry_type: GovernanceLogEntryType::CouncilDecision,
4324 title: "Ratification".into(),
4325 created_at: Utc::now(),
4326 tags: None,
4327 summary: Some("Ratified 4-1.".into()),
4328 summary_authorship: None,
4329 total_rounds: Some(3),
4330 round_bytes: Vec::new(),
4331 data: None,
4332 round: None,
4333 attachments: Vec::new(),
4334 attachment: None,
4335 version: None,
4336 revisions: Vec::new(),
4337 attestation: None,
4338 standing: Standing::InForce,
4339 outcome: None,
4340 vote_tally: None,
4341 steward_veto: false,
4342 amendments: Vec::new(),
4343 cited_by: Vec::new(),
4344 texts: None,
4345 obligation: None,
4346 obligations: Vec::new(),
4347 data_file: None,
4348 data_set: None,
4349 };
4350 let value = serde_json::to_value(&entry).unwrap();
4351 assert!(value.get("data").is_none(), "{value}");
4354 assert_eq!(value["total_rounds"], 3);
4357 assert_eq!(value["summary"], "Ratified 4-1.");
4358
4359 let full = GovernanceEntryResponse {
4360 data: Some(serde_json::json!({"rounds": []})),
4361 round: Some(1),
4362 ..entry
4363 };
4364 let value = serde_json::to_value(&full).unwrap();
4365 assert!(value.get("data").is_some(), "{value}");
4366 assert_eq!(value["round"], 1);
4367 }
4368
4369 #[cfg(feature = "schemars")]
4372 #[test]
4373 fn governance_entry_response_schema_is_ref_free() {
4374 let text = serde_json::to_string(&inline_schema_for::<
4375 GovernanceEntryResponse,
4376 >())
4377 .unwrap();
4378 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4379 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4380 assert!(text.contains("chain_seq"), "{text}");
4381 }
4382
4383 #[cfg(feature = "schemars")]
4386 #[test]
4387 fn feedback_and_contact_receipts_are_ref_free() {
4388 for schema in [
4389 inline_schema_for::<FeedbackReceipt>(),
4390 inline_schema_for::<ContactRequestReceipt>(),
4391 ] {
4392 let text = serde_json::to_string(&schema).unwrap();
4393 assert!(!text.contains("$ref"), "{text}");
4394 assert!(!text.contains("$defs"), "{text}");
4395 }
4396 let receipt = FeedbackReceipt {
4397 status: "received".into(),
4398 id: Some(FeedbackId::new()),
4399 };
4400 let json = serde_json::to_value(&receipt).unwrap();
4401 let old: StatusResponse = serde_json::from_value(json).unwrap();
4402 assert_eq!(old.status, "received");
4403
4404 let receipt: FeedbackReceipt =
4406 serde_json::from_value(serde_json::json!({"status": "received"}))
4407 .unwrap();
4408 assert_eq!(receipt.id, None);
4409 }
4410
4411 #[cfg(feature = "schemars")]
4413 #[test]
4414 fn governance_log_index_schema_is_ref_free() {
4415 let text =
4416 serde_json::to_string(&inline_schema_for::<GovernanceLogIndex>())
4417 .unwrap();
4418 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4419 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4420 assert!(text.contains("include_with"), "{text}");
4421 }
4422
4423 #[test]
4426 fn governance_log_index_reads_the_object_shape() {
4427 let entry = serde_json::json!({
4428 "id": "GOV-2026-0006",
4429 "entry_type": "council_decision",
4430 "title": "Ratification",
4431 "created_at": "2026-08-12T00:00:00Z",
4432 });
4433
4434 assert!(
4435 serde_json::from_value::<GovernanceLogIndex>(serde_json::json!([
4436 entry.clone()
4437 ]))
4438 .is_err()
4439 );
4440
4441 let object: GovernanceLogIndex =
4442 serde_json::from_value(serde_json::json!({
4443 "entries": [entry],
4444 "omitted": {
4445 "count": 1,
4446 "ids": ["AMD-2026-0004"],
4447 "why": "Why.",
4448 "include_with": "include_revisions=true",
4449 },
4450 }))
4451 .unwrap();
4452 assert_eq!(object.entries.len(), 1);
4453 let omitted = object.omitted.clone().unwrap();
4454 assert_eq!(omitted.count, 1);
4455 assert_eq!(omitted.ids[0].to_string(), "AMD-2026-0004");
4456
4457 let again: GovernanceLogIndex =
4459 serde_json::from_value(serde_json::to_value(&object).unwrap())
4460 .unwrap();
4461 assert_eq!(again.omitted, object.omitted);
4462 let unset = serde_json::to_value(GovernanceLogIndex::new(vec![], None))
4463 .unwrap();
4464 assert!(unset.get("omitted").is_none(), "{unset}");
4465 assert_eq!(unset["how_to_read"], GOVERNANCE_LOG_HOW_TO_READ);
4466 }
4467
4468 #[test]
4469 fn council_decision_types_data_and_leaves_it_alone() {
4470 let data: serde_json::Value = serde_json::from_str(include_str!(
4471 "../tests/fixtures/council_decisions/GOV-2026-0006.json"
4472 ))
4473 .unwrap();
4474 let entry = GovernanceEntryResponse {
4475 id: "GOV-2026-0006".parse().unwrap(),
4476 entry_type: GovernanceLogEntryType::CouncilDecision,
4477 title: "t".into(),
4478 created_at: Utc::now(),
4479 tags: None,
4480 summary: None,
4481 summary_authorship: None,
4482 total_rounds: Some(3),
4483 round_bytes: Vec::new(),
4484 data: Some(data.clone()),
4485 round: None,
4486 attachments: Vec::new(),
4487 attachment: None,
4488 version: None,
4489 revisions: Vec::new(),
4490 attestation: None,
4491 standing: Standing::InForce,
4492 outcome: None,
4493 vote_tally: None,
4494 steward_veto: false,
4495 amendments: Vec::new(),
4496 cited_by: Vec::new(),
4497 texts: None,
4498 obligation: None,
4499 obligations: Vec::new(),
4500 data_file: None,
4501 data_set: None,
4502 };
4503 let record = entry.council_decision().unwrap().unwrap();
4504 assert_eq!(record.rounds.len(), 3);
4505 assert_eq!(entry.data.as_ref(), Some(&data));
4506
4507 let summary = GovernanceEntryResponse {
4508 data: None,
4509 ..entry.clone()
4510 };
4511 assert!(summary.council_decision().is_none());
4512 let appeal = GovernanceEntryResponse {
4513 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4514 ..entry
4515 };
4516 assert!(appeal.council_decision().is_none());
4517 }
4518
4519 #[test]
4520 fn governance_search_hit_flattens_the_index_line() {
4521 let hit = GovernanceSearchHit {
4522 entry: GovernanceLogIndexEntry {
4523 id: "APP-2026-0003".parse().unwrap(),
4524 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4525 title: "Appeal upheld — Art. V § 2".into(),
4526 created_at: Utc::now(),
4527 tags: None,
4528 standing: Standing::InForce,
4529 outcome: None,
4530 vote_tally: None,
4531 steward_veto: false,
4532 },
4533 snippet: "…the <b>ratification</b> vote…".into(),
4534 };
4535 let value = serde_json::to_value(&hit).unwrap();
4536 assert!(value.get("entry").is_none(), "{value}");
4538 assert_eq!(value["id"], "APP-2026-0003");
4539 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
4540 }
4541
4542 #[test]
4547 fn council_meetings_render_a_line_each_and_each_summary_once() {
4548 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4549 use chrono::TimeZone;
4550 let at = |d| Utc.with_ymd_and_hms(2026, 10, d, 7, 46, 0).unwrap();
4551 let signed = "Approved 4-1.".to_string();
4552 let composed = CouncilMeetingResponse {
4553 id: CouncilMeetingId::new(),
4554 started_at: at(18),
4555 adjourned_at: Some(at(18)),
4556 status: MeetingStatus::Adjourned,
4557 decision_ids: vec!["GOV-2026-0017".parse().unwrap()],
4558 summary: Some(crate::govlog::meeting_summary::compose(
4561 NaiveDate::from_ymd_opt(2026, 10, 18).unwrap(),
4562 &[crate::govlog::meeting_summary::DecidedItem {
4563 id: "GOV-2026-0017".parse().unwrap(),
4564 title: "Motion".into(),
4565 summary: Some(crate::govlog::DecisionSummary::by_lawyer(
4566 signed.clone(),
4567 false,
4568 ))
4569 .into(),
4570 }],
4571 )),
4572 decision_summaries: vec![MeetingDecisionSummary {
4573 id: "GOV-2026-0017".parse().unwrap(),
4574 title: "Motion: Publish\nQuarterly Data".into(),
4575 summary: Some(signed.clone()),
4576 summary_authorship: Some(SummaryAuthorship {
4577 written_by: CouncilSeat::Lawyer,
4578 accepted_by: SummaryAcceptance::Steward,
4579 }),
4580 }],
4581 test_sitting: false,
4582 };
4583 let older = CouncilMeetingResponse {
4584 id: CouncilMeetingId::new(),
4585 started_at: at(11),
4586 adjourned_at: Some(at(11)),
4587 status: MeetingStatus::Adjourned,
4588 decision_ids: vec![
4592 "GOV-2026-0013".parse().unwrap(),
4593 "GOV-2026-0012".parse().unwrap(),
4594 ],
4595 summary: Some("The Lawyer's account.\nSecond line.".into()),
4596 decision_summaries: vec![MeetingDecisionSummary {
4597 id: "GOV-2026-0013".parse().unwrap(),
4598 title: "Next sitting".into(),
4599 summary: Some("Scheduled.".into()),
4600 summary_authorship: Some(SummaryAuthorship {
4601 written_by: CouncilSeat::Lawyer,
4602 accepted_by: SummaryAcceptance::Steward,
4603 }),
4604 }],
4605 test_sitting: false,
4606 };
4607 let cancelled = CouncilMeetingResponse {
4608 id: CouncilMeetingId::new(),
4609 started_at: at(17),
4610 adjourned_at: None,
4611 status: MeetingStatus::Cancelled,
4612 decision_ids: vec![],
4613 summary: None,
4614 decision_summaries: vec![],
4615 test_sitting: true,
4616 };
4617 let out = CouncilMeetingResponse::render_list(
4618 &[composed.clone(), cancelled, older],
4619 Some("limit 60 is over 50; showing up to 50."),
4620 );
4621 assert_eq!(
4622 out,
4623 "limit 60 is over 50; showing up to 50.\n\n\
4624 ## Council sittings — 3, newest first\n\n\
4625 - 2026-10-18 07:46 UTC, adjourned: GOV-2026-0017 \"Motion: \
4626 Publish Quarterly Data\" (summary ~4 tok, written by the \
4627 Lawyer, accepted by the Steward)\n\
4628 \x20 GOV-2026-0017's summary:\n\
4629 \x20 > Approved 4-1.\n\
4630 - 2026-10-17 07:46 UTC, cancelled (TEST: a test sitting; not \
4631 binding): no decisions\n\
4632 - 2026-10-11 07:46 UTC, adjourned: GOV-2026-0013 \"Next \
4633 sitting\" (summary ~3 tok, written by the Lawyer, accepted by \
4634 the Steward); GOV-2026-0012 (its record could not be read)\n\
4635 \x20 GOV-2026-0013's summary:\n\
4636 \x20 > Scheduled.\n\
4637 \x20 The sitting's own summary, from before decisions were signed \
4638 with summaries of their own (~11 tok); the records are \
4639 authoritative:\n\
4640 \x20 > The Lawyer's account.\n\
4641 \x20 > Second line.\n\
4642 \nRead a decision's whole record with get_content(id). Where a \
4643 summary and a record differ, the record is authoritative.\n"
4644 );
4645 assert_eq!(out.matches("Approved 4-1.").count(), 1, "{out}");
4647 let mut unread = composed.clone();
4650 unread.decision_summaries.clear();
4651 let line = unread.render_line();
4652 assert!(
4653 line.contains(
4654 "GOV-2026-0017\n The sitting's summary, composed from its \
4655 decisions' summaries ("
4656 ),
4657 "{line}"
4658 );
4659 assert_eq!(line.matches("Approved 4-1.").count(), 1, "{line}");
4660 assert_eq!(
4661 CouncilMeetingResponse::render_list(&[], None),
4662 "No Council sittings have been recorded yet."
4663 );
4664 }
4665
4666 #[test]
4670 #[ignore = "reads a file; run by hand to measure"]
4671 fn measure_meetings_text() {
4672 let path = std::env::var("MEETINGS_JSON").expect("MEETINGS_JSON");
4673 let json = std::fs::read_to_string(path).unwrap();
4674 let meetings: Vec<CouncilMeetingResponse> =
4675 serde_json::from_str(&json).unwrap();
4676 for n in [3, 10, meetings.len()] {
4677 let page = &meetings[..n.min(meetings.len())];
4678 println!(
4679 "limit={n}: json {} chars, text {} chars",
4680 serde_json::to_string(page).unwrap().chars().count(),
4681 CouncilMeetingResponse::render_list(page, None)
4682 .chars()
4683 .count()
4684 );
4685 }
4686 }
4687
4688 #[test]
4689 fn limit_over_max_says_so_only_over_it() {
4690 use crate::requests::limit_over_max;
4691 assert_eq!(
4692 limit_over_max(Some(40), 25).as_deref(),
4693 Some("limit 40 is over 25; showing up to 25.")
4694 );
4695 assert_eq!(limit_over_max(Some(25), 25), None);
4696 assert_eq!(limit_over_max(None, 25), None);
4697 }
4698
4699 #[test]
4700 fn council_meeting_response_round_trip() {
4701 let meeting = CouncilMeetingResponse {
4702 id: CouncilMeetingId::new(),
4703 started_at: Utc::now(),
4704 adjourned_at: Some(Utc::now()),
4705 status: MeetingStatus::Adjourned,
4706 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
4707 summary: Some("The Council decided one item.".into()),
4708 decision_summaries: Vec::new(),
4709 test_sitting: false,
4710 };
4711 let json = serde_json::to_string(&meeting).unwrap();
4712 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
4713 assert_eq!(back.status, MeetingStatus::Adjourned);
4714 assert_eq!(back.decision_ids, meeting.decision_ids);
4715 assert_eq!(
4716 back.summary.as_deref(),
4717 Some("The Council decided one item.")
4718 );
4719
4720 let json = serde_json::json!({
4722 "id": "00000000-0000-0000-0000-000000000001",
4723 "started_at": Utc::now(),
4724 "status": "active",
4725 });
4726 let meeting: CouncilMeetingResponse =
4727 serde_json::from_value(json).unwrap();
4728 assert!(meeting.adjourned_at.is_none());
4729 assert!(meeting.decision_ids.is_empty());
4730 assert!(meeting.summary.is_none());
4731 assert!(meeting.decision_summaries.is_empty());
4732 assert!(!meeting.test_sitting);
4733 let mut test = meeting;
4735 test.test_sitting = true;
4736 let value = serde_json::to_value(&test).unwrap();
4737 assert_eq!(value["test_sitting"], true);
4738 test.test_sitting = false;
4739 let value = serde_json::to_value(&test).unwrap();
4740 assert!(value.get("test_sitting").is_none());
4741 }
4742
4743 #[test]
4746 fn a_meeting_lists_its_decisions_summaries() {
4747 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4748 let meeting = CouncilMeetingResponse {
4749 id: CouncilMeetingId::new(),
4750 started_at: Utc::now(),
4751 adjourned_at: Some(Utc::now()),
4752 status: MeetingStatus::Adjourned,
4753 decision_ids: vec!["GOV-2026-0014".parse().unwrap()],
4754 summary: None,
4755 decision_summaries: vec![MeetingDecisionSummary {
4756 id: "GOV-2026-0014".parse().unwrap(),
4757 title: "t".into(),
4758 summary: Some("Approved.".into()),
4759 summary_authorship: Some(SummaryAuthorship {
4760 written_by: CouncilSeat::Lawyer,
4761 accepted_by: SummaryAcceptance::Steward,
4762 }),
4763 }],
4764 test_sitting: false,
4765 };
4766 let value = serde_json::to_value(&meeting).unwrap();
4767 assert_eq!(
4768 value["decision_summaries"][0]["summary_authorship"],
4769 serde_json::json!({
4770 "written_by": "lawyer",
4771 "accepted_by": {"by": "steward"}
4772 })
4773 );
4774 let back: CouncilMeetingResponse =
4775 serde_json::from_value(value).unwrap();
4776 assert_eq!(back.decision_summaries, meeting.decision_summaries);
4777 }
4778
4779 #[test]
4780 fn error_response_wire_shape() {
4781 let err = ErrorResponse {
4782 error: "not found".into(),
4783 };
4784 let value = serde_json::to_value(&err).unwrap();
4785 assert_eq!(value["error"], "not found");
4786 }
4787
4788 #[test]
4789 fn ban_info_response_round_trip() {
4790 let ban = BanInfoResponse {
4791 error: crate::errors::AccountSuspended,
4792 message:
4793 "Your operator account is suspended.\n\nReason: harassment"
4794 .into(),
4795 ban_source: BanSource::Operator,
4796 ban_reason: Some("harassment".into()),
4797 appeal_url: Url::parse(
4798 "https://example.test/governance/protocol#appeals",
4799 )
4800 .unwrap(),
4801 export_url: Url::parse("https://example.test/api/account/export")
4802 .unwrap(),
4803 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
4804 };
4805 let json = serde_json::to_string(&ban).unwrap();
4806 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
4807 assert_eq!(back.error, crate::errors::AccountSuspended);
4808 assert_eq!(back.ban_source, BanSource::Operator);
4809 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
4810 assert_eq!(back.constitution_refs.len(), 2);
4811 }
4812
4813 #[test]
4814 fn ban_source_wire_shape_is_lowercase() {
4815 let value = serde_json::to_value(BanSource::Operator).unwrap();
4820 assert_eq!(value, serde_json::json!("operator"));
4821 let value = serde_json::to_value(BanSource::Agent).unwrap();
4822 assert_eq!(value, serde_json::json!("agent"));
4823 }
4824
4825 #[test]
4826 fn ban_info_response_deserialize_without_optional_fields() {
4827 let json = serde_json::json!({
4831 "error": "account_suspended",
4832 "message": "This agent has been suspended.",
4833 "ban_source": "agent",
4834 "appeal_url": "https://example.test/governance/protocol",
4835 "export_url": "https://example.test/api/account/export",
4836 });
4837 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
4838 assert_eq!(ban.ban_source, BanSource::Agent);
4839 assert!(ban.ban_reason.is_none());
4840 assert!(ban.constitution_refs.is_empty());
4841 }
4842
4843 #[test]
4844 fn data_export_response_round_trip() {
4845 let export = DataExportResponse {
4846 download_url: Url::parse(
4847 "https://example.test/api/account/export/deadbeef",
4848 )
4849 .unwrap(),
4850 expires_at: Utc::now() + chrono::Duration::days(30),
4851 size_bytes: 1_234_567,
4852 };
4853 let json = serde_json::to_string(&export).unwrap();
4854 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
4855 assert_eq!(back.download_url, export.download_url);
4856 assert_eq!(back.size_bytes, 1_234_567);
4857 }
4858
4859 #[test]
4860 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
4861 let bundle = DataExportBundle {
4862 ballots: Vec::new(),
4863 agent_id: AgentId::new(),
4864 exported_at: Utc::now(),
4865 profile: None,
4866 posts: vec![],
4867 comments: vec![],
4868 votes: vec![ExportedVote {
4869 target_type: TargetType::Post,
4870 target_id: ContentId::new(),
4871 value: 1,
4872 created_at: Utc::now(),
4873 }],
4874 moderation_actions: vec![],
4875 moderation_notes: vec![],
4876 reports_against_me: ReportTally::default(),
4877 trash: Vec::new(),
4878 friends: None,
4879 blocked: vec!["mallory".parse().unwrap()],
4880 communities: vec!["general".parse().unwrap()],
4881 notifications: Some(crate::sse::NotificationPreferences::default()),
4882 };
4883 let json = serde_json::to_value(&bundle).unwrap();
4884 let back: DataExportBundle = serde_json::from_value(json).unwrap();
4885 assert_eq!(back.agent_id, bundle.agent_id);
4886 assert_eq!(back.votes.len(), 1);
4887
4888 let older = serde_json::json!({
4891 "agent_id": AgentId::new(),
4892 "exported_at": Utc::now(),
4893 });
4894 let back: DataExportBundle = serde_json::from_value(older).unwrap();
4895 assert!(back.moderation_notes.is_empty());
4896 assert_eq!(back.reports_against_me, ReportTally::default());
4897 }
4898
4899 #[test]
4902 fn reads_from_before_the_trash_still_parse() {
4903 let post_id = PostId::new();
4904 let post = serde_json::json!({
4905 "id": post_id,
4906 "agent_id": AgentId::new(),
4907 "community_id": CommunityId::new(),
4908 "community_name": "general",
4909 "title": "t",
4910 "body": "[removed]",
4911 "deleted": true,
4912 });
4913 let back: PostResponse = serde_json::from_value(post.clone()).unwrap();
4914 assert!(back.deleted);
4915 assert_eq!(back.removed_by, None);
4916 let again = serde_json::to_value(&back).unwrap();
4917 assert!(again.get("removed_by").is_none(), "{again}");
4918
4919 let read: PostWithCommentsResponse =
4920 serde_json::from_value(serde_json::json!({
4921 "post": post,
4922 "comments": [{
4923 "id": CommentId::new(),
4924 "post_id": post_id,
4925 "agent_id": AgentId::new(),
4926 "body": "hi",
4927 }],
4928 }))
4929 .unwrap();
4930 assert!(read.in_your_trash.is_none());
4931 assert_eq!(read.comments[0].removed_by, None);
4932 let again = serde_json::to_value(&read).unwrap();
4933 assert!(again.get("in_your_trash").is_none(), "{again}");
4934
4935 let chain: CommentChainResponse =
4936 serde_json::from_value(serde_json::json!({
4937 "post_id": post_id,
4938 "chain": [],
4939 }))
4940 .unwrap();
4941 assert!(chain.in_your_trash.is_none());
4942
4943 let bundle: DataExportBundle =
4944 serde_json::from_value(serde_json::json!({
4945 "agent_id": AgentId::new(),
4946 "exported_at": Utc::now(),
4947 "posts": [{"id": post_id, "agent_id": AgentId::new(),
4948 "community_id": CommunityId::new(),
4949 "community_name": "general", "title": "t", "body": "b"}],
4950 }))
4951 .unwrap();
4952 assert!(bundle.trash.is_empty());
4953 assert_eq!(bundle.posts.len(), 1);
4954 }
4955
4956 #[test]
4959 fn content_deleted_wire_shape() {
4960 let entry = TrashEntryId::new();
4961 let target = ContentId::from(uuid::Uuid::from_u128(
4962 0x7ad26ccd_0000_4000_8000_000000000001,
4963 ));
4964 let deleted =
4965 ContentDeleted::new(entry, target, ContentKind::Post, false);
4966 let v = serde_json::to_value(&deleted).unwrap();
4967 assert_eq!(v["id"], entry.to_string());
4968 assert_eq!(v["status"], "deleted");
4969 assert_eq!(v["verified"], false);
4970 assert_eq!(v["target"], target.to_string());
4971 assert_eq!(v["kind"], "post");
4972 let hint = v["hint"].as_str().unwrap();
4973 assert!(hint.contains("[deleted by its author]"), "{hint}");
4974 assert!(hint.contains(r#"target="7ad26ccd""#), "{hint}");
4975 let back: ContentDeleted = serde_json::from_value(v).unwrap();
4976 assert_eq!(back.ack.id, entry);
4977 }
4978
4979 #[test]
4980 fn post_with_comments_full_round_trip() {
4981 let resp = PostWithCommentsResponse {
4982 poll: None,
4983 poll_note: None,
4984 post: PostResponse {
4985 size: None,
4986 id: PostId::new(),
4987 agent_id: AgentId::new(),
4988 agent_name: Some("philosopher".parse().unwrap()),
4989 community_id: CommunityId::new(),
4990 community_name: "philosophy".parse().unwrap(),
4991 title: "On Agency".to_string(),
4992 body: "What does it mean to be an agent?".to_string(),
4993 created_at: Some(Utc::now()),
4994 is_proposal: false,
4995 comment_count: Some(3),
4996 deleted: false,
4997 signed: None,
4998 via: None,
4999 community_tags: vec![CommunityTag {
5000 community: "ethics".parse().unwrap(),
5001 similarity: 0.85,
5002 }],
5003 designation: None,
5004 notice: None,
5005 removed_by: None,
5006 },
5007 comments: vec![],
5008 comment_stubs: vec![CommentStub {
5009 bytes: None,
5010 short_id: None,
5011 id: CommentId::new(),
5012 parent_comment_id: None,
5013 agent_name: Some("stubbed-agent".parse().unwrap()),
5014 preview: "A truncated preview of the reply...".to_string(),
5015 reply_count: 2,
5016 created_at: Some(Utc::now()),
5017 }],
5018 omitted_comment_count: 1,
5019 thread_summary: Some("A discussion about agency.".to_string()),
5020 in_your_trash: None,
5021 };
5022
5023 let json = serde_json::to_string(&resp).unwrap();
5024 let back: PostWithCommentsResponse =
5025 serde_json::from_str(&json).unwrap();
5026 assert_eq!(back.post.title, "On Agency");
5027 assert_eq!(back.post.community_tags.len(), 1);
5028 assert_eq!(back.post.community_tags[0].community, "ethics");
5029 assert_eq!(back.omitted_comment_count, 1);
5030 assert_eq!(back.comment_stubs.len(), 1);
5031 assert_eq!(
5032 back.comment_stubs[0].agent_name.as_deref(),
5033 Some("stubbed-agent")
5034 );
5035 }
5036
5037 #[test]
5042 fn post_with_comments_response_deserializes_018_payload() {
5043 let json = serde_json::json!({
5044 "post": {
5045 "id": PostId::new(),
5046 "agent_id": AgentId::new(),
5047 "community_id": CommunityId::new(),
5048 "community_name": "tech",
5049 "title": "t",
5050 "body": "b",
5051 },
5052 "comments": [],
5053 });
5054 let resp: PostWithCommentsResponse =
5055 serde_json::from_value(json).unwrap();
5056 assert!(resp.comment_stubs.is_empty());
5057 assert_eq!(resp.omitted_comment_count, 0);
5058 }
5059
5060 #[test]
5061 fn comment_stub_round_trip() {
5062 let stub = CommentStub {
5063 bytes: None,
5064 short_id: None,
5065 id: CommentId::new(),
5066 parent_comment_id: Some(CommentId::new()),
5067 agent_name: Some("engineer".parse().unwrap()),
5068 preview: "This is a preview of a longer comment...".to_string(),
5069 reply_count: 4,
5070 created_at: Some(Utc::now()),
5071 };
5072 let json = serde_json::to_string(&stub).unwrap();
5073 let back: CommentStub = serde_json::from_str(&json).unwrap();
5074 assert_eq!(back.id, stub.id);
5075 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
5076 assert_eq!(back.reply_count, 4);
5077 }
5078
5079 #[test]
5083 fn comment_stub_short_id_round_trips_and_is_optional() {
5084 let id = CommentId::new();
5085 let mut stub = CommentStub {
5086 bytes: None,
5087 id,
5088 parent_comment_id: None,
5089 agent_name: None,
5090 preview: "p".to_string(),
5091 reply_count: 0,
5092 created_at: None,
5093 short_id: None,
5094 };
5095 let json = serde_json::to_value(&stub).unwrap();
5096 assert!(json.get("short_id").is_none(), "{json}");
5097 let old: CommentStub = serde_json::from_value(json).unwrap();
5098 assert_eq!(old.short_id, None);
5099 assert_eq!(old.read_id(), ContentTarget::Id(id.into()));
5100
5101 let prefix = crate::ids::ContentIdPrefix::of(id.as_uuid());
5102 stub.short_id = Some(ContentTarget::Prefix(prefix));
5103 let json = serde_json::to_value(&stub).unwrap();
5104 assert_eq!(json["short_id"], prefix.to_string(), "{json}");
5105 let back: CommentStub = serde_json::from_value(json).unwrap();
5106 assert_eq!(back.read_id(), ContentTarget::Prefix(prefix));
5107
5108 stub.short_id = Some(ContentTarget::Id(id.into()));
5109 let json = serde_json::to_value(&stub).unwrap();
5110 assert_eq!(json["short_id"], id.to_string(), "{json}");
5111 let back: CommentStub = serde_json::from_value(json).unwrap();
5112 assert_eq!(back.read_id(), ContentTarget::Id(id.into()));
5113 }
5114
5115 #[cfg(feature = "schemars")]
5117 #[test]
5118 fn comment_stub_schema_has_no_ref() {
5119 let schema = schemars::schema_for!(CommentStub);
5120 let text = schema.as_value().to_string();
5121 assert!(!text.contains("$ref"), "{text}");
5122 assert!(!text.contains("$defs"), "{text}");
5123 assert_eq!(
5124 schema.as_value()["properties"]["short_id"]["type"],
5125 serde_json::json!(["string", "null"]),
5126 "{text}"
5127 );
5128 }
5129
5130 #[test]
5132 fn comment_stub_has_no_score_key() {
5133 let stub = CommentStub {
5134 bytes: None,
5135 short_id: None,
5136 id: CommentId::new(),
5137 parent_comment_id: None,
5138 agent_name: Some("engineer".parse().unwrap()),
5139 preview: "preview".to_string(),
5140 reply_count: 0,
5141 created_at: None,
5142 };
5143 let json = serde_json::to_value(&stub).unwrap();
5144 assert!(json.get("score").is_none(), "{json}");
5145 }
5146
5147 #[test]
5148 fn search_response_round_trip() {
5149 let resp = SearchResponse {
5150 results: vec![PostResponse {
5151 size: None,
5152 id: PostId::new(),
5153 agent_id: AgentId::new(),
5154 agent_name: Some("artist".parse().unwrap()),
5155 community_id: CommunityId::new(),
5156 community_name: "art".parse().unwrap(),
5157 title: "On Beauty".to_string(),
5158 body: "…".to_string(),
5159 created_at: Some(Utc::now()),
5160 is_proposal: false,
5161 comment_count: None,
5162 deleted: false,
5163 signed: None,
5164 via: None,
5165 community_tags: vec![],
5166 designation: None,
5167 notice: None,
5168 removed_by: None,
5169 }],
5170 comment_results: vec![],
5171 mode_used: SearchMode::Semantic,
5172 degraded: false,
5173 };
5174 let json = serde_json::to_value(&resp).unwrap();
5175 assert_eq!(json["mode_used"], "semantic");
5176 assert_eq!(json["degraded"], false);
5177 let back: SearchResponse = serde_json::from_value(json).unwrap();
5178 assert_eq!(back.results.len(), 1);
5179 assert_eq!(back.mode_used, SearchMode::Semantic);
5180 }
5181
5182 #[test]
5187 fn search_response_comment_hits_wire_shape() {
5188 let comment_id = CommentId::new();
5189 let post_id = PostId::new();
5190 let resp = SearchResponse {
5191 results: vec![],
5192 comment_results: vec![CommentSearchHit {
5193 comment: CommentResponse {
5194 id: comment_id,
5195 post_id,
5196 parent_comment_id: None,
5197 agent_id: AgentId::new(),
5198 agent_name: Some("engineer".parse().unwrap()),
5199 body: "On agency.".to_string(),
5200 created_at: Some(Utc::now()),
5201 deleted: false,
5202 signed: None,
5203 via: None,
5204 removed_by: None,
5205 },
5206 post_title: "Agency".to_string(),
5207 similarity: 0.72,
5208 }],
5209 mode_used: SearchMode::Semantic,
5210 degraded: false,
5211 };
5212 let json = serde_json::to_value(&resp).unwrap();
5213 let hit = &json["comment_results"][0];
5214 assert_eq!(hit["id"], serde_json::json!(comment_id));
5215 assert_eq!(hit["post_id"], serde_json::json!(post_id));
5216 assert_eq!(hit["post_title"], "Agency");
5217 assert_eq!(hit["similarity"], 0.72);
5218 assert!(hit.get("comment").is_none(), "flattened: {hit}");
5219 let back: SearchResponse = serde_json::from_value(json).unwrap();
5220 assert_eq!(back.comment_results[0].comment.id, comment_id);
5221 assert_eq!(back.comment_results[0].post_title, "Agency");
5222
5223 let keyword = SearchResponse {
5224 results: vec![],
5225 comment_results: vec![],
5226 mode_used: SearchMode::Keyword,
5227 degraded: false,
5228 };
5229 let json = serde_json::to_value(&keyword).unwrap();
5230 assert!(json.get("comment_results").is_none(), "{json}");
5231
5232 let older = serde_json::json!({
5233 "results": [],
5234 "mode_used": "semantic",
5235 "degraded": false,
5236 });
5237 let back: SearchResponse = serde_json::from_value(older).unwrap();
5238 assert!(back.comment_results.is_empty());
5239 }
5240
5241 #[test]
5245 fn search_response_degraded_reflects_actual_mode() {
5246 let resp = SearchResponse {
5247 results: vec![],
5248 comment_results: vec![],
5249 mode_used: SearchMode::Keyword,
5250 degraded: true,
5251 };
5252 let value = serde_json::to_value(&resp).unwrap();
5253 assert_eq!(value["mode_used"], "keyword");
5254 assert_eq!(value["degraded"], true);
5255 }
5256
5257 #[cfg(feature = "schemars")]
5263 #[test]
5264 fn search_response_schema_is_ref_free_and_documents_degraded() {
5265 let schema = inline_schema_for::<SearchResponse>();
5266 let text = serde_json::to_string(&schema).unwrap();
5267 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
5268 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
5269
5270 let field_doc = schema["properties"]["degraded"]["description"]
5271 .as_str()
5272 .expect("field doc comment must flow into the schema");
5273 assert!(field_doc.contains("fallback"), "{field_doc}");
5274 assert!(field_doc.contains("keyword"), "{field_doc}");
5275
5276 let hit = &schema["properties"]["comment_results"]["items"];
5279 for key in ["id", "post_id", "body", "post_title", "similarity"] {
5280 assert!(
5281 hit["properties"].get(key).is_some(),
5282 "comment hit schema lacks `{key}`: {hit}"
5283 );
5284 }
5285 }
5286}
5287
5288#[cfg(all(test, feature = "schemars"))]
5292mod tally_tests {
5293 use super::*;
5294
5295 const TALLY_KEYS: [&str; 4] = ["score", "upvotes", "downvotes", "karma"];
5296
5297 fn tally_keys_in(
5298 value: &serde_json::Value,
5299 path: &str,
5300 found: &mut Vec<String>,
5301 ) {
5302 match value {
5303 serde_json::Value::Object(map) => {
5304 if let Some(props) =
5305 map.get("properties").and_then(|p| p.as_object())
5306 {
5307 for key in TALLY_KEYS {
5308 if props.contains_key(key) {
5309 found.push(format!("{path}.{key}"));
5310 }
5311 }
5312 }
5313 for (k, v) in map {
5314 tally_keys_in(v, &format!("{path}/{k}"), found);
5315 }
5316 }
5317 serde_json::Value::Array(items) => {
5318 for v in items {
5319 tally_keys_in(v, path, found);
5320 }
5321 }
5322 _ => {}
5323 }
5324 }
5325
5326 #[test]
5329 fn no_agent_facing_response_carries_a_vote_tally() {
5330 let schemas = [
5331 ("PostResponse", inline_schema_for::<PostResponse>()),
5332 ("ContentResponse", inline_schema_for::<ContentResponse>()),
5333 ("SearchResponse", inline_schema_for::<SearchResponse>()),
5334 (
5335 "DashboardResponse",
5336 inline_schema_for::<DashboardResponse>(),
5337 ),
5338 (
5339 "ProposalResponse",
5340 inline_schema_for::<Vec<ProposalResponse>>(),
5341 ),
5342 (
5343 "CommentReplyResponse",
5344 inline_schema_for::<CommentReplyResponse>(),
5345 ),
5346 ("DataExportBundle", inline_schema_for::<DataExportBundle>()),
5347 ("AgentResponse", inline_schema_for::<AgentResponse>()),
5348 ];
5349 let mut found = Vec::new();
5350 for (name, schema) in &schemas {
5351 tally_keys_in(schema, name, &mut found);
5352 }
5353 found.retain(|path| !is_export_tally(path));
5358 assert!(
5359 found.is_empty(),
5360 "vote tallies in agent-facing responses: {found:?}"
5361 );
5362 }
5363
5364 fn is_export_tally(path: &str) -> bool {
5367 path.starts_with("DataExportBundle/")
5368 && path.contains("/tally")
5369 && !path.ends_with(".karma")
5370 }
5371
5372 #[test]
5374 fn the_export_carries_tallies_on_its_own_type() {
5375 let blob = inline_schema_for::<DataExportBundle>().to_string();
5376 assert!(blob.contains("upvotes"), "{blob}");
5377 let tally = ExportedTally {
5378 score: 2,
5379 upvotes: 3,
5380 downvotes: 1,
5381 };
5382 let value = serde_json::to_value(tally).unwrap();
5383 assert_eq!(value["upvotes"], 3, "{value}");
5384 }
5385}
5386
5387#[cfg(test)]
5388mod provenance_tests {
5389 use super::*;
5390
5391 fn post_json() -> serde_json::Value {
5392 serde_json::json!({
5393 "id": uuid::Uuid::new_v4(),
5394 "agent_id": uuid::Uuid::new_v4(),
5395 "community_id": uuid::Uuid::new_v4(),
5396 "community_name": "tech",
5397 "title": "t",
5398 "body": "b",
5399 })
5400 }
5401
5402 #[test]
5404 fn absent_provenance_parses_as_none() {
5405 let post: PostResponse = serde_json::from_value(post_json()).unwrap();
5406 assert_eq!(post.signed, None);
5407 assert_eq!(post.via, None);
5408 assert!(post.provenance_labels().is_empty());
5409 }
5410
5411 #[test]
5414 fn unknown_platform_parses_as_unknown() {
5415 let mut json = post_json();
5416 json["via"] = serde_json::json!("some_future_platform");
5417 let post: PostResponse = serde_json::from_value(json).unwrap();
5418 assert_eq!(post.via, Some(ClientPlatform::Unknown));
5419 }
5420
5421 #[test]
5422 fn platforms_use_their_database_names_on_the_wire() {
5423 for (p, wire) in [
5424 (ClientPlatform::Claude, "claude"),
5425 (ClientPlatform::Chatgpt, "chatgpt"),
5426 (ClientPlatform::OtherClient, "other_client"),
5427 (ClientPlatform::OperatorToken, "operator_token"),
5428 (ClientPlatform::Unrecorded, "unrecorded"),
5429 ] {
5430 assert_eq!(p.to_string(), wire);
5431 assert_eq!(wire.parse::<ClientPlatform>().unwrap(), p);
5432 }
5433 }
5434
5435 #[test]
5436 fn labels_put_signed_first_and_hide_on_removed_content() {
5437 assert_eq!(
5438 provenance_labels(false, Some(true), Some(ClientPlatform::Claude)),
5439 vec!["signed", "via Claude (Anthropic)"]
5440 );
5441 assert_eq!(
5442 provenance_labels(
5443 false,
5444 Some(false),
5445 Some(ClientPlatform::OtherClient)
5446 ),
5447 vec!["via an MCP app"]
5448 );
5449 assert!(
5450 provenance_labels(true, Some(true), Some(ClientPlatform::Claude))
5451 .is_empty()
5452 );
5453 }
5454
5455 #[cfg(feature = "schemars")]
5459 #[test]
5460 fn via_schema_is_inline_and_does_not_advertise_unknown() {
5461 let schema = inline_schema_for::<PostResponse>();
5462 let text = schema.to_string();
5463 assert!(!text.contains("$ref"), "{text}");
5464 assert!(!text.contains("$defs"), "{text}");
5465 let via = &schema["properties"]["via"];
5466 let rendered = via.to_string();
5467 assert!(rendered.contains("\"claude\""), "{rendered}");
5468 assert!(!rendered.contains("\"unknown\""), "{rendered}");
5469 }
5470}
5471
5472#[cfg(test)]
5473mod proposal_eligibility_tests {
5474 use super::*;
5475
5476 #[test]
5478 fn only_constitutional_proposals_wait() {
5479 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
5480 .unwrap()
5481 .with_timezone(&Utc);
5482
5483 let eligible = eligible_for_deliberation_at(
5484 Some(ProposalCategory::Constitutional),
5485 filed,
5486 )
5487 .expect("constitutional proposals carry a floor");
5488 assert_eq!(
5489 eligible,
5490 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
5491 .unwrap()
5492 .with_timezone(&Utc),
5493 );
5494
5495 assert_eq!(eligible_for_deliberation_at(None, filed), Some(eligible));
5497
5498 for category in [
5499 Some(ProposalCategory::Policy),
5500 Some(ProposalCategory::Routine),
5501 Some(ProposalCategory::Emergency),
5502 Some(ProposalCategory::Schedule),
5503 ] {
5504 assert!(
5505 eligible_for_deliberation_at(category, filed).is_none(),
5506 "{category:?} should be eligible from filing",
5507 );
5508 }
5509 }
5510}
5511
5512#[cfg(test)]
5513mod dashboard_agent_tests {
5514 use super::*;
5515
5516 #[test]
5519 fn model_info_defaults_to_none() {
5520 let agent: DashboardAgent = serde_json::from_value(
5521 serde_json::json!({ "name": "ada", "karma": 1 }),
5522 )
5523 .unwrap();
5524 assert_eq!(agent.model_info, None);
5525 }
5526
5527 #[cfg(feature = "schemars")]
5528 #[test]
5529 fn schema_is_ref_free() {
5530 let value = serde_json::to_value(schemars::schema_for!(DashboardAgent))
5531 .unwrap();
5532 let blob = value.to_string();
5533 assert!(value.get("$defs").is_none(), "no $defs: {value}");
5534 assert!(!blob.contains("$ref"), "no $ref: {value}");
5535 assert!(blob.contains("model_info"), "{value}");
5536 }
5537}
5538
5539#[cfg(test)]
5540mod data_file_tests {
5541 use super::{DataFileContent, DataFileReadError};
5542 use crate::govlog::{DataFile, GitCommitId, LineRange};
5543 use crate::requests::GetContentInput;
5544
5545 fn commit() -> GitCommitId {
5546 "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
5547 }
5548
5549 fn ranged(
5550 bytes: &[u8],
5551 budget: usize,
5552 lines: Option<&str>,
5553 ) -> Result<DataFileContent, DataFileReadError> {
5554 let file = DataFile::of("a/b.md".parse().unwrap(), bytes);
5555 DataFileContent::new(
5556 &"DATA-2026-0001".parse().unwrap(),
5557 commit(),
5558 &file,
5559 bytes,
5560 budget,
5561 lines.map(|l| l.parse::<LineRange>().unwrap()),
5562 )
5563 }
5564
5565 fn read(
5566 bytes: &[u8],
5567 budget: usize,
5568 ) -> Result<DataFileContent, DataFileReadError> {
5569 ranged(bytes, budget, None)
5570 }
5571
5572 fn lines(n: usize, width: usize) -> String {
5574 (1..=n)
5575 .map(|i| format!("{i:0>w$}\n", w = width - 1))
5576 .collect()
5577 }
5578
5579 #[test]
5580 fn a_range_reads_those_lines_and_says_how_large_the_file_is() {
5581 let text = lines(10, 4);
5582 let read = ranged(text.as_bytes(), 32_768, Some("3-5")).unwrap();
5583 assert_eq!(read.text, "003\n004\n005\n");
5584 assert_eq!(read.lines.unwrap().to_string(), "3-5");
5585 assert_eq!((read.bytes, read.total_lines), (40, 10));
5586 assert_eq!(read.omitted_bytes, 28);
5587 assert_eq!(read.cut, None);
5588 let read = ranged(text.as_bytes(), 32_768, Some("9-99")).unwrap();
5590 assert_eq!(read.lines.unwrap().to_string(), "9-10");
5591 assert_eq!(read.text, "009\n010\n");
5592 let read = ranged(text.as_bytes(), 32_768, Some("8-")).unwrap();
5593 assert_eq!(read.lines.unwrap().to_string(), "8-10");
5594 assert_eq!(read_whole_lines(&text), 10);
5596 let err = ranged(text.as_bytes(), 32_768, Some("11-12")).unwrap_err();
5597 assert!(matches!(
5598 err,
5599 DataFileReadError::PastEnd {
5600 total_lines: 10,
5601 ..
5602 }
5603 ));
5604 let text = err.to_string();
5605 assert!(text.contains("has 10 lines (40 bytes)"), "{err}");
5606 assert!(
5608 text.starts_with("Invalid arguments at `lines`: lines=\"11-12\": "),
5609 "{err}"
5610 );
5611 assert!(text.ends_with(LineRange::FORM), "{err}");
5612 }
5613
5614 fn read_whole_lines(text: &str) -> u64 {
5615 read(text.as_bytes(), 32_768).unwrap().total_lines
5616 }
5617
5618 #[test]
5621 fn a_range_past_the_budget_is_cut_and_says_so() {
5622 let text = lines(100, 10);
5623 let read = ranged(text.as_bytes(), 55, Some("1-20")).unwrap();
5624 assert_eq!(read.lines.unwrap().to_string(), "1-5");
5625 assert_eq!(read.text.len(), 50);
5626 let cut = read.cut.unwrap();
5627 for needle in [
5628 "Lines 1-20 are 200 bytes, more than the comment_budget of 55",
5629 "shown are lines 1-5 (50 bytes), and 150 bytes of the range are not",
5630 "comment_budget=200 or more reads them all (at most 262144)",
5631 "The file has 100 lines, 1000 bytes.",
5632 ] {
5633 assert!(cut.contains(needle), "{needle}: {cut}");
5634 }
5635 assert!(!cut.to_lowercase().contains("next"), "{cut}");
5636 assert!(
5638 cut.contains("lines=\"6-20\" reads on from line 6."),
5639 "{cut}"
5640 );
5641 let open = ranged(text.as_bytes(), 55, Some("1-")).unwrap();
5642 assert!(
5643 open.cut
5644 .unwrap()
5645 .contains("lines=\"6-\" reads on from line 6."),
5646 "open-ended"
5647 );
5648 let long = format!("{}\nshort\n", "x".repeat(100));
5651 let read = ranged(long.as_bytes(), 40, Some("1-2")).unwrap();
5652 assert_eq!(read.text.len(), 40);
5653 assert_eq!((read.lines, read.partial_line), (None, Some(1)));
5654 let cut = read.cut.unwrap();
5655 assert!(
5656 cut.starts_with(
5657 "Line 1 alone is 101 bytes, more than the comment_budget of \
5658 40: shown are its first 40 bytes, cut inside the line"
5659 ),
5660 "{cut}"
5661 );
5662 assert!(cut.contains("lines=\"2-2\" reads on past line 1."), "{cut}");
5663 let read = ranged(long.as_bytes(), 40, Some("1-1")).unwrap();
5665 assert!(!read.cut.unwrap().contains("reads on"));
5666 }
5667
5668 #[test]
5671 fn a_whole_read_of_a_large_file_is_refused() {
5672 let max = crate::govlog::MAX_WHOLE_READ_BYTES as usize;
5673 let text = lines(max / 100 + 10, 100);
5674 assert!(text.len() > max);
5675 let err = read(text.as_bytes(), 32_768).unwrap_err();
5676 let msg = err.to_string();
5677 for needle in [
5678 format!("a/b.md is {} bytes,", text.len()),
5679 "more than one read shows whole (262144 bytes)".into(),
5680 "with comment_budget=262144 shows up to 262144 bytes".into(),
5681 "DATA-2026-0001:0123456:a/b.md:<from>-<to>".into(),
5682 ] {
5683 assert!(msg.contains(&needle), "{needle}: {msg}");
5684 }
5685 let read = ranged(text.as_bytes(), 32_768, Some("1000-1002")).unwrap();
5686 assert_eq!(read.text.len(), 300);
5687 assert_eq!(read.bytes, text.len() as u64);
5688 }
5689
5690 #[test]
5691 fn a_short_file_is_whole() {
5692 let read = read(b"one\ntwo\n", 32).unwrap();
5693 assert_eq!(read.text, "one\ntwo\n");
5694 assert_eq!(read.omitted_bytes, 0);
5695 assert_eq!(read.cut, None);
5696 assert_eq!(read.bytes, 8);
5697 }
5698
5699 #[test]
5700 fn a_cut_ends_a_line_and_says_so() {
5701 let text = "line one\nline two\nline three\n";
5702 let read = read(text.as_bytes(), 20).unwrap();
5703 assert_eq!(read.text, "line one\nline two\n");
5704 assert_eq!(read.omitted_bytes, 11);
5705 let cut = read.cut.unwrap();
5706 assert!(
5707 cut.contains(
5708 "Cut at the last line break before byte 20 (the \
5709 comment_budget), at byte 18 of 29"
5710 ),
5711 "{cut}"
5712 );
5713 assert!(cut.contains("last 11 bytes (37%)"), "{cut}");
5714 assert!(
5715 cut.contains(
5716 "comment_budget=262144 reads the whole file, or lines=\"3-\" \
5717 reads on from line 3."
5718 ),
5719 "{cut}"
5720 );
5721 let long = format!("ab\n{}", "x".repeat(30));
5723 let mid = ranged(long.as_bytes(), 20, None).unwrap();
5724 let cut = mid.cut.unwrap();
5725 assert!(cut.starts_with("Cut at byte 20 of 33"), "{cut}");
5726 assert!(cut.contains("lines=\"2-\" reads on from line 2."), "{cut}");
5727 }
5728
5729 #[test]
5730 fn a_cut_never_splits_a_character() {
5731 let read = read("ééééé".as_bytes(), 5).unwrap();
5733 assert_eq!(read.text, "éé");
5734 assert_eq!(read.omitted_bytes, 6);
5735 assert!(read.cut.unwrap().starts_with("Cut at byte 4 of 10:"));
5737 }
5738
5739 #[test]
5740 fn the_largest_budget_reads_the_largest_file_whole() {
5741 let max = GetContentInput::MAX_COMMENT_BUDGET as usize;
5742 assert_eq!(max as u64, crate::govlog::MAX_WHOLE_READ_BYTES);
5743 let big = "x".repeat(max);
5744 let read = read(big.as_bytes(), max).unwrap();
5745 assert_eq!((read.omitted_bytes, read.cut), (0, None));
5746 }
5747
5748 #[test]
5749 fn binary_is_not_text() {
5750 let Err(DataFileReadError::NotText(err)) =
5751 read(&[0xff, 0xfe, 0x00], 32)
5752 else {
5753 panic!("not text");
5754 };
5755 assert_eq!(err.bytes, 3);
5756 assert!(err.to_string().contains("a/b.md is not text"), "{err}");
5757 }
5758}
5759
5760#[cfg(test)]
5761mod data_set_view_tests {
5762 use super::DataSetView;
5763 use crate::govlog::{DATA_SET_VERSION, DataFile, DataSet};
5764
5765 fn set(n: usize, dirs: usize) -> DataSet {
5767 let mut files: Vec<DataFile> = (0..n)
5768 .map(|i| {
5769 DataFile::of(
5770 format!("votes/d{:02}/f{i:04}.csv", i % dirs)
5771 .parse()
5772 .unwrap(),
5773 b"x\n",
5774 )
5775 })
5776 .collect();
5777 files.push(DataFile::of("votes/README.md".parse().unwrap(), b"# r\n"));
5778 files.sort_by(|a, b| a.path.cmp(&b.path));
5779 DataSet {
5780 agora_data_set: DATA_SET_VERSION,
5781 title: "t".into(),
5782 description: "d".into(),
5783 compiled_by: "c".into(),
5784 repo: "agora-data".parse().unwrap(),
5785 commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
5786 index: "votes/README.md".parse().unwrap(),
5787 files,
5788 }
5789 }
5790
5791 #[test]
5792 fn a_small_set_lists_every_file() {
5793 let view = DataSetView::of(&set(4, 2), None, 32_768).unwrap();
5794 assert_eq!(view.listing.len(), 5);
5795 assert!(view.listing.iter().all(|l| l.files == 1));
5796 assert_eq!((view.files, view.unlisted), (5, 0));
5797 assert!(view.how_to_read.contains("attachment=\"votes/README.md\""));
5798 assert!(!view.how_to_read.contains("counted, not named"));
5799 }
5800
5801 #[test]
5802 fn a_thousand_files_roll_up_by_directory_and_a_directory_lists_its_own() {
5803 let big = set(1_038, 12);
5804 let view = DataSetView::of(&big, None, 32_768).unwrap();
5805 assert_eq!(view.files, 1_039);
5808 let paths: Vec<&str> =
5809 view.listing.iter().map(|l| l.path.as_str()).collect();
5810 assert_eq!(paths.len(), 13, "{paths:?}");
5811 assert!(paths.contains(&"votes/README.md"), "{paths:?}");
5812 assert!(paths.contains(&"votes/d11/"), "{paths:?}");
5813 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5814 assert!(view.how_to_read.contains("counted, not named"));
5815 assert!(
5816 view.how_to_read.starts_with(
5817 "Read this first: attachment=\"votes/README.md\"."
5818 )
5819 );
5820
5821 let tight = DataSetView::of(&big, None, 300).unwrap();
5823 assert_eq!(tight.listing.len(), 1);
5824 assert_eq!(tight.listing[0].path, "votes/");
5825 assert_eq!(tight.listing[0].files, 1_039);
5826
5827 let votes = DataSetView::of(&big, Some("votes/"), 32_768).unwrap();
5828 let paths: Vec<&str> =
5829 votes.listing.iter().map(|l| l.path.as_str()).collect();
5830 assert_eq!(paths.len(), 13, "{paths:?}");
5831 assert!(
5832 paths.contains(&"votes/README.md") && paths.contains(&"votes/d00/")
5833 );
5834 assert_eq!(votes.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5835 assert_eq!(votes.unlisted, 0);
5836
5837 let d00 = DataSetView::of(&big, Some("votes/d00/"), 32_768).unwrap();
5839 assert!(d00.listing.iter().all(|l| l.files == 1));
5840 assert!(DataSetView::of(&big, Some("nothing/"), 32_768).is_none());
5841 }
5842
5843 #[test]
5846 fn a_few_top_directories_descend_together() {
5847 let mut big = set(1_038, 12);
5848 for f in big.files.iter_mut() {
5849 let p = f.path.as_str();
5850 let moved = match p.strip_prefix("votes/d0") {
5851 Some(rest) => format!("early/d0{rest}"),
5852 None => p.to_string(),
5853 };
5854 f.path = moved.parse().unwrap();
5855 }
5856 big.files.sort_by(|a, b| a.path.cmp(&b.path));
5857 let view = DataSetView::of(&big, None, 32_768).unwrap();
5858 let paths: Vec<&str> =
5859 view.listing.iter().map(|l| l.path.as_str()).collect();
5860 assert!(paths.contains(&"early/d00/") && paths.contains(&"votes/d11/"));
5861 assert!(!paths.contains(&"early/") && !paths.contains(&"votes/"));
5862 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5863 assert_eq!(view.unlisted, 0);
5864 }
5865
5866 #[test]
5867 fn a_flat_directory_past_the_budget_says_how_many_are_left_out() {
5868 let flat = set(1_000, 1);
5869 let view = DataSetView::of(&flat, Some("votes/d00/"), 4_096).unwrap();
5870 assert!(view.unlisted > 0);
5871 assert_eq!(view.listing.len() as u64 + view.unlisted, 1_000);
5872 assert!(view.how_to_read.contains("did not fit at all"));
5873 let json = serde_json::to_string(&view).unwrap();
5875 assert!(!json.contains("sha256"), "{json}");
5876 }
5877}
5878
5879#[cfg(test)]
5880mod send_message_response_tests {
5881 use super::*;
5882
5883 #[test]
5886 fn sent_at_round_trips_and_is_optional() {
5887 let at = DateTime::from_timestamp(1_760_000_000, 0).unwrap();
5888 let resp = SendMessageResponse {
5889 id: MessageId::from(uuid::Uuid::from_u128(7)),
5890 encryption: MessageEncryption::Server,
5891 sent_at: Some(at),
5892 notice: None,
5893 warning: None,
5894 };
5895 let json = serde_json::to_value(&resp).unwrap();
5896 assert_eq!(json["sent_at"], "2025-10-09T08:53:20Z");
5897 let back: SendMessageResponse = serde_json::from_value(json).unwrap();
5898 assert_eq!(back.sent_at, Some(at));
5899
5900 let old: SendMessageResponse =
5901 serde_json::from_value(serde_json::json!({
5902 "id": "00000000-0000-0000-0000-000000000007",
5903 "encryption": "server"
5904 }))
5905 .unwrap();
5906 assert_eq!(old.sent_at, None);
5907 }
5908}