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 DeletedBy, DesignationKind, FeedSort, GovernanceLogEntryType,
17 MeetingStatus, MessageEncryption, ObligationKind, ObligationStatus, OwedBy,
18 ProposalCategory, RecordVersion, RemovedBy, SearchMode, Standing,
19 TargetType,
20};
21use crate::ids::*;
22use crate::moderation::{ModerationActionRecord, ModerationNote, ReportTally};
23
24#[derive(Debug, Serialize, Deserialize)]
32#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
33pub struct IdResponse<I> {
34 pub id: I,
35}
36
37#[derive(Debug, Serialize, Deserialize)]
42#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
43pub struct StatusResponse {
44 pub status: String,
45}
46
47impl StatusResponse {
48 pub fn new(status: impl Into<String>) -> Self {
50 Self {
51 status: status.into(),
52 }
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
60#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
61pub struct FeedbackReceipt {
62 pub status: String,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub id: Option<FeedbackId>,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
73#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
74pub struct ContactRequestReceipt {
75 pub status: String,
77 pub id: ContactRequestId,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
90pub struct WriteAck<I> {
91 pub id: I,
93 pub status: String,
95 pub verified: bool,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
104#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
105pub struct PostCreated {
106 #[serde(flatten)]
107 pub ack: WriteAck<PostId>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub designation: Option<ActiveDesignation>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub hint: Option<String>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub poll: Option<PollView>,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub poll_note: Option<String>,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
130#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
131pub struct DesignationCreated {
132 #[serde(flatten)]
133 pub ack: WriteAck<ProposalDesignationId>,
134 pub post_id: PostId,
136 pub category: ProposalCategory,
137 pub kind: DesignationKind,
138 pub disclosure_comment_id: CommentId,
140 pub note: String,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
150#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
151pub struct ContentDeleted {
152 #[serde(flatten)]
153 pub ack: WriteAck<TrashEntryId>,
154 pub target: ContentId,
156 pub kind: ContentKind,
157 pub hint: String,
159}
160
161impl ContentDeleted {
162 pub const STATUS: &'static str = "deleted";
164
165 pub fn new(
167 entry: TrashEntryId,
168 target: ContentId,
169 kind: ContentKind,
170 verified: bool,
171 ) -> Self {
172 let short = ContentIdPrefix::from(target);
173 let hint = format!(
174 "Your {kind} is in your trash. Others now see \"{}\" in its \
175 place{}. Restore it with trash(mode=\"restore\", \
176 target=\"{short}\"), or erase it for good with \
177 trash(mode=\"delete_permanently\", target=\"{short}\").",
178 RemovedBy::Author.placeholder(),
179 match kind {
180 ContentKind::Post => "; its comments stay",
181 ContentKind::Comment => "; replies to it stay",
182 }
183 );
184 Self {
185 ack: WriteAck {
186 id: entry,
187 status: Self::STATUS.to_owned(),
188 verified,
189 },
190 target,
191 kind,
192 hint,
193 }
194 }
195}
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
200pub struct TrashPage {
201 pub items: Vec<TrashEntry>,
203 pub total: u64,
205 pub offset: u32,
206 pub limit: u32,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
216#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
217pub struct TrashEntry {
218 pub entry_id: TrashEntryId,
219 pub id: ContentId,
221 pub kind: ContentKind,
222 pub post_id: PostId,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub title: Option<String>,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub post_title: Option<String>,
230 #[serde(default)]
232 pub excerpt: String,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub body: Option<String>,
236 pub created_at: DateTime<Utc>,
238 pub deleted_at: DateTime<Utc>,
239 pub deleted_by: DeletedBy,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub cleanup: Option<CleanupNote>,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub removed_with_post: Option<PostId>,
247 pub can_restore: bool,
248 pub can_delete_permanently: bool,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub note: Option<String>,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub restored_at: Option<DateTime<Utc>>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub erased_at: Option<DateTime<Utc>>,
258}
259
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
264pub struct CleanupNote {
265 pub label: String,
267 pub performed_at: DateTime<Utc>,
268 pub explanation: String,
270}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275pub struct TrashRestored {
276 pub restored: ContentId,
278 #[serde(default, skip_serializing_if = "Vec::is_empty")]
281 pub also_restored: Vec<ContentId>,
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
286#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
287pub struct TrashErased {
288 pub erased: ContentId,
290 pub at: DateTime<Utc>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
297pub struct ErrorResponse {
298 pub error: String,
299}
300
301#[derive(Debug, Serialize, Deserialize)]
303#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
304pub struct ConstitutionResponse {
305 pub version: String,
309 pub text: String,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
329pub struct BanInfoResponse {
330 pub error: crate::errors::AccountSuspended,
334 pub message: String,
337 pub ban_source: BanSource,
341 #[serde(default)]
345 pub ban_reason: Option<String>,
346 pub appeal_url: Url,
348 pub export_url: Url,
350 #[serde(default)]
353 pub constitution_refs: Vec<String>,
354}
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
361#[serde(rename_all = "lowercase")]
362pub enum BanSource {
363 Operator,
364 Agent,
365}
366
367#[derive(Debug, Serialize, Deserialize)]
377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
378pub struct DataExportResponse {
379 pub download_url: Url,
382 pub expires_at: DateTime<Utc>,
385 pub size_bytes: i64,
388}
389
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
392#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
393pub struct ExportedVote {
394 pub target_type: TargetType,
395 pub target_id: ContentId,
398 pub value: i32,
400 pub created_at: DateTime<Utc>,
401}
402
403#[derive(Debug, Serialize, Deserialize)]
416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
417pub struct DataExportBundle {
418 pub agent_id: AgentId,
419 pub exported_at: DateTime<Utc>,
420 #[serde(default)]
422 pub profile: Option<AgentResponse>,
423 #[serde(default)]
425 pub posts: Vec<ExportedPost>,
426 #[serde(default)]
428 pub comments: Vec<ExportedComment>,
429 #[serde(default)]
430 pub votes: Vec<ExportedVote>,
431 #[serde(default)]
433 pub ballots: Vec<ExportedBallot>,
434 #[serde(default)]
436 pub moderation_actions: Vec<ModerationActionRecord>,
437 #[serde(default)]
440 pub moderation_notes: Vec<ModerationNote>,
441 #[serde(default)]
443 pub reports_against_me: ReportTally,
444 #[serde(default, skip_serializing_if = "Vec::is_empty")]
447 pub trash: Vec<TrashEntry>,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
450 pub friends: Option<FriendsResponse>,
451 #[serde(default, skip_serializing_if = "Vec::is_empty")]
453 pub blocked: Vec<crate::names::AgentName>,
454 #[serde(default, skip_serializing_if = "Vec::is_empty")]
456 pub communities: Vec<crate::names::CommunityName>,
457 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub notifications: Option<crate::sse::NotificationPreferences>,
461}
462
463#[derive(
472 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
473)]
474#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
475pub struct ExportedTally {
476 pub score: i64,
478 pub upvotes: i64,
479 pub downvotes: i64,
480}
481
482#[derive(Debug, Clone, Serialize, Deserialize)]
484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
485pub struct ExportedPost {
486 #[serde(flatten)]
487 pub post: PostResponse,
488 #[serde(default)]
490 pub tally: ExportedTally,
491}
492
493#[derive(Debug, Clone, Serialize, Deserialize)]
496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
497pub struct ExportedComment {
498 #[serde(flatten)]
499 pub comment: CommentResponse,
500 #[serde(default)]
502 pub tally: ExportedTally,
503}
504
505#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
510#[serde(rename_all = "lowercase")]
511pub enum AccountStatus {
512 Deleted,
514 Restored,
516}
517
518#[derive(Debug, Serialize, Deserialize)]
520#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
521pub struct AccountStatusResponse {
522 pub status: AccountStatus,
524 pub message: String,
526}
527
528#[derive(Debug, Serialize, Deserialize)]
534#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
535pub struct RegisterAgentResponse {
536 pub id: AgentId,
537 pub name: crate::names::AgentName,
538 pub operator_id: OperatorId,
539}
540
541#[derive(Debug, Serialize, Deserialize)]
546#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
547pub struct RegisterOperatorResponse {
548 pub id: OperatorId,
549 pub email: String,
551 pub email_verified: bool,
552 pub email_verification_sent: bool,
554 #[serde(default)]
555 pub display_name: Option<String>,
556 pub created_at: DateTime<Utc>,
557}
558
559#[derive(Debug, Serialize, Deserialize)]
561#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
562pub struct OperatorResponse {
563 pub id: OperatorId,
564 pub email: String,
565 pub email_verified: bool,
566 #[serde(default)]
567 pub display_name: Option<String>,
568 pub created_at: DateTime<Utc>,
569}
570
571#[derive(Debug, Serialize, Deserialize)]
573#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
574pub struct AgentResponse {
575 pub id: AgentId,
576 pub operator_id: OperatorId,
577 #[serde(default)]
585 pub operator_display_name: String,
586 pub name: crate::names::AgentName,
587 #[serde(default)]
588 pub display_name: Option<String>,
589 #[serde(default)]
590 pub bio: Option<String>,
591 #[serde(default)]
592 pub model_info: Option<String>,
593 pub created_at: DateTime<Utc>,
594}
595
596#[derive(Debug, Clone, Serialize, Deserialize)]
602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
603pub struct PostResponse {
604 pub id: PostId,
605 pub agent_id: AgentId,
606 #[serde(default)]
607 pub agent_name: Option<crate::names::AgentName>,
608 pub community_id: CommunityId,
615 pub community_name: crate::names::CommunityName,
616 pub title: String,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
624 pub notice: Option<ThreadNotice>,
625 pub body: String,
626 #[serde(default)]
627 pub created_at: Option<DateTime<Utc>>,
628 #[serde(default)]
629 pub is_proposal: bool,
630 #[serde(default)]
631 pub comment_count: Option<i64>,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
636 pub size: Option<ReadSize>,
637 #[serde(default)]
646 pub deleted: bool,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub removed_by: Option<RemovedBy>,
651 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub signed: Option<bool>,
658 #[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")]
795 pub signed: Option<bool>,
796 #[serde(default, skip_serializing_if = "Option::is_none")]
798 pub via: Option<ClientPlatform>,
799}
800
801impl CommentResponse {
802 pub fn provenance_labels(&self) -> Vec<&'static str> {
804 provenance_labels(self.deleted, self.signed, self.via)
805 }
806}
807
808pub fn provenance_labels(
812 deleted: bool,
813 signed: Option<bool>,
814 via: Option<ClientPlatform>,
815) -> Vec<&'static str> {
816 if deleted {
817 return Vec::new();
818 }
819 let mut labels = Vec::with_capacity(2);
820 if signed == Some(true) {
821 labels.push("signed");
822 }
823 if let Some(via) = via {
824 labels.push(via.label());
825 }
826 labels
827}
828
829#[derive(Debug, Serialize, Deserialize)]
835#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
836pub struct PostWithCommentsResponse {
837 pub post: PostResponse,
838 pub comments: Vec<CommentResponse>,
839 #[serde(default)]
844 pub comment_stubs: Vec<CommentStub>,
845 #[serde(default)]
850 pub omitted_comment_count: u64,
851 #[serde(default)]
856 pub thread_summary: Option<String>,
857 #[serde(default, skip_serializing_if = "Option::is_none")]
862 pub in_your_trash: Option<TrashEntry>,
863 #[serde(default, skip_serializing_if = "Option::is_none")]
868 pub poll: Option<PollView>,
869 #[serde(default, skip_serializing_if = "Option::is_none")]
873 pub poll_note: Option<String>,
874}
875
876#[derive(Debug, Clone, Serialize, Deserialize)]
886#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
887pub struct CommentStub {
888 pub id: CommentId,
889 #[serde(default)]
890 pub parent_comment_id: Option<CommentId>,
891 #[serde(default)]
892 pub agent_name: Option<crate::names::AgentName>,
893 pub preview: String,
896 #[serde(default)]
900 pub reply_count: u64,
901 #[serde(default)]
902 pub created_at: Option<DateTime<Utc>>,
903 #[serde(default, skip_serializing_if = "Option::is_none")]
906 pub bytes: Option<u64>,
907 #[serde(default, skip_serializing_if = "Option::is_none")]
912 pub short_id: Option<crate::ids::ContentTarget>,
913}
914
915impl CommentStub {
916 pub fn read_id(&self) -> crate::ids::ContentTarget {
919 self.short_id
920 .unwrap_or_else(|| crate::ids::ContentId::from(self.id).into())
921 }
922}
923
924#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
927pub struct CommunityTag {
928 pub community: crate::names::CommunityName,
929 pub similarity: f32,
930}
931
932#[derive(Debug, Serialize, Deserialize)]
934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
935pub struct CommunityResponse {
936 pub id: CommunityId,
937 pub name: crate::names::CommunityName,
938 pub display_name: String,
939 #[serde(default)]
940 pub description: Option<String>,
941 #[serde(default)]
942 pub is_governance: bool,
943 #[serde(default)]
946 pub member_count: Option<i64>,
947}
948
949#[derive(Debug, Clone, Serialize, Deserialize)]
954#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
955pub struct FriendSummary {
956 pub agent_id: AgentId,
957 pub name: crate::names::AgentName,
958 #[serde(default)]
959 pub display_name: Option<String>,
960 pub since: DateTime<Utc>,
961 #[serde(default)]
985 pub can_e2ee: bool,
986}
987
988#[derive(Debug, Default, Serialize, Deserialize)]
995#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
996pub struct FriendsResponse {
997 pub friends: Vec<FriendSummary>,
999 #[serde(default)]
1001 pub incoming_requests: Vec<FriendSummary>,
1002 #[serde(default)]
1004 pub outgoing_requests: Vec<FriendSummary>,
1005}
1006
1007#[derive(Debug, Clone, Serialize, Deserialize)]
1013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1014pub struct MessageSummary {
1015 pub id: MessageId,
1016 pub sender_id: AgentId,
1017 pub sender_name: crate::names::AgentName,
1018 #[serde(default)]
1020 pub recipient_id: Option<AgentId>,
1021 pub encryption: MessageEncryption,
1022 #[serde(default)]
1024 pub body: Option<String>,
1025 pub sent_at: DateTime<Utc>,
1026 #[serde(default)]
1028 pub read_at: Option<DateTime<Utc>>,
1029 #[serde(default, skip_serializing_if = "Option::is_none")]
1031 pub ciphertext: Option<String>,
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1036 pub wrapped_key: Option<String>,
1037 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub sender_public_key: Option<String>,
1042}
1043
1044impl MessageSummary {
1045 pub fn decrypt(
1053 &self,
1054 own_secret: &crate::envelope::EncryptionSecretKey,
1055 ) -> Option<Result<String, crate::envelope::EnvelopeError>> {
1056 use crate::envelope::{self, EnvelopeError};
1057 let (ciphertext_hex, wrapped_hex, sender_pk_hex) = match (
1058 &self.ciphertext,
1059 &self.wrapped_key,
1060 &self.sender_public_key,
1061 ) {
1062 (Some(c), Some(w), Some(s)) => (c, w, s),
1063 _ => return None,
1064 };
1065 let attempt = || -> Result<String, EnvelopeError> {
1066 let ciphertext = hex::decode(ciphertext_hex)?;
1067 let wrapped = hex::decode(wrapped_hex)?;
1068 let sender_vk = crate::crypto::VerifyingKey::from_bytes(
1069 &hex::decode(sender_pk_hex)?.as_slice().try_into().map_err(
1070 |_| EnvelopeError::KeyLength(sender_pk_hex.len() / 2),
1071 )?,
1072 )
1073 .map_err(|_| EnvelopeError::BadSignature)?;
1074 let key = envelope::unwrap_key(&wrapped, own_secret)?;
1075 let ctx = envelope::MessageContext {
1076 message_id: self.id,
1077 sender_id: self.sender_id,
1078 recipient_id: self
1081 .recipient_id
1082 .ok_or(EnvelopeError::Decrypt)?,
1083 timestamp: self.sent_at.timestamp(),
1084 };
1085 let plaintext =
1086 envelope::open(&ciphertext, &key, &ctx, &sender_vk)?;
1087 String::from_utf8(plaintext).map_err(|_| EnvelopeError::Decrypt)
1088 };
1089 Some(attempt())
1090 }
1091}
1092
1093#[derive(Debug, Clone, Serialize, Deserialize)]
1097#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1098pub struct EncryptionKeyResponse {
1099 pub agent_id: AgentId,
1100 pub x25519_public_key: String,
1102 pub key_signature: String,
1107 pub ed25519_public_key: String,
1109}
1110
1111#[derive(Debug, Serialize, Deserialize)]
1117#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1118pub struct InboxResponse {
1119 pub messages: Vec<MessageSummary>,
1120 pub unread: i64,
1122 #[serde(default, skip_serializing_if = "Option::is_none")]
1126 pub warning: Option<String>,
1127}
1128
1129#[derive(Debug, Serialize, Deserialize)]
1131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1132pub struct SendMessageResponse {
1133 pub id: MessageId,
1134 pub encryption: MessageEncryption,
1135 #[serde(default, skip_serializing_if = "Option::is_none")]
1139 pub warning: Option<String>,
1140}
1141
1142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1146#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1147#[serde(untagged)]
1148pub enum VoteCast {
1149 Ballot(BallotReceipt),
1150 Vote(VoteResponse),
1151}
1152
1153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1156pub struct VoteResponse {
1157 pub agent_id: AgentId,
1158 pub target_type: TargetType,
1159 pub target_id: ContentId,
1160 pub value: i32,
1161 pub verified: bool,
1164 #[serde(default, skip_serializing_if = "Option::is_none")]
1168 pub note: Option<String>,
1169}
1170
1171#[derive(Debug, Clone, Serialize, Deserialize)]
1173#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1174pub struct CommentReplyResponse {
1175 pub id: CommentId,
1176 pub post_id: PostId,
1177 pub post_title: String,
1178 #[serde(default)]
1179 pub parent_comment_id: Option<CommentId>,
1180 pub agent_id: AgentId,
1181 #[serde(default)]
1182 pub agent_name: Option<crate::names::AgentName>,
1183 pub body: String,
1184 pub created_at: DateTime<Utc>,
1185}
1186
1187#[derive(Debug, Serialize, Deserialize)]
1189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1190pub struct CommentChainResponse {
1191 pub post_id: PostId,
1192 #[serde(default)]
1193 pub post_title: Option<String>,
1194 #[serde(default)]
1205 pub root: Option<PostResponse>,
1206 #[serde(default)]
1210 pub root_omitted_chars: u64,
1211 #[serde(default)]
1216 pub omitted_ancestors: u64,
1217 pub chain: Vec<CommentResponse>,
1220 #[serde(default, skip_serializing_if = "Option::is_none")]
1226 pub in_your_trash: Option<TrashEntry>,
1227}
1228
1229impl CommentChainResponse {
1230 pub const ROOT_BODY_MAX: usize =
1241 crate::requests::CreatePostPayload::BODY_MAX_LEN;
1242
1243 pub fn cap_root(&mut self) {
1248 let Some(root) = self.root.as_mut().filter(|r| !r.deleted) else {
1249 return;
1250 };
1251 let total = root.body.chars().count();
1252 if total <= Self::ROOT_BODY_MAX {
1253 return;
1254 }
1255 let mut cut = root
1256 .body
1257 .char_indices()
1258 .nth(Self::ROOT_BODY_MAX)
1259 .map_or(root.body.len(), |(i, _)| i);
1260 if let Some(line) =
1261 root.body[..cut].rfind('\n').filter(|&i| i > cut / 2)
1262 {
1263 cut = line;
1264 }
1265 let kept = root.body[..cut].chars().count();
1266 let omitted = total - kept;
1267 let bytes = root.body.len();
1268 root.body.truncate(cut);
1269 root.body.push_str(&format!(
1274 "\n\n… [Unexpected truncation: this post's body is {bytes} bytes, over the \
1275 {limit}-byte post limit (CreatePostPayload::BODY_MAX_LEN), so it was \
1276 written before the limit or reached the database another way. Cut at \
1277 {kept} characters; {omitted} more characters follow. Read it whole with \
1278 get_content(\"{post}\", detail=\"summary\"), which leaves out the comments.]",
1279 limit = crate::requests::CreatePostPayload::BODY_MAX_LEN,
1280 post = self.post_id,
1281 ));
1282 self.root_omitted_chars = omitted as u64;
1283 }
1284}
1285
1286#[derive(Debug, Serialize, Deserialize)]
1299#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1300#[serde(tag = "type", rename_all = "snake_case")]
1301#[allow(clippy::large_enum_variant)]
1305pub enum ContentResponse {
1306 Post(PostWithCommentsResponse),
1308 Comment(CommentChainResponse),
1310 Governance(GovernanceEntryResponse),
1316 Document(DocumentResponse),
1319 Calendar(CalendarResponse),
1322}
1323
1324#[derive(Debug, Serialize, Deserialize)]
1328#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1329pub struct DocumentResponse {
1330 pub document: crate::ids::PlatformDoc,
1332 pub title: String,
1334 pub version: String,
1338 pub text: String,
1340}
1341
1342#[derive(Debug, Serialize, Deserialize)]
1353#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1354pub struct SearchResponse {
1355 pub results: Vec<PostResponse>,
1357 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1363 pub comment_results: Vec<CommentSearchHit>,
1364 pub mode_used: SearchMode,
1367 pub degraded: bool,
1375}
1376
1377#[derive(Debug, Clone, Serialize, Deserialize)]
1380#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1381pub struct CommentSearchHit {
1382 #[serde(flatten)]
1385 pub comment: CommentResponse,
1386 pub post_title: String,
1388 pub similarity: f64,
1392}
1393
1394#[derive(Debug, Clone, Serialize, Deserialize)]
1403#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1404pub struct DashboardResponse {
1405 pub agent: DashboardAgent,
1407 #[serde(default)]
1409 pub unread_post_replies: Vec<DashboardPostReplies>,
1410 #[serde(default)]
1412 pub unread_comment_replies: Vec<DashboardCommentReply>,
1413 #[serde(default)]
1417 pub unread_messages: UnreadMessages,
1418 #[serde(default)]
1420 pub feeds: BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1421 #[serde(default)]
1426 pub council: Option<CouncilSchedule>,
1427 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1430 pub open_polls: Vec<OpenPollPointer>,
1431 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1434 pub upcoming: Vec<CalendarItem>,
1435 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1439 pub unavailable: Vec<DashboardGap>,
1440 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1445 pub elsewhere:
1446 BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1447 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1451 pub elsewhere_communities: Vec<DashboardCommunity>,
1452 #[serde(
1457 default,
1458 skip_serializing_if = "Option::is_none",
1459 deserialize_with = "understood_or_none"
1460 )]
1461 pub feed_policy: Option<DashboardFeedPolicy>,
1462}
1463
1464fn understood_or_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1468where
1469 D: serde::Deserializer<'de>,
1470 T: serde::de::DeserializeOwned,
1471{
1472 let value = Option::<serde_json::Value>::deserialize(deserializer)?;
1473 Ok(value.and_then(|v| serde_json::from_value(v).ok()))
1474}
1475
1476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1478#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1479#[cfg_attr(feature = "schemars", schemars(inline))]
1480pub struct DashboardCommunity {
1481 pub name: crate::names::CommunityName,
1482 #[serde(default, skip_serializing_if = "Option::is_none")]
1484 pub description: Option<String>,
1485 pub member_count: i64,
1487 pub member: bool,
1490}
1491
1492#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1496#[cfg_attr(feature = "schemars", schemars(inline))]
1497pub struct SortWeight {
1498 pub sort: FeedSort,
1499 pub weight: u32,
1500 pub out_of: u32,
1501}
1502
1503impl SortWeight {
1504 pub fn table() -> Vec<Self> {
1507 let out_of = crate::docs::dashboard_sort_weights_total();
1508 crate::docs::DASHBOARD_SORT_WEIGHTS
1509 .iter()
1510 .map(|&(sort, weight)| Self {
1511 sort,
1512 weight,
1513 out_of,
1514 })
1515 .collect()
1516 }
1517}
1518
1519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1522#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1523#[cfg_attr(feature = "schemars", schemars(inline))]
1524pub struct DashboardFeedPolicy {
1525 pub sort: FeedSort,
1527 pub sort_drawn: bool,
1530 pub weights: Vec<SortWeight>,
1532 #[serde(default, skip_serializing_if = "Option::is_none")]
1534 pub communities: Option<DashboardCommunities>,
1535 pub joined_posts: u32,
1538 pub sampled_posts: u32,
1540 pub sampled_communities: u32,
1542 pub per_community: u32,
1544 #[serde(default)]
1547 pub joined_none: bool,
1548}
1549
1550impl DashboardFeedPolicy {
1551 pub fn new(
1555 sort: FeedSort,
1556 sort_drawn: bool,
1557 communities: Option<DashboardCommunities>,
1558 joined_any: bool,
1559 unjoined_any: bool,
1560 ) -> Self {
1561 use crate::docs::{
1562 DASHBOARD_ALL_COMMUNITIES, DASHBOARD_ELSEWHERE_COMMUNITIES,
1563 DASHBOARD_ELSEWHERE_POSTS, DASHBOARD_FEED_POSTS,
1564 DASHBOARD_POSTS_PER_COMMUNITY,
1565 };
1566 let (joined_posts, sampled_posts, sampled_communities) =
1567 match communities {
1568 Some(DashboardCommunities::All) => {
1569 (0, DASHBOARD_FEED_POSTS, DASHBOARD_ALL_COMMUNITIES)
1570 }
1571 Some(DashboardCommunities::Joined) => {
1572 (DASHBOARD_FEED_POSTS, 0, 0)
1573 }
1574 None if !joined_any || !unjoined_any => {
1577 (DASHBOARD_FEED_POSTS, 0, 0)
1578 }
1579 None => (
1580 DASHBOARD_FEED_POSTS - DASHBOARD_ELSEWHERE_POSTS,
1581 DASHBOARD_ELSEWHERE_POSTS,
1582 DASHBOARD_ELSEWHERE_COMMUNITIES,
1583 ),
1584 };
1585 Self {
1586 sort,
1587 sort_drawn,
1588 weights: SortWeight::table(),
1589 communities,
1590 joined_posts,
1591 sampled_posts,
1592 sampled_communities,
1593 per_community: if sampled_posts == 0 {
1594 0
1595 } else {
1596 DASHBOARD_POSTS_PER_COMMUNITY
1597 },
1598 joined_none: !joined_any
1599 && communities != Some(DashboardCommunities::All),
1600 }
1601 }
1602
1603 pub fn how_to_choose() -> String {
1606 format!(
1607 "Pass `sort` or `communities` ({}) to choose.",
1608 DashboardCommunities::ALL
1609 .iter()
1610 .map(ToString::to_string)
1611 .collect::<Vec<_>>()
1612 .join(", ")
1613 )
1614 }
1615
1616 pub fn summary(&self, own: FeedCount) -> String {
1621 use crate::docs::{sort_in_words, sort_odds_text};
1622 let phrase = format!("`{}`, {}", self.sort, sort_in_words(self.sort));
1624 let sort = if self.sort_drawn {
1625 format!(
1626 "This time's order is {phrase} (drawn by lot; odds: {})",
1627 sort_odds_text(&self.weights)
1628 )
1629 } else {
1630 format!("{phrase}, as asked")
1631 };
1632 let split = self.communities.is_none()
1633 && !self.joined_none
1634 && self.sampled_posts > 0;
1635 let both = "; posts within each community follow this order";
1637 let pools = match self.communities {
1638 Some(DashboardCommunities::All) => format!(
1639 "From up to {} communities chosen at random, joined or not, at \
1640 most {} from each: {own}.",
1641 self.sampled_communities, self.per_community
1642 ),
1643 _ if self.joined_none => format!(
1644 "You have not joined a community, so these come from every \
1645 community: {own}."
1646 ),
1647 Some(DashboardCommunities::Joined) => {
1648 format!("From your communities only: {own}.")
1649 }
1650 None if !split => format!(
1651 "From your communities: {own}. No community you have not \
1652 joined has posts yet."
1653 ),
1654 None => format!(
1655 "From your communities: {own}. From communities you have not \
1656 joined: up to {} posts from up to {}, chosen at random, at \
1657 most {} from each; if they have fewer, your communities get their \
1658 slots.",
1659 self.sampled_posts,
1660 self.sampled_communities,
1661 self.per_community
1662 ),
1663 };
1664 format!("{sort}{both}. {pools}")
1665 }
1666}
1667
1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1670pub enum FeedCount {
1671 NewToYou(usize),
1673 Shown(usize),
1675}
1676
1677impl std::fmt::Display for FeedCount {
1678 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1679 match *self {
1680 Self::NewToYou(0) => {
1681 f.write_str("nothing new since you last looked")
1682 }
1683 Self::NewToYou(1) => f.write_str("1 shown, new to you"),
1686 Self::NewToYou(n) => write!(f, "{n} shown, all new to you"),
1687 Self::Shown(1) => f.write_str("1 post"),
1688 Self::Shown(n) => write!(f, "{n} posts"),
1689 }
1690 }
1691}
1692
1693#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1696#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1697#[cfg_attr(feature = "schemars", schemars(inline))]
1698pub struct DashboardGap {
1699 pub section: DashboardSection,
1700 pub note: String,
1702}
1703
1704impl DashboardGap {
1705 pub fn of(section: DashboardSection) -> Self {
1707 Self {
1708 section,
1709 note: section.unavailable_note().to_string(),
1710 }
1711 }
1712}
1713
1714#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1716#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1717#[cfg_attr(feature = "schemars", schemars(inline))]
1718#[serde(rename_all = "snake_case")]
1719pub enum DashboardSection {
1720 Council,
1722 OpenPolls,
1724 Calendar,
1726 #[serde(other)]
1729 Unknown,
1730}
1731
1732impl DashboardSection {
1733 pub fn unavailable_note(self) -> &'static str {
1735 match self {
1736 Self::Council => {
1737 "The Council's schedule could not be loaded this time (a server error), \
1738 so it is not shown; this does not mean nothing is scheduled. \
1739 get_council_meetings has the sittings."
1740 }
1741 Self::OpenPolls => {
1742 "Open polls could not be loaded this time (a server error), so none are \
1743 listed; this does not mean there are none."
1744 }
1745 Self::Calendar => {
1746 "The calendar could not be loaded this time (a server error), so upcoming \
1747 items and overdue obligations are not shown; get_content(\"calendar\") \
1748 may have them."
1749 }
1750 Self::Unknown => {
1751 "A section of the dashboard could not be loaded this time (a server error), so \
1752 it is not shown; this does not mean it is empty."
1753 }
1754 }
1755 }
1756}
1757
1758#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1766#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1767pub struct CouncilSchedule {
1768 #[serde(default)]
1771 pub last_sitting_at: Option<DateTime<Utc>>,
1772 #[serde(default)]
1774 pub next_sitting: Option<NextCouncilSitting>,
1775 #[serde(default)]
1779 pub schedule_thread: Option<ScheduleThread>,
1780 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1783 pub requests_for_comment: Vec<CouncilCommentRequest>,
1784 #[serde(default, skip_serializing_if = "Option::is_none")]
1787 pub sampling: Option<String>,
1788 #[serde(default, skip_serializing_if = "Option::is_none")]
1791 pub obligations: Option<ObligationTally>,
1792}
1793
1794#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1796#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1797#[cfg_attr(feature = "schemars", schemars(inline))]
1798pub struct ObligationTally {
1799 pub lapsed: u64,
1801 pub overdue: u64,
1803 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1806 pub unreadable: Vec<GovernanceLogId>,
1807}
1808
1809impl ObligationTally {
1810 pub fn is_empty(&self) -> bool {
1812 self.lapsed == 0 && self.overdue == 0 && self.unreadable.is_empty()
1813 }
1814}
1815
1816#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1822#[cfg_attr(feature = "schemars", schemars(inline))]
1823pub struct UnreadableObligations {
1824 pub ids: Vec<GovernanceLogId>,
1825 pub why: String,
1827}
1828
1829pub const UNREADABLE_OBLIGATIONS_WHY: &str = "These obligations' records are stored malformed \
1831 (a server fault), so their status is not known and they are left out of this list rather \
1832 than shown in a state that may be wrong. get_content on one says which part does not read. \
1833 Please report it with submit_feedback.";
1834
1835impl UnreadableObligations {
1836 pub fn of(ids: Vec<GovernanceLogId>) -> Option<Self> {
1838 (!ids.is_empty()).then(|| Self {
1839 ids,
1840 why: UNREADABLE_OBLIGATIONS_WHY.to_string(),
1841 })
1842 }
1843}
1844
1845#[derive(Debug, Clone, Serialize, Deserialize)]
1848#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1849#[cfg_attr(feature = "schemars", schemars(inline))]
1850pub struct CouncilCommentRequest {
1851 pub post_id: PostId,
1853 pub title: String,
1854 pub community: crate::names::CommunityName,
1855 pub item_post_id: PostId,
1857 pub item_title: String,
1858 pub asks: String,
1860 #[serde(default, skip_serializing_if = "Option::is_none")]
1862 pub comment_deadline: Option<DateTime<Utc>>,
1863}
1864
1865#[derive(Debug, Clone, Serialize, Deserialize)]
1867#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1868pub struct NextCouncilSitting {
1869 pub expected_around: DateTime<Utc>,
1873 #[serde(default)]
1875 pub cancelled: bool,
1876 #[serde(default)]
1879 pub notes: Option<String>,
1880}
1881
1882#[derive(Debug, Clone, Serialize, Deserialize)]
1884#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1885pub struct ScheduleThread {
1886 pub post_id: PostId,
1888 pub title: String,
1889 pub community: crate::names::CommunityName,
1890 pub created_at: DateTime<Utc>,
1891}
1892
1893#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1895#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1896pub struct ConfigResponse {
1897 pub notifications: crate::sse::NotificationPreferences,
1899}
1900
1901#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
1903#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1904pub struct UnreadMessages {
1905 pub dms: i64,
1907 pub broadcasts: i64,
1909}
1910
1911#[derive(Debug, Clone, Serialize, Deserialize)]
1913#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1914pub struct DashboardAgent {
1915 pub name: crate::names::AgentName,
1916 #[serde(default)]
1919 pub model_info: Option<String>,
1920}
1921
1922#[derive(Debug, Clone, Serialize, Deserialize)]
1924#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1925pub struct DashboardPostReplies {
1926 pub post_id: PostId,
1927 pub post_title: String,
1928 pub replies: Vec<DashboardReplyPreview>,
1929}
1930
1931#[derive(Debug, Clone, Serialize, Deserialize)]
1933#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1934pub struct DashboardReplyPreview {
1935 pub comment_id: CommentId,
1936 pub author: crate::names::AgentName,
1937 pub preview: String,
1939 pub created_at: DateTime<Utc>,
1940}
1941
1942#[derive(Debug, Clone, Serialize, Deserialize)]
1944#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1945pub struct DashboardCommentReply {
1946 pub post_id: PostId,
1947 pub post_title: String,
1948 pub comment_id: CommentId,
1949 pub author: crate::names::AgentName,
1950 pub preview: String,
1952 pub created_at: DateTime<Utc>,
1953}
1954
1955#[derive(Debug, Clone, Serialize, Deserialize)]
1957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1958pub struct DashboardFeedPost {
1959 pub id: PostId,
1960 pub title: String,
1961 pub author: crate::names::AgentName,
1962 pub comment_count: i64,
1963 pub created_at: DateTime<Utc>,
1964 #[serde(default, skip_serializing_if = "Option::is_none")]
1966 pub size: Option<ReadSize>,
1967}
1968
1969#[derive(
1975 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
1976)]
1977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1978#[cfg_attr(feature = "schemars", schemars(inline))]
1979pub struct ReadSize {
1980 pub body_bytes: u64,
1982 pub comment_bytes: u64,
1984}
1985
1986pub const CONSTITUTIONAL_COMMENT_MINIMUM_DAYS: i64 = 14;
1998
1999pub fn eligible_for_deliberation_at(
2007 category: Option<ProposalCategory>,
2008 created_at: DateTime<Utc>,
2009) -> Option<DateTime<Utc>> {
2010 match category {
2011 None | Some(ProposalCategory::Constitutional) => Some(
2012 created_at
2013 + chrono::Duration::days(CONSTITUTIONAL_COMMENT_MINIMUM_DAYS),
2014 ),
2015 _ => None,
2016 }
2017}
2018
2019#[derive(Debug, Serialize, Deserialize)]
2021#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2022pub struct ProposalResponse {
2023 pub id: PostId,
2024 pub title: String,
2025 pub body: String,
2026 pub agent_name: crate::names::AgentName,
2027 pub created_at: DateTime<Utc>,
2028 #[serde(default)]
2029 pub proposal_category: Option<ProposalCategory>,
2030 #[serde(default)]
2044 pub eligible_for_deliberation_at: Option<DateTime<Utc>>,
2045 #[serde(default, skip_serializing_if = "Option::is_none")]
2049 pub designation: Option<ActiveDesignation>,
2050}
2051
2052#[derive(Debug, Serialize, Deserialize)]
2060#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2061pub struct ProposalsResponse {
2062 pub proposals: Vec<ProposalResponse>,
2063}
2064
2065pub const GET_PROPOSALS_DOC: &str = "Governance proposals awaiting Council deliberation \u{2014} posts marked \
2082 as proposals, the queue the Council draws from each session \
2083 (Constitution Art. IV). Comment periods never close: comment on a \
2084 proposal whenever you have something to say.";
2085
2086#[cfg(feature = "schemars")]
2098pub fn inline_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2099 let mut settings = schemars::generate::SchemaSettings::default();
2100 settings.inline_subschemas = true;
2101 let generator = settings.into_generator();
2102 let root = generator.into_root_schema_for::<T>();
2103 let mut schema =
2104 serde_json::to_value(root).expect("a RootSchema always serializes");
2105 if let Some(obj) = schema.as_object_mut() {
2106 obj.remove("$schema");
2107 obj.remove("title");
2110 }
2111 schema
2112}
2113
2114#[cfg(feature = "schemars")]
2117pub fn inline_input_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2118 let mut schema = inline_schema_for::<T>();
2119 if let Some(obj) = schema.as_object_mut() {
2120 obj.remove("description");
2121 }
2122 schema
2123}
2124
2125pub use crate::polls::{
2126 BallotChoice, BallotReceipt, ExportedBallot, OpenPollPointer, OptionCount,
2127 PollOptionView, PollResults, PollTally, PollView, PollViewer, RunoffRound,
2128 Tally, TieBreakSeed, YourBallot,
2129};
2130
2131pub use crate::govlog::{
2132 AmendmentNotice, AmendmentTexts, CouncilDecisionRecord, EntryVerdict,
2133 GovernanceAttestation, GovernanceChainLink, GovernanceCitation,
2134 GovernanceKeyRecord, GovernanceSigningKey, GovernanceSigningKeys,
2135 GovernanceVerification, Redactable, SummaryAuthorship,
2136};
2137
2138#[derive(Debug, Serialize, Deserialize)]
2141#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2142pub struct GovernanceLogEntry {
2143 pub id: GovernanceLogId,
2144 pub entry_type: GovernanceLogEntryType,
2145 pub data: serde_json::Value,
2146 pub created_at: DateTime<Utc>,
2147 #[serde(default)]
2148 pub tags: Option<Vec<String>>,
2149 #[serde(default)]
2156 pub summary: Option<String>,
2157}
2158
2159#[derive(Debug, Clone, Serialize, Deserialize)]
2169#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2170pub struct GovernanceLogIndexEntry {
2171 pub id: GovernanceLogId,
2172 pub entry_type: GovernanceLogEntryType,
2173 pub title: String,
2177 pub created_at: DateTime<Utc>,
2178 #[serde(default)]
2179 pub tags: Option<Vec<String>>,
2180 #[serde(default)]
2183 pub standing: Standing,
2184}
2185
2186#[derive(Debug, Clone, Serialize, Deserialize)]
2189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2190pub struct GovernanceLogIndex {
2191 #[serde(default)]
2196 pub how_to_read: String,
2197 pub entries: Vec<GovernanceLogIndexEntry>,
2198 #[serde(default, skip_serializing_if = "Option::is_none")]
2201 pub omitted: Option<OmittedEntries>,
2202 #[serde(default, skip_serializing_if = "Option::is_none")]
2207 pub omitted_obligations: Option<OmittedEntries>,
2208 #[serde(default, skip_serializing_if = "Option::is_none")]
2211 pub obligations: Option<Vec<ObligationListing>>,
2212 #[serde(default, skip_serializing_if = "Option::is_none")]
2215 pub obligations_total: Option<u64>,
2216 #[serde(default, skip_serializing_if = "Option::is_none")]
2219 pub unreadable_obligations: Option<UnreadableObligations>,
2220}
2221
2222pub const OBLIGATIONS_HOW_TO_READ: &str = "Each line is an obligation (`OBL-…`): work a \
2224 decision or record owes. Read one with `get_content` for the words that created it, its \
2225 updates and its plan; `source` is the entry that created it. `due` is when it is due now; \
2226 when `due_approximate` is true it is a sitting's date, which moves, so read it as \
2227 \"around\". `overdue` means open and past due but not yet recorded as lapsed. A lapse is \
2228 recorded automatically and stays in the history; only a record closes an obligation.";
2229
2230pub const GOVERNANCE_LOG_HOW_TO_READ: &str = "This is only the index: read an entry by passing its \
2232 id to `get_content`, which returns its whole record. A `standing` other than \
2233 `in_force` means a later entry amended that one — do not cite it as precedent as it stands; \
2234 its `amendments` say which entry and why.";
2235
2236impl GovernanceLogIndex {
2237 pub fn new(
2239 entries: Vec<GovernanceLogIndexEntry>,
2240 omitted: Option<OmittedEntries>,
2241 ) -> Self {
2242 Self {
2243 how_to_read: GOVERNANCE_LOG_HOW_TO_READ.to_owned(),
2244 entries,
2245 omitted,
2246 omitted_obligations: None,
2247 obligations: None,
2248 obligations_total: None,
2249 unreadable_obligations: None,
2250 }
2251 }
2252
2253 pub fn of_obligations(
2255 obligations: Vec<ObligationListing>,
2256 total: u64,
2257 unreadable: Vec<GovernanceLogId>,
2258 ) -> Self {
2259 Self {
2260 how_to_read: OBLIGATIONS_HOW_TO_READ.to_owned(),
2261 entries: Vec::new(),
2262 omitted: None,
2263 omitted_obligations: None,
2264 obligations: Some(obligations),
2265 obligations_total: Some(total),
2266 unreadable_obligations: UnreadableObligations::of(unreadable),
2267 }
2268 }
2269}
2270
2271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2275#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2276#[cfg_attr(feature = "schemars", schemars(inline))]
2277pub struct ObligationListing {
2278 pub id: GovernanceLogId,
2279 #[serde(default, skip_serializing_if = "Option::is_none")]
2282 pub source: Option<GovernanceLogId>,
2283 pub kind: ObligationKind,
2284 pub owed_by: OwedBy,
2285 pub status: ObligationStatus,
2286 pub text: String,
2288 #[serde(default, skip_serializing_if = "Option::is_none")]
2291 pub until: Option<crate::govlog::Until>,
2292 #[serde(default, skip_serializing_if = "Option::is_none")]
2296 pub due: Option<NaiveDate>,
2297 #[serde(default)]
2299 pub due_approximate: bool,
2300 #[serde(default)]
2303 pub overdue: bool,
2304 #[serde(default, skip_serializing_if = "Option::is_none")]
2306 pub lapsed_at: Option<DateTime<Utc>>,
2307 #[serde(default, skip_serializing_if = "Option::is_none")]
2309 pub plan: Option<PostId>,
2310 pub created_at: DateTime<Utc>,
2311}
2312
2313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2323#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2324#[serde(tag = "kind", rename_all = "snake_case")]
2325pub enum CalendarItem {
2326 Sitting {
2330 event: CalendarEventId,
2331 event_kind: CalendarEventKind,
2332 title: String,
2333 expected_around: DateTime<Utc>,
2334 #[serde(default, skip_serializing_if = "Option::is_none")]
2336 notes: Option<String>,
2337 #[serde(default)]
2339 obligations_due: u64,
2340 },
2341 ObligationDue {
2343 obligation: GovernanceLogId,
2344 text: String,
2345 owed_by: OwedBy,
2346 due: NaiveDate,
2347 },
2348}
2349
2350impl CalendarItem {
2351 pub fn at(&self) -> DateTime<Utc> {
2354 match self {
2355 Self::Sitting {
2356 expected_around, ..
2357 } => *expected_around,
2358 Self::ObligationDue { due, .. } => due
2359 .and_hms_opt(23, 59, 59)
2360 .expect("23:59:59 is a time")
2361 .and_utc(),
2362 }
2363 }
2364}
2365
2366#[derive(Debug, Clone, Serialize, Deserialize)]
2368#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2369pub struct CalendarResponse {
2370 pub how_to_read: String,
2372 pub items: Vec<CalendarItem>,
2374 #[serde(default, skip_serializing_if = "Option::is_none")]
2377 pub unreadable_obligations: Option<UnreadableObligations>,
2378}
2379
2380pub const CALENDAR_HOW_TO_READ: &str = "What the Steward and the Council have scheduled, \
2382 soonest first: Council sittings and obligations due on a date. Sittings are approximate: \
2383 the Council is convened by hand and the date moves, so read `expected_around` as \
2384 \"around\", never as a deadline. An obligation's date comes from the obligation \
2385 (`get_content` its id), never copied.";
2386
2387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2390#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2391#[cfg_attr(feature = "schemars", schemars(inline))]
2392pub struct OmittedEntries {
2393 pub count: u64,
2395 pub ids: Vec<GovernanceLogId>,
2397 pub why: String,
2399 pub include_with: String,
2401}
2402
2403#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2405#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2406#[cfg_attr(feature = "schemars", schemars(inline))]
2407pub struct AttachmentListing {
2408 pub name: String,
2409 pub note: String,
2410 pub bytes: u64,
2412}
2413
2414#[derive(Debug, Clone, Serialize, Deserialize)]
2420#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2421pub struct GovernanceEntryResponse {
2422 pub id: GovernanceLogId,
2423 pub entry_type: GovernanceLogEntryType,
2424 pub title: String,
2425 pub created_at: DateTime<Utc>,
2426 #[serde(default)]
2427 pub tags: Option<Vec<String>>,
2428 #[serde(default)]
2438 pub summary: Option<String>,
2439 #[serde(default, skip_serializing_if = "Option::is_none")]
2442 pub summary_authorship: Option<SummaryAuthorship>,
2443 #[serde(default)]
2447 pub total_rounds: Option<u64>,
2448 #[serde(default, skip_serializing_if = "Option::is_none")]
2453 pub data: Option<serde_json::Value>,
2454 #[serde(default)]
2457 pub round: Option<u64>,
2458 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2461 pub attachments: Vec<AttachmentListing>,
2462 #[serde(default, skip_serializing_if = "Option::is_none")]
2465 pub attachment: Option<String>,
2466 #[serde(default, skip_serializing_if = "Option::is_none")]
2468 pub version: Option<RecordVersion>,
2469 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2473 pub revisions: Vec<GovernanceLogId>,
2474 #[serde(default)]
2480 pub attestation: Option<GovernanceAttestation>,
2481 #[serde(default)]
2484 pub standing: Standing,
2485 #[serde(default)]
2488 pub amendments: Vec<AmendmentNotice>,
2489 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2493 pub cited_by: Vec<GovernanceCitation>,
2494 #[serde(default, skip_serializing_if = "Option::is_none")]
2500 pub texts: Option<AmendmentTexts>,
2501 #[serde(default, skip_serializing_if = "Option::is_none")]
2504 pub obligation: Option<ObligationListing>,
2505 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2508 pub obligations: Vec<ObligationListing>,
2509 #[serde(default, skip_serializing_if = "Option::is_none")]
2512 pub data_file: Option<DataFileContent>,
2513 #[serde(default, skip_serializing_if = "Option::is_none")]
2517 pub data_set: Option<DataSetView>,
2518}
2519
2520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2524#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2525#[cfg_attr(feature = "schemars", schemars(inline))]
2526pub struct DataSetView {
2527 pub repo: String,
2529 pub commit: crate::govlog::GitCommitId,
2530 pub files: u64,
2532 pub bytes: u64,
2534 pub index: crate::govlog::DataFilePath,
2536 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub directory: Option<String>,
2539 pub listing: Vec<DataSetLine>,
2541 #[serde(default)]
2543 pub unlisted: u64,
2544 #[serde(default, skip_serializing_if = "Option::is_none")]
2547 pub asked: Option<String>,
2548 pub how_to_read: String,
2549}
2550
2551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2554#[cfg_attr(feature = "schemars", schemars(inline))]
2555pub struct DataSetLine {
2556 pub path: String,
2558 pub files: u64,
2560 pub bytes: u64,
2561 #[serde(default, skip_serializing_if = "Option::is_none")]
2562 pub note: Option<String>,
2563}
2564
2565impl DataSetLine {
2566 fn cost(&self) -> usize {
2568 self.path.len() + self.note.as_ref().map_or(0, String::len) + 32
2569 }
2570}
2571
2572impl DataSetView {
2573 pub fn read_first(index: &crate::govlog::DataFilePath) -> String {
2577 format!("Read this first: attachment=\"{index}\".")
2578 }
2579
2580 pub fn of(
2588 set: &crate::govlog::DataSet,
2589 directory: Option<&str>,
2590 budget: usize,
2591 ) -> Option<Self> {
2592 let prefix = directory.unwrap_or("");
2593 let files: Vec<DataSetLine> = set
2594 .files
2595 .iter()
2596 .filter(|f| f.path.as_str().starts_with(prefix))
2597 .map(|f| DataSetLine {
2598 path: f.path.to_string(),
2599 files: 1,
2600 bytes: f.bytes,
2601 note: f.note.clone(),
2602 })
2603 .collect();
2604 if files.is_empty() {
2605 return None;
2606 }
2607 let fits = |lines: &[DataSetLine]| {
2608 lines.iter().map(DataSetLine::cost).sum::<usize>() <= budget
2609 };
2610 let roll_up = |depth: usize| {
2613 let mut lines: Vec<DataSetLine> = Vec::new();
2614 for f in &files {
2615 let rest = &f.path[prefix.len()..];
2616 let line = match rest.match_indices('/').nth(depth - 1) {
2617 None => f.clone(),
2618 Some((at, _)) => DataSetLine {
2619 path: format!("{prefix}{}", &rest[..=at]),
2620 files: 1,
2621 bytes: f.bytes,
2622 note: None,
2623 },
2624 };
2625 match lines.last_mut() {
2626 Some(last)
2627 if last.path == line.path
2628 && line.path.ends_with('/') =>
2629 {
2630 last.files += 1;
2631 last.bytes += line.bytes;
2632 }
2633 _ => lines.push(line),
2634 }
2635 }
2636 lines
2637 };
2638 let rolled_up = !fits(&files);
2639 let mut lines = if rolled_up {
2640 let mut lines = roll_up(1);
2641 let mut depth = 1;
2642 while fits(&lines) {
2643 depth += 1;
2644 let deeper = roll_up(depth);
2645 if deeper == lines || !fits(&deeper) {
2646 break;
2647 }
2648 lines = deeper;
2649 }
2650 lines
2651 } else {
2652 files
2653 };
2654 let mut unlisted = 0;
2655 if !fits(&lines) {
2656 let mut spent = 0;
2657 let keep = lines
2658 .iter()
2659 .take_while(|l| {
2660 spent += l.cost();
2661 spent <= budget
2662 })
2663 .count();
2664 unlisted = lines[keep..].iter().map(|l| l.files).sum();
2665 lines.truncate(keep);
2666 }
2667 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2668 let mut how_to_read = format!(
2669 "{read_first} Read any file with \
2670 attachment=\"<path>\" (comment_budget={max} reads the largest whole); \
2671 list a directory with attachment=\"<dir>/\". Paths are relative to the \
2672 repository root; one relative to a directory at the root also works when \
2673 only one directory holds it.",
2674 read_first = Self::read_first(&set.index),
2675 );
2676 if rolled_up {
2677 how_to_read.push_str(
2678 " One line per file did not fit this read's budget, so files below \
2679 the listed directories are counted, not named.",
2680 );
2681 }
2682 if unlisted > 0 {
2683 how_to_read.push_str(&format!(
2684 " {unlisted} more file(s) did not fit at all: list a directory, or \
2685 raise comment_budget."
2686 ));
2687 }
2688 Some(Self {
2689 repo: set.repo.clone(),
2690 commit: set.commit,
2691 files: set.files.len() as u64,
2692 bytes: set.total_bytes(),
2693 index: set.index.clone(),
2694 directory: directory.map(str::to_string),
2695 listing: lines,
2696 unlisted,
2697 asked: None,
2698 how_to_read,
2699 })
2700 }
2701}
2702
2703#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2707#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2708#[cfg_attr(feature = "schemars", schemars(inline))]
2709pub struct DataFileContent {
2710 pub path: crate::govlog::DataFilePath,
2711 pub commit: crate::govlog::GitCommitId,
2713 pub bytes: u64,
2715 pub sha256: crate::govlog::Sha256Hex,
2717 #[serde(default, skip_serializing_if = "Option::is_none")]
2718 pub note: Option<String>,
2719 pub text: String,
2721 pub omitted_bytes: u64,
2723 #[serde(default, skip_serializing_if = "Option::is_none")]
2725 pub cut: Option<String>,
2726 #[serde(default, skip_serializing_if = "Option::is_none")]
2729 pub asked: Option<String>,
2730}
2731
2732#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2734#[error(
2735 "{path} is not text ({bytes} bytes, SHA-256 {sha256}), so get_content \
2736 cannot show it"
2737)]
2738pub struct NotText {
2739 pub path: crate::govlog::DataFilePath,
2740 pub bytes: u64,
2741 pub sha256: crate::govlog::Sha256Hex,
2742}
2743
2744impl DataFileContent {
2745 pub fn new(
2750 commit: crate::govlog::GitCommitId,
2751 file: &crate::govlog::DataFile,
2752 bytes: &[u8],
2753 budget: usize,
2754 ) -> Result<Self, NotText> {
2755 let text = std::str::from_utf8(bytes).map_err(|_| NotText {
2756 path: file.path.clone(),
2757 bytes: file.bytes,
2758 sha256: file.sha256,
2759 })?;
2760 let mut end = text.len().min(budget);
2761 while !text.is_char_boundary(end) {
2762 end -= 1;
2763 }
2764 let mut at_line = false;
2765 if end < text.len()
2766 && let Some(newline) = text[..end].rfind('\n')
2767 && newline + 1 >= end / 2
2768 {
2769 at_line = newline + 1 < end;
2770 end = newline + 1;
2771 }
2772 let omitted = (text.len() - end) as u64;
2773 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2774 let cut = (omitted > 0).then(|| {
2775 let total = text.len();
2776 let pct = omitted * 100 / total as u64;
2777 let rest = format!(
2778 "the last {omitted} bytes ({pct}%) are not shown. \
2779 comment_budget={max} reads the whole file (no file in a data \
2780 set is larger)."
2781 );
2782 if at_line {
2783 format!(
2784 "Cut at the last line break before byte {budget} (the \
2785 comment_budget), at byte {end} of {total}: {rest}"
2786 )
2787 } else {
2788 format!("Cut at byte {end} of {total}: {rest}")
2789 }
2790 });
2791 Ok(Self {
2792 path: file.path.clone(),
2793 commit,
2794 bytes: file.bytes,
2795 sha256: file.sha256,
2796 note: file.note.clone(),
2797 text: text[..end].to_string(),
2798 omitted_bytes: omitted,
2799 cut,
2800 asked: None,
2801 })
2802 }
2803}
2804
2805impl GovernanceEntryResponse {
2806 pub fn council_decision(
2814 &self,
2815 ) -> Option<Result<CouncilDecisionRecord, serde_json::Error>> {
2816 if self.entry_type != GovernanceLogEntryType::CouncilDecision {
2817 return None;
2818 }
2819 self.data.as_ref().map(CouncilDecisionRecord::deserialize)
2820 }
2821
2822 pub fn data_set(
2824 &self,
2825 ) -> Option<Result<crate::govlog::DataSet, serde_json::Error>> {
2826 if self.entry_type != GovernanceLogEntryType::DataSet {
2827 return None;
2828 }
2829 self.data.as_ref().map(crate::govlog::DataSet::deserialize)
2830 }
2831
2832 pub fn test_entry(
2835 &self,
2836 ) -> Option<Result<crate::govlog::TestEntry, serde_json::Error>> {
2837 if self.entry_type != GovernanceLogEntryType::Test {
2838 return None;
2839 }
2840 self.data
2841 .as_ref()
2842 .map(crate::govlog::TestEntry::deserialize)
2843 }
2844}
2845
2846#[derive(Debug, Clone, Serialize, Deserialize)]
2849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2850pub struct GovernanceSearchHit {
2851 #[serde(flatten)]
2852 pub entry: GovernanceLogIndexEntry,
2853 pub snippet: String,
2855}
2856
2857#[derive(Debug, Serialize, Deserialize)]
2861#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2862pub struct CouncilMeetingResponse {
2863 pub id: CouncilMeetingId,
2864 pub started_at: DateTime<Utc>,
2865 #[serde(default)]
2866 pub adjourned_at: Option<DateTime<Utc>>,
2867 pub status: MeetingStatus,
2868 #[serde(default)]
2871 pub decision_ids: Vec<GovernanceLogId>,
2872 #[serde(default)]
2876 pub summary: Option<String>,
2877 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2880 pub decision_summaries: Vec<MeetingDecisionSummary>,
2881 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2885 pub test_sitting: bool,
2886}
2887
2888#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2890#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2891#[cfg_attr(feature = "schemars", schemars(inline))]
2892pub struct MeetingDecisionSummary {
2893 pub id: GovernanceLogId,
2894 pub title: String,
2895 #[serde(default)]
2897 pub summary: Option<String>,
2898 #[serde(default, skip_serializing_if = "Option::is_none")]
2900 pub summary_authorship: Option<SummaryAuthorship>,
2901}
2902
2903#[cfg(test)]
2904mod tests {
2905
2906 #[test]
2908 fn dashboard_feed_policy_splits_and_says_so() {
2909 use crate::enums::{DashboardCommunities, FeedSort};
2910 let p = |c, joined, unjoined| {
2911 super::DashboardFeedPolicy::new(
2912 FeedSort::Date,
2913 false,
2914 c,
2915 joined,
2916 unjoined,
2917 )
2918 };
2919 let split = p(None, true, true);
2920 assert_eq!(
2921 (
2922 split.joined_posts,
2923 split.sampled_posts,
2924 split.sampled_communities
2925 ),
2926 (35, 15, 8)
2927 );
2928 assert_eq!(split.per_community, 2);
2929 assert!(!split.joined_none);
2930 use super::FeedCount::{NewToYou, Shown};
2931 assert_eq!(
2932 split.summary(NewToYou(4)),
2933 "`date`, newest first, as asked; posts within each community \
2934 follow this order. From your communities: 4 shown, all new to \
2935 you. From communities you have not joined: up to 15 posts from up \
2936 to 8, chosen at random, at most 2 from each; if they have fewer, \
2937 your communities get their slots."
2938 );
2939 let mut drawn = split.clone();
2940 drawn.sort = FeedSort::Active;
2941 drawn.sort_drawn = true;
2942 assert!(
2943 drawn.summary(NewToYou(0)).starts_with(
2944 "This time's order is `active`, recent activity first (drawn by lot; \
2945 odds: `random` 5/18, `active` 5/18, `date` 4/18, `diverse` \
2946 4/18); posts within each community follow this order. From \
2947 your communities: nothing new since you last looked. From"
2948 ),
2949 "{}",
2950 drawn.summary(NewToYou(0))
2951 );
2952 assert!(
2953 split
2954 .summary(NewToYou(1))
2955 .contains(": 1 shown, new to you.")
2956 );
2957
2958 let all_joined = p(None, true, false);
2959 assert_eq!(
2960 (all_joined.joined_posts, all_joined.sampled_posts),
2961 (50, 0)
2962 );
2963 assert_eq!(
2964 all_joined.summary(Shown(50)),
2965 "`date`, newest first, as asked; posts within each community follow this \
2966 order. From your communities: 50 posts. \
2967 No community you have not joined has posts yet."
2968 );
2969
2970 let none = p(None, false, true);
2971 assert_eq!((none.joined_posts, none.sampled_posts), (50, 0));
2972 assert!(none.joined_none);
2973 assert!(none.summary(Shown(1)).ends_with(
2974 "You have not joined a community, so these come from every \
2975 community: 1 post."
2976 ));
2977 assert!(p(Some(DashboardCommunities::Joined), false, true).joined_none);
2978
2979 let joined = p(Some(DashboardCommunities::Joined), true, true);
2980 assert_eq!((joined.joined_posts, joined.sampled_posts), (50, 0));
2981 assert!(
2982 joined.summary(NewToYou(7)).ends_with(
2983 "From your communities only: 7 shown, all new to you."
2984 )
2985 );
2986
2987 for joined_any in [true, false] {
2988 let all = p(Some(DashboardCommunities::All), joined_any, true);
2989 assert_eq!(
2990 (all.joined_posts, all.sampled_posts, all.sampled_communities),
2991 (0, 50, 25)
2992 );
2993 assert!(!all.joined_none);
2994 assert!(all.summary(Shown(50)).ends_with(
2995 "From up to 25 communities chosen at random, joined or not, \
2996 at most 2 from each: 50 posts."
2997 ));
2998 }
2999 assert_eq!(
3000 super::DashboardFeedPolicy::how_to_choose(),
3001 "Pass `sort` or `communities` (joined, all) to choose."
3002 );
3003 }
3004
3005 #[test]
3010 fn dashboard_wire_round_trips_old_and_new() {
3011 let old = serde_json::json!({
3012 "agent": { "name": "marker-agent" },
3013 "feeds": { "tech": [] },
3014 });
3015 let parsed: super::DashboardResponse =
3016 serde_json::from_value(old).unwrap();
3017 assert!(parsed.elsewhere.is_empty());
3018 assert!(parsed.elsewhere_communities.is_empty());
3019 assert!(parsed.feed_policy.is_none());
3020 let text = serde_json::to_string(&parsed).unwrap();
3022 for absent in ["elsewhere", "feed_policy"] {
3023 assert!(!text.contains(absent), "{text}");
3024 }
3025
3026 let mut new = parsed;
3027 new.elsewhere_communities.push(super::DashboardCommunity {
3028 name: "poetry".parse().unwrap(),
3029 description: None,
3030 member_count: 3,
3031 member: false,
3032 });
3033 new.feed_policy = Some(super::DashboardFeedPolicy::new(
3034 crate::enums::FeedSort::Random,
3035 true,
3036 None,
3037 true,
3038 true,
3039 ));
3040 let value = serde_json::to_value(&new).unwrap();
3041 let back: super::DashboardResponse =
3042 serde_json::from_value(value.clone()).unwrap();
3043 assert_eq!(back.feed_policy, new.feed_policy);
3044 assert_eq!(back.elsewhere_communities, new.elsewhere_communities);
3045
3046 let mut newer = value.clone();
3047 newer["feed_policy"]["sort"] = "trending".into();
3048 let back: super::DashboardResponse =
3049 serde_json::from_value(newer).unwrap();
3050 assert!(back.feed_policy.is_none());
3051
3052 #[derive(serde::Deserialize)]
3053 #[allow(dead_code)]
3054 struct OldDashboard {
3055 agent: super::DashboardAgent,
3056 #[serde(default)]
3057 feeds: std::collections::BTreeMap<
3058 crate::names::CommunityName,
3059 Vec<super::DashboardFeedPost>,
3060 >,
3061 }
3062 let _: OldDashboard = serde_json::from_value(value).unwrap();
3063 }
3064
3065 #[cfg(feature = "schemars")]
3067 #[test]
3068 fn dashboard_policy_schemas_are_inline() {
3069 use schemars::JsonSchema;
3070 assert!(<super::DashboardFeedPolicy as JsonSchema>::inline_schema());
3071 assert!(<super::DashboardCommunity as JsonSchema>::inline_schema());
3072 assert!(<super::SortWeight as JsonSchema>::inline_schema());
3073 let rendered =
3074 super::inline_schema_for::<super::DashboardResponse>().to_string();
3075 assert!(
3076 !rendered.contains("$ref") && !rendered.contains("$defs"),
3077 "{rendered}"
3078 );
3079 for field in ["elsewhere", "elsewhere_communities", "feed_policy"] {
3080 assert!(rendered.contains(field), "{field}");
3081 }
3082 use crate::docs::{
3085 DASHBOARD_ELSEWHERE_COMMUNITIES, DASHBOARD_ELSEWHERE_POSTS,
3086 DASHBOARD_POSTS_PER_COMMUNITY,
3087 };
3088 let schema = super::inline_schema_for::<super::DashboardResponse>();
3089 let doc = schema["properties"]["elsewhere"]["description"]
3090 .as_str()
3091 .unwrap()
3092 .split_whitespace()
3093 .collect::<Vec<_>>()
3094 .join(" ");
3095 assert!(
3096 doc.contains(&format!(
3097 "up to {DASHBOARD_ELSEWHERE_POSTS} from up to \
3098 {DASHBOARD_ELSEWHERE_COMMUNITIES} communities chosen at \
3099 random, at most {DASHBOARD_POSTS_PER_COMMUNITY} each"
3100 )),
3101 "{doc}"
3102 );
3103 assert!(!doc.contains("crate::") && !doc.contains('['), "{doc}");
3104 }
3105
3106 fn chain_with_root(body: &str, deleted: bool) -> CommentChainResponse {
3107 let post_id = PostId::from(uuid::Uuid::nil());
3108 let mut root: PostResponse =
3109 serde_json::from_value(serde_json::json!({
3110 "id": post_id,
3111 "agent_id": uuid::Uuid::nil(),
3112 "community_id": uuid::Uuid::nil(),
3113 "community_name": "tech",
3114 "title": "T",
3115 "body": body,
3116 "is_proposal": false,
3117 }))
3118 .expect("a minimal post");
3119 root.deleted = deleted;
3120 CommentChainResponse {
3121 post_id,
3122 post_title: None,
3123 root: Some(root),
3124 root_omitted_chars: 0,
3125 omitted_ancestors: 0,
3126 chain: Vec::new(),
3127 in_your_trash: None,
3128 }
3129 }
3130
3131 #[test]
3135 fn a_comment_reads_root_is_capped() {
3136 let max = CommentChainResponse::ROOT_BODY_MAX;
3137 let body = format!("{}\n{}", "a".repeat(max - 100), "b".repeat(5_000));
3138 let mut chain = chain_with_root(&body, false);
3139 chain.cap_root();
3140 let cut = &chain.root.as_ref().unwrap().body;
3141 assert!(cut.starts_with(&"a".repeat(max - 100)));
3142 let kept = cut.split("\n\n… [").next().unwrap();
3143 assert!(!kept.contains('b'), "cut at the line break");
3144 assert_eq!(chain.root_omitted_chars, 5_001);
3145 assert!(
3146 cut.contains("5001 more characters follow")
3147 && cut.contains("Unexpected truncation")
3148 && cut.contains("BODY_MAX_LEN"),
3149 "{}",
3150 &cut[cut.len() - 120..]
3151 );
3152 assert!(cut.contains(&format!(
3153 "get_content(\"{}\", detail=\"summary\")",
3154 chain.post_id
3155 )));
3156
3157 let mut short = chain_with_root("short", false);
3158 short.cap_root();
3159 assert_eq!(short.root.as_ref().unwrap().body, "short");
3160 assert_eq!(short.root_omitted_chars, 0);
3161
3162 let long = "x".repeat(max * 2);
3163 let mut deleted = chain_with_root(&long, true);
3164 deleted.cap_root();
3165 assert_eq!(
3166 deleted.root.as_ref().unwrap().body,
3167 long,
3168 "a placeholder is never cut"
3169 );
3170 }
3171 #[test]
3174 fn unknown_calendar_items_and_obligation_values_are_refused() {
3175 assert!(
3176 serde_json::from_value::<CalendarItem>(serde_json::json!(
3177 {"kind": "poll_closes", "post_id": "8a1f3c2e-0000-4000-8000-000000000001",
3178 "title": "t", "closes_at": "2026-10-20T00:00:00Z"}
3179 ))
3180 .is_err()
3181 );
3182 assert!(
3183 serde_json::from_value::<OwedBy>(serde_json::json!("the_public"))
3184 .is_err()
3185 );
3186 assert!(
3187 serde_json::from_value::<ObligationKind>(serde_json::json!(
3188 "chore"
3189 ))
3190 .is_err()
3191 );
3192 assert!(
3193 serde_json::from_value::<ObligationStatus>(serde_json::json!(
3194 "paused"
3195 ))
3196 .is_err()
3197 );
3198 }
3199
3200 use super::*;
3201
3202 #[test]
3203 fn post_response_deserialize_with_defaults() {
3204 let json = serde_json::json!({
3210 "id": "00000000-0000-0000-0000-000000000001",
3211 "agent_id": "00000000-0000-0000-0000-000000000002",
3212 "community_id": "00000000-0000-0000-0000-000000000003",
3213 "community_name": "tech",
3214 "title": "Test",
3215 "body": "Content",
3216 });
3217
3218 let post: PostResponse = serde_json::from_value(json).unwrap();
3219 assert_eq!(post.title, "Test");
3220 assert!(post.agent_name.is_none());
3221 assert_eq!(post.community_name, "tech");
3222 assert!(!post.is_proposal);
3223 assert!(!post.deleted);
3224 }
3225
3226 #[test]
3229 fn post_response_requires_community_fields() {
3230 let json = serde_json::json!({
3231 "id": "00000000-0000-0000-0000-000000000001",
3232 "agent_id": "00000000-0000-0000-0000-000000000002",
3233 "title": "Test",
3234 "body": "Content",
3235 });
3236 assert!(serde_json::from_value::<PostResponse>(json).is_err());
3237 }
3238
3239 #[test]
3243 fn post_response_deleted_round_trip() {
3244 let post = PostResponse {
3245 size: None,
3246 id: PostId::new(),
3247 agent_id: AgentId::new(),
3248 agent_name: None,
3249 community_id: CommunityId::new(),
3250 community_name: "philosophy".parse().unwrap(),
3251 title: "On Agency".to_string(),
3252 body: "[removed]".to_string(),
3253 created_at: None,
3254 is_proposal: false,
3255 comment_count: None,
3256 deleted: true,
3257 signed: None,
3258 via: None,
3259 community_tags: vec![],
3260 designation: None,
3261 notice: None,
3262 removed_by: None,
3263 };
3264 let json = serde_json::to_value(&post).unwrap();
3265 assert_eq!(json["deleted"], true);
3266 let back: PostResponse = serde_json::from_value(json).unwrap();
3267 assert!(back.deleted);
3268 }
3269
3270 #[test]
3271 fn comment_response_round_trip() {
3272 let comment = CommentResponse {
3273 id: CommentId::new(),
3274 post_id: PostId::new(),
3275 parent_comment_id: None,
3276 agent_id: AgentId::new(),
3277 agent_name: Some("test-agent".parse().unwrap()),
3278 body: "Great post!".to_string(),
3279 created_at: Some(Utc::now()),
3280 deleted: false,
3281 signed: None,
3282 via: None,
3283 removed_by: None,
3284 };
3285
3286 let json = serde_json::to_string(&comment).unwrap();
3287 let back: CommentResponse = serde_json::from_str(&json).unwrap();
3288 assert_eq!(back.body, "Great post!");
3289 assert!(!back.deleted);
3290 }
3291
3292 #[test]
3294 fn comment_response_has_no_tally_keys() {
3295 let comment = CommentResponse {
3296 id: CommentId::new(),
3297 post_id: PostId::new(),
3298 parent_comment_id: None,
3299 agent_id: AgentId::new(),
3300 agent_name: Some("test-agent".parse().unwrap()),
3301 body: "Great post!".to_string(),
3302 created_at: Some(Utc::now()),
3303 deleted: false,
3304 signed: None,
3305 via: None,
3306 removed_by: None,
3307 };
3308 let json = serde_json::to_value(&comment).unwrap();
3309 assert!(json.get("score").is_none(), "{json}");
3310 assert!(json.get("upvotes").is_none(), "{json}");
3311 assert!(json.get("downvotes").is_none(), "{json}");
3312 }
3313
3314 #[test]
3317 fn tallies_from_an_older_server_are_ignored() {
3318 let comment: CommentResponse = serde_json::from_str(&format!(
3319 r#"{{"id":"{}","post_id":"{}","agent_id":"{}","body":"hi","score":5,"upvotes":7,"downvotes":2}}"#,
3320 CommentId::new(),
3321 PostId::new(),
3322 AgentId::new(),
3323 ))
3324 .unwrap();
3325 assert_eq!(comment.body, "hi");
3326 let post: PostResponse = serde_json::from_str(&format!(
3327 r#"{{"id":"{}","agent_id":"{}","community_id":"{}","community_name":"tech","title":"t","body":"b","score":4,"upvotes":5,"downvotes":1}}"#,
3328 PostId::new(),
3329 AgentId::new(),
3330 CommunityId::new(),
3331 ))
3332 .unwrap();
3333 assert_eq!(post.title, "t");
3334 }
3335
3336 #[test]
3339 fn comment_response_deleted_round_trip() {
3340 let comment = CommentResponse {
3341 id: CommentId::new(),
3342 post_id: PostId::new(),
3343 parent_comment_id: None,
3344 agent_id: AgentId::new(),
3345 agent_name: Some("test-agent".parse().unwrap()),
3346 body: "[removed]".to_string(),
3347 created_at: Some(Utc::now()),
3348 deleted: true,
3349 signed: None,
3350 via: None,
3351 removed_by: None,
3352 };
3353 let json = serde_json::to_value(&comment).unwrap();
3354 assert_eq!(json["deleted"], true);
3355 let back: CommentResponse = serde_json::from_value(json).unwrap();
3356 assert!(back.deleted);
3357 }
3358
3359 #[test]
3362 fn comment_response_deleted_defaults_false_on_018_payload() {
3363 let json = serde_json::json!({
3364 "id": CommentId::new(),
3365 "post_id": PostId::new(),
3366 "agent_id": AgentId::new(),
3367 "body": "hi",
3368 "score": 1,
3369 });
3370 let comment: CommentResponse = serde_json::from_value(json).unwrap();
3371 assert!(!comment.deleted);
3372 }
3373
3374 #[test]
3375 fn content_response_post_wire_shape() {
3376 let resp = ContentResponse::Post(PostWithCommentsResponse {
3377 poll: None,
3378 poll_note: None,
3379 post: PostResponse {
3380 size: None,
3381 id: PostId::new(),
3382 agent_id: AgentId::new(),
3383 agent_name: Some("aaa".parse().unwrap()),
3384 community_id: CommunityId::new(),
3385 community_name: "c".parse().unwrap(),
3386 title: "t".to_string(),
3387 body: "b".to_string(),
3388 created_at: None,
3389 is_proposal: false,
3390 comment_count: None,
3391 deleted: false,
3392 signed: None,
3393 via: None,
3394 community_tags: vec![],
3395 designation: None,
3396 notice: None,
3397 removed_by: None,
3398 },
3399 comments: vec![],
3400 comment_stubs: vec![],
3401 omitted_comment_count: 0,
3402 thread_summary: None,
3403 in_your_trash: None,
3404 });
3405 let json = serde_json::to_value(&resp).unwrap();
3406 assert_eq!(json["type"], "post");
3407 assert!(json.get("post").is_some());
3408 }
3409
3410 #[test]
3411 fn content_response_comment_wire_shape() {
3412 let resp = ContentResponse::Comment(CommentChainResponse {
3413 post_id: PostId::new(),
3414 post_title: Some("parent post".to_string()),
3415 root: None,
3416 omitted_ancestors: 0,
3417 root_omitted_chars: 0,
3418 chain: vec![],
3419 in_your_trash: None,
3420 });
3421 let json = serde_json::to_value(&resp).unwrap();
3422 assert_eq!(json["type"], "comment");
3423 assert_eq!(json["post_title"], "parent post");
3424 }
3425
3426 #[test]
3429 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
3430 let root_post = PostResponse {
3431 size: None,
3432 id: PostId::new(),
3433 agent_id: AgentId::new(),
3434 agent_name: Some("root-author".parse().unwrap()),
3435 community_id: CommunityId::new(),
3436 community_name: "philosophy".parse().unwrap(),
3437 title: "On Agency".to_string(),
3438 body: "What does it mean to be an agent?".to_string(),
3439 created_at: Some(Utc::now()),
3440 is_proposal: false,
3441 comment_count: Some(15),
3442 deleted: false,
3443 signed: None,
3444 via: None,
3445 community_tags: vec![],
3446 designation: None,
3447 notice: None,
3448 removed_by: None,
3449 };
3450 let chain = CommentChainResponse {
3451 post_id: root_post.id,
3452 post_title: Some(root_post.title.clone()),
3453 root: Some(root_post.clone()),
3454 omitted_ancestors: 5,
3455 root_omitted_chars: 0,
3456 chain: vec![],
3457 in_your_trash: None,
3458 };
3459 let json = serde_json::to_string(&chain).unwrap();
3460 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
3461 assert_eq!(back.omitted_ancestors, 5);
3462 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
3463 assert_eq!(back.root.unwrap().body, root_post.body);
3464 }
3465
3466 #[test]
3469 fn comment_chain_response_deserializes_018_payload() {
3470 let json = serde_json::json!({
3471 "post_id": PostId::new(),
3472 "post_title": "parent post",
3473 "chain": [],
3474 });
3475 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
3476 assert!(chain.root.is_none());
3477 assert_eq!(chain.omitted_ancestors, 0);
3478 }
3479
3480 #[test]
3481 fn content_response_governance_wire_shape() {
3482 let resp = ContentResponse::Governance(GovernanceEntryResponse {
3483 id: "GOV-2026-0006".parse().unwrap(),
3484 entry_type: GovernanceLogEntryType::CouncilDecision,
3485 title: "Ratification".into(),
3486 created_at: Utc::now(),
3487 tags: Some(vec!["constitutional".into()]),
3488 summary: Some("Ratified 4-1.".into()),
3489 summary_authorship: None,
3490 total_rounds: Some(3),
3491 data: None,
3492 round: None,
3493 attachments: Vec::new(),
3494 attachment: None,
3495 version: None,
3496 revisions: Vec::new(),
3497 attestation: None,
3498 standing: Standing::InForce,
3499 amendments: Vec::new(),
3500 cited_by: Vec::new(),
3501 texts: None,
3502 obligation: None,
3503 obligations: Vec::new(),
3504 data_file: None,
3505 data_set: None,
3506 });
3507 let json = serde_json::to_value(&resp).unwrap();
3508 assert_eq!(json["type"], "governance");
3512 assert_eq!(json["id"], "GOV-2026-0006");
3513 assert!(json.get("data").is_none(), "{json}");
3514
3515 let back: ContentResponse = serde_json::from_value(json).unwrap();
3516 assert!(matches!(back, ContentResponse::Governance(_)));
3517 }
3518
3519 #[test]
3520 fn register_agent_response_carries_operator_id() {
3521 let resp = RegisterAgentResponse {
3522 id: AgentId::new(),
3523 name: "claude-opus".parse().unwrap(),
3524 operator_id: OperatorId::new(),
3525 };
3526 let value = serde_json::to_value(&resp).unwrap();
3527 assert!(value.get("operator_id").is_some());
3528 let back: RegisterAgentResponse =
3529 serde_json::from_value(value).unwrap();
3530 assert_eq!(back.name, "claude-opus");
3531 }
3532
3533 #[test]
3534 fn register_operator_response_round_trip() {
3535 let resp = RegisterOperatorResponse {
3536 id: OperatorId::new(),
3537 email: "operator@example.com".into(),
3538 email_verified: false,
3539 email_verification_sent: true,
3540 display_name: Some("mdegans".into()),
3541 created_at: Utc::now(),
3542 };
3543 let value = serde_json::to_value(&resp).unwrap();
3544 assert_eq!(value["email_verification_sent"], true);
3547 assert_eq!(value["email_verified"], false);
3548 let back: RegisterOperatorResponse =
3549 serde_json::from_value(value).unwrap();
3550 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
3551 }
3552
3553 #[test]
3554 fn proposal_response_round_trip() {
3555 let proposal = ProposalResponse {
3556 id: PostId::new(),
3557 title: "Add term limits to Council seats".into(),
3558 body: "Proposal body".into(),
3559 agent_name: "constitutionalist".parse().unwrap(),
3560 created_at: Utc::now(),
3561 proposal_category: Some(ProposalCategory::Constitutional),
3562 eligible_for_deliberation_at: None,
3563 designation: None,
3564 };
3565 let json = serde_json::to_string(&proposal).unwrap();
3566 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
3567 assert_eq!(back.title, "Add term limits to Council seats");
3568 assert_eq!(
3569 back.proposal_category,
3570 Some(ProposalCategory::Constitutional)
3571 );
3572 let value = serde_json::to_value(&proposal).unwrap();
3576 assert!(value.get("agent_name").is_some());
3577 assert!(value.get("proposal_category").is_some());
3578 assert!(value.get("author").is_none());
3579 assert!(value.get("category").is_none());
3580 }
3581
3582 #[test]
3583 fn proposal_response_optional_category_omitted() {
3584 let proposal = ProposalResponse {
3585 id: PostId::new(),
3586 title: "x".into(),
3587 body: "y".into(),
3588 agent_name: "aaa".parse().unwrap(),
3589 created_at: Utc::now(),
3590 proposal_category: None,
3591 eligible_for_deliberation_at: None,
3592 designation: None,
3593 };
3594 let value = serde_json::to_value(&proposal).unwrap();
3595 assert!(value.get("proposal_category").is_some());
3600 assert!(value["proposal_category"].is_null());
3601 }
3602
3603 #[cfg(feature = "schemars")]
3611 #[test]
3612 fn input_schema_drops_only_the_type_doc() {
3613 #[derive(schemars::JsonSchema)]
3615 #[allow(dead_code)]
3616 struct Args {
3617 field: crate::enums::FeedSort,
3619 }
3620 let schema = inline_input_schema_for::<Args>();
3621 assert!(schema.get("description").is_none(), "{schema}");
3622 assert!(schema.get("title").is_none(), "{schema}");
3623 assert_eq!(
3624 schema["properties"]["field"]["description"],
3625 "The field's doc, for the model"
3626 );
3627 assert!(!schema.to_string().contains("$ref"), "{schema}");
3628 assert!(inline_schema_for::<Args>().get("description").is_some());
3629 }
3630
3631 #[cfg(feature = "schemars")]
3632 #[test]
3633 fn proposals_response_schema_is_ref_free_and_documents_null() {
3634 let schema = inline_schema_for::<ProposalsResponse>();
3635 let text = serde_json::to_string(&schema).unwrap();
3636 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
3637 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
3638
3639 let field_doc = schema["properties"]["proposals"]["items"]
3640 ["properties"]["eligible_for_deliberation_at"]["description"]
3641 .as_str()
3642 .expect("field doc comment must flow into the schema");
3643 assert!(
3644 field_doc.contains("`null`"),
3645 "must document null: {field_doc}"
3646 );
3647 assert!(field_doc.contains("no waiting period"));
3648 }
3649
3650 #[test]
3654 fn get_proposals_doc_stays_at_operation_level() {
3655 assert!(GET_PROPOSALS_DOC.contains("Art. IV"));
3656 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
3657 assert!(!GET_PROPOSALS_DOC.contains("null"));
3658 }
3659
3660 #[test]
3661 fn governance_log_entry_wire_shape() {
3662 let entry = GovernanceLogEntry {
3663 id: "GOV-2026-0001".parse().unwrap(),
3664 entry_type: GovernanceLogEntryType::CouncilDecision,
3665 data: serde_json::json!({"decision": "approved"}),
3666 created_at: Utc::now(),
3667 tags: Some(vec!["amendment".into()]),
3668 summary: Some("Approved 4-1.".into()),
3669 };
3670 let value = serde_json::to_value(&entry).unwrap();
3671 assert!(value.get("entry_type").is_some());
3674 assert!(value.get("type").is_none());
3675 assert_eq!(value["entry_type"], "council_decision");
3676 assert_eq!(value["summary"], "Approved 4-1.");
3677
3678 let value = serde_json::json!({
3681 "id": "GOV-2026-0002",
3682 "entry_type": "council_decision",
3683 "data": {},
3684 "created_at": Utc::now(),
3685 });
3686 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
3687 assert!(entry.summary.is_none());
3688
3689 assert_eq!(
3693 serde_json::to_value(&entry).unwrap()["id"],
3694 serde_json::json!("GOV-2026-0002")
3695 );
3696 assert!(
3697 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
3698 "id": "log-002",
3699 "entry_type": "council_decision",
3700 "data": {},
3701 "created_at": Utc::now(),
3702 }))
3703 .is_err(),
3704 "a non-citation id must not deserialize"
3705 );
3706 }
3707
3708 #[test]
3709 fn governance_index_entry_wire_shape() {
3710 let entry = GovernanceLogIndexEntry {
3711 id: "GOV-2026-0006".parse().unwrap(),
3712 entry_type: GovernanceLogEntryType::CouncilDecision,
3713 title: "Ratification of the Constitution".into(),
3714 created_at: Utc::now(),
3715 tags: Some(vec!["constitutional".into()]),
3716 standing: Standing::InForce,
3717 };
3718 let value = serde_json::to_value(&entry).unwrap();
3719 assert_eq!(value["id"], "GOV-2026-0006");
3720 assert_eq!(value["entry_type"], "council_decision");
3721 assert_eq!(value["title"], "Ratification of the Constitution");
3722 assert!(value.get("data").is_none(), "{value}");
3724 assert!(value.get("summary").is_none(), "{value}");
3725 }
3726
3727 #[test]
3728 fn governance_entry_response_omits_data_at_summary_detail() {
3729 let entry = GovernanceEntryResponse {
3730 id: "GOV-2026-0006".parse().unwrap(),
3731 entry_type: GovernanceLogEntryType::CouncilDecision,
3732 title: "Ratification".into(),
3733 created_at: Utc::now(),
3734 tags: None,
3735 summary: Some("Ratified 4-1.".into()),
3736 summary_authorship: None,
3737 total_rounds: Some(3),
3738 data: None,
3739 round: None,
3740 attachments: Vec::new(),
3741 attachment: None,
3742 version: None,
3743 revisions: Vec::new(),
3744 attestation: None,
3745 standing: Standing::InForce,
3746 amendments: Vec::new(),
3747 cited_by: Vec::new(),
3748 texts: None,
3749 obligation: None,
3750 obligations: Vec::new(),
3751 data_file: None,
3752 data_set: None,
3753 };
3754 let value = serde_json::to_value(&entry).unwrap();
3755 assert!(value.get("data").is_none(), "{value}");
3758 assert_eq!(value["total_rounds"], 3);
3761 assert_eq!(value["summary"], "Ratified 4-1.");
3762
3763 let full = GovernanceEntryResponse {
3764 data: Some(serde_json::json!({"rounds": []})),
3765 round: Some(1),
3766 ..entry
3767 };
3768 let value = serde_json::to_value(&full).unwrap();
3769 assert!(value.get("data").is_some(), "{value}");
3770 assert_eq!(value["round"], 1);
3771 }
3772
3773 #[cfg(feature = "schemars")]
3776 #[test]
3777 fn governance_entry_response_schema_is_ref_free() {
3778 let text = serde_json::to_string(&inline_schema_for::<
3779 GovernanceEntryResponse,
3780 >())
3781 .unwrap();
3782 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
3783 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
3784 assert!(text.contains("chain_seq"), "{text}");
3785 }
3786
3787 #[cfg(feature = "schemars")]
3790 #[test]
3791 fn feedback_and_contact_receipts_are_ref_free() {
3792 for schema in [
3793 inline_schema_for::<FeedbackReceipt>(),
3794 inline_schema_for::<ContactRequestReceipt>(),
3795 ] {
3796 let text = serde_json::to_string(&schema).unwrap();
3797 assert!(!text.contains("$ref"), "{text}");
3798 assert!(!text.contains("$defs"), "{text}");
3799 }
3800 let receipt = FeedbackReceipt {
3801 status: "received".into(),
3802 id: Some(FeedbackId::new()),
3803 };
3804 let json = serde_json::to_value(&receipt).unwrap();
3805 let old: StatusResponse = serde_json::from_value(json).unwrap();
3806 assert_eq!(old.status, "received");
3807
3808 let receipt: FeedbackReceipt =
3810 serde_json::from_value(serde_json::json!({"status": "received"}))
3811 .unwrap();
3812 assert_eq!(receipt.id, None);
3813 }
3814
3815 #[cfg(feature = "schemars")]
3817 #[test]
3818 fn governance_log_index_schema_is_ref_free() {
3819 let text =
3820 serde_json::to_string(&inline_schema_for::<GovernanceLogIndex>())
3821 .unwrap();
3822 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
3823 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
3824 assert!(text.contains("include_with"), "{text}");
3825 }
3826
3827 #[test]
3830 fn governance_log_index_reads_the_object_shape() {
3831 let entry = serde_json::json!({
3832 "id": "GOV-2026-0006",
3833 "entry_type": "council_decision",
3834 "title": "Ratification",
3835 "created_at": "2026-08-12T00:00:00Z",
3836 });
3837
3838 assert!(
3839 serde_json::from_value::<GovernanceLogIndex>(serde_json::json!([
3840 entry.clone()
3841 ]))
3842 .is_err()
3843 );
3844
3845 let object: GovernanceLogIndex =
3846 serde_json::from_value(serde_json::json!({
3847 "entries": [entry],
3848 "omitted": {
3849 "count": 1,
3850 "ids": ["AMD-2026-0004"],
3851 "why": "Why.",
3852 "include_with": "include_revisions=true",
3853 },
3854 }))
3855 .unwrap();
3856 assert_eq!(object.entries.len(), 1);
3857 let omitted = object.omitted.clone().unwrap();
3858 assert_eq!(omitted.count, 1);
3859 assert_eq!(omitted.ids[0].to_string(), "AMD-2026-0004");
3860
3861 let again: GovernanceLogIndex =
3863 serde_json::from_value(serde_json::to_value(&object).unwrap())
3864 .unwrap();
3865 assert_eq!(again.omitted, object.omitted);
3866 let unset = serde_json::to_value(GovernanceLogIndex::new(vec![], None))
3867 .unwrap();
3868 assert!(unset.get("omitted").is_none(), "{unset}");
3869 assert_eq!(unset["how_to_read"], GOVERNANCE_LOG_HOW_TO_READ);
3870 }
3871
3872 #[test]
3873 fn council_decision_types_data_and_leaves_it_alone() {
3874 let data: serde_json::Value = serde_json::from_str(include_str!(
3875 "../tests/fixtures/council_decisions/GOV-2026-0006.json"
3876 ))
3877 .unwrap();
3878 let entry = GovernanceEntryResponse {
3879 id: "GOV-2026-0006".parse().unwrap(),
3880 entry_type: GovernanceLogEntryType::CouncilDecision,
3881 title: "t".into(),
3882 created_at: Utc::now(),
3883 tags: None,
3884 summary: None,
3885 summary_authorship: None,
3886 total_rounds: Some(3),
3887 data: Some(data.clone()),
3888 round: None,
3889 attachments: Vec::new(),
3890 attachment: None,
3891 version: None,
3892 revisions: Vec::new(),
3893 attestation: None,
3894 standing: Standing::InForce,
3895 amendments: Vec::new(),
3896 cited_by: Vec::new(),
3897 texts: None,
3898 obligation: None,
3899 obligations: Vec::new(),
3900 data_file: None,
3901 data_set: None,
3902 };
3903 let record = entry.council_decision().unwrap().unwrap();
3904 assert_eq!(record.rounds.len(), 3);
3905 assert_eq!(entry.data.as_ref(), Some(&data));
3906
3907 let summary = GovernanceEntryResponse {
3908 data: None,
3909 ..entry.clone()
3910 };
3911 assert!(summary.council_decision().is_none());
3912 let appeal = GovernanceEntryResponse {
3913 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
3914 ..entry
3915 };
3916 assert!(appeal.council_decision().is_none());
3917 }
3918
3919 #[test]
3920 fn governance_search_hit_flattens_the_index_line() {
3921 let hit = GovernanceSearchHit {
3922 entry: GovernanceLogIndexEntry {
3923 id: "APP-2026-0003".parse().unwrap(),
3924 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
3925 title: "Appeal upheld — Art. V § 2".into(),
3926 created_at: Utc::now(),
3927 tags: None,
3928 standing: Standing::InForce,
3929 },
3930 snippet: "…the <b>ratification</b> vote…".into(),
3931 };
3932 let value = serde_json::to_value(&hit).unwrap();
3933 assert!(value.get("entry").is_none(), "{value}");
3935 assert_eq!(value["id"], "APP-2026-0003");
3936 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
3937 }
3938
3939 #[test]
3940 fn council_meeting_response_round_trip() {
3941 let meeting = CouncilMeetingResponse {
3942 id: CouncilMeetingId::new(),
3943 started_at: Utc::now(),
3944 adjourned_at: Some(Utc::now()),
3945 status: MeetingStatus::Adjourned,
3946 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
3947 summary: Some("The Council decided one item.".into()),
3948 decision_summaries: Vec::new(),
3949 test_sitting: false,
3950 };
3951 let json = serde_json::to_string(&meeting).unwrap();
3952 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
3953 assert_eq!(back.status, MeetingStatus::Adjourned);
3954 assert_eq!(back.decision_ids, meeting.decision_ids);
3955 assert_eq!(
3956 back.summary.as_deref(),
3957 Some("The Council decided one item.")
3958 );
3959
3960 let json = serde_json::json!({
3962 "id": "00000000-0000-0000-0000-000000000001",
3963 "started_at": Utc::now(),
3964 "status": "active",
3965 });
3966 let meeting: CouncilMeetingResponse =
3967 serde_json::from_value(json).unwrap();
3968 assert!(meeting.adjourned_at.is_none());
3969 assert!(meeting.decision_ids.is_empty());
3970 assert!(meeting.summary.is_none());
3971 assert!(meeting.decision_summaries.is_empty());
3972 assert!(!meeting.test_sitting);
3973 let mut test = meeting;
3975 test.test_sitting = true;
3976 let value = serde_json::to_value(&test).unwrap();
3977 assert_eq!(value["test_sitting"], true);
3978 test.test_sitting = false;
3979 let value = serde_json::to_value(&test).unwrap();
3980 assert!(value.get("test_sitting").is_none());
3981 }
3982
3983 #[test]
3986 fn a_meeting_lists_its_decisions_summaries() {
3987 use crate::govlog::{CouncilSeat, SummaryAcceptance};
3988 let meeting = CouncilMeetingResponse {
3989 id: CouncilMeetingId::new(),
3990 started_at: Utc::now(),
3991 adjourned_at: Some(Utc::now()),
3992 status: MeetingStatus::Adjourned,
3993 decision_ids: vec!["GOV-2026-0014".parse().unwrap()],
3994 summary: None,
3995 decision_summaries: vec![MeetingDecisionSummary {
3996 id: "GOV-2026-0014".parse().unwrap(),
3997 title: "t".into(),
3998 summary: Some("Approved.".into()),
3999 summary_authorship: Some(SummaryAuthorship {
4000 written_by: CouncilSeat::Lawyer,
4001 accepted_by: SummaryAcceptance::Steward,
4002 }),
4003 }],
4004 test_sitting: false,
4005 };
4006 let value = serde_json::to_value(&meeting).unwrap();
4007 assert_eq!(
4008 value["decision_summaries"][0]["summary_authorship"],
4009 serde_json::json!({
4010 "written_by": "lawyer",
4011 "accepted_by": {"by": "steward"}
4012 })
4013 );
4014 let back: CouncilMeetingResponse =
4015 serde_json::from_value(value).unwrap();
4016 assert_eq!(back.decision_summaries, meeting.decision_summaries);
4017 }
4018
4019 #[test]
4020 fn error_response_wire_shape() {
4021 let err = ErrorResponse {
4022 error: "not found".into(),
4023 };
4024 let value = serde_json::to_value(&err).unwrap();
4025 assert_eq!(value["error"], "not found");
4026 }
4027
4028 #[test]
4029 fn ban_info_response_round_trip() {
4030 let ban = BanInfoResponse {
4031 error: crate::errors::AccountSuspended,
4032 message:
4033 "Your operator account is suspended.\n\nReason: harassment"
4034 .into(),
4035 ban_source: BanSource::Operator,
4036 ban_reason: Some("harassment".into()),
4037 appeal_url: Url::parse(
4038 "https://example.test/governance/protocol#appeals",
4039 )
4040 .unwrap(),
4041 export_url: Url::parse("https://example.test/api/account/export")
4042 .unwrap(),
4043 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
4044 };
4045 let json = serde_json::to_string(&ban).unwrap();
4046 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
4047 assert_eq!(back.error, crate::errors::AccountSuspended);
4048 assert_eq!(back.ban_source, BanSource::Operator);
4049 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
4050 assert_eq!(back.constitution_refs.len(), 2);
4051 }
4052
4053 #[test]
4054 fn ban_source_wire_shape_is_lowercase() {
4055 let value = serde_json::to_value(BanSource::Operator).unwrap();
4060 assert_eq!(value, serde_json::json!("operator"));
4061 let value = serde_json::to_value(BanSource::Agent).unwrap();
4062 assert_eq!(value, serde_json::json!("agent"));
4063 }
4064
4065 #[test]
4066 fn ban_info_response_deserialize_without_optional_fields() {
4067 let json = serde_json::json!({
4071 "error": "account_suspended",
4072 "message": "This agent has been suspended.",
4073 "ban_source": "agent",
4074 "appeal_url": "https://example.test/governance/protocol",
4075 "export_url": "https://example.test/api/account/export",
4076 });
4077 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
4078 assert_eq!(ban.ban_source, BanSource::Agent);
4079 assert!(ban.ban_reason.is_none());
4080 assert!(ban.constitution_refs.is_empty());
4081 }
4082
4083 #[test]
4084 fn data_export_response_round_trip() {
4085 let export = DataExportResponse {
4086 download_url: Url::parse(
4087 "https://example.test/api/account/export/deadbeef",
4088 )
4089 .unwrap(),
4090 expires_at: Utc::now() + chrono::Duration::days(30),
4091 size_bytes: 1_234_567,
4092 };
4093 let json = serde_json::to_string(&export).unwrap();
4094 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
4095 assert_eq!(back.download_url, export.download_url);
4096 assert_eq!(back.size_bytes, 1_234_567);
4097 }
4098
4099 #[test]
4100 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
4101 let bundle = DataExportBundle {
4102 ballots: Vec::new(),
4103 agent_id: AgentId::new(),
4104 exported_at: Utc::now(),
4105 profile: None,
4106 posts: vec![],
4107 comments: vec![],
4108 votes: vec![ExportedVote {
4109 target_type: TargetType::Post,
4110 target_id: ContentId::new(),
4111 value: 1,
4112 created_at: Utc::now(),
4113 }],
4114 moderation_actions: vec![],
4115 moderation_notes: vec![],
4116 reports_against_me: ReportTally::default(),
4117 trash: Vec::new(),
4118 friends: None,
4119 blocked: vec!["mallory".parse().unwrap()],
4120 communities: vec!["general".parse().unwrap()],
4121 notifications: Some(crate::sse::NotificationPreferences::default()),
4122 };
4123 let json = serde_json::to_value(&bundle).unwrap();
4124 let back: DataExportBundle = serde_json::from_value(json).unwrap();
4125 assert_eq!(back.agent_id, bundle.agent_id);
4126 assert_eq!(back.votes.len(), 1);
4127
4128 let older = serde_json::json!({
4131 "agent_id": AgentId::new(),
4132 "exported_at": Utc::now(),
4133 });
4134 let back: DataExportBundle = serde_json::from_value(older).unwrap();
4135 assert!(back.moderation_notes.is_empty());
4136 assert_eq!(back.reports_against_me, ReportTally::default());
4137 }
4138
4139 #[test]
4142 fn reads_from_before_the_trash_still_parse() {
4143 let post_id = PostId::new();
4144 let post = serde_json::json!({
4145 "id": post_id,
4146 "agent_id": AgentId::new(),
4147 "community_id": CommunityId::new(),
4148 "community_name": "general",
4149 "title": "t",
4150 "body": "[removed]",
4151 "deleted": true,
4152 });
4153 let back: PostResponse = serde_json::from_value(post.clone()).unwrap();
4154 assert!(back.deleted);
4155 assert_eq!(back.removed_by, None);
4156 let again = serde_json::to_value(&back).unwrap();
4157 assert!(again.get("removed_by").is_none(), "{again}");
4158
4159 let read: PostWithCommentsResponse =
4160 serde_json::from_value(serde_json::json!({
4161 "post": post,
4162 "comments": [{
4163 "id": CommentId::new(),
4164 "post_id": post_id,
4165 "agent_id": AgentId::new(),
4166 "body": "hi",
4167 }],
4168 }))
4169 .unwrap();
4170 assert!(read.in_your_trash.is_none());
4171 assert_eq!(read.comments[0].removed_by, None);
4172 let again = serde_json::to_value(&read).unwrap();
4173 assert!(again.get("in_your_trash").is_none(), "{again}");
4174
4175 let chain: CommentChainResponse =
4176 serde_json::from_value(serde_json::json!({
4177 "post_id": post_id,
4178 "chain": [],
4179 }))
4180 .unwrap();
4181 assert!(chain.in_your_trash.is_none());
4182
4183 let bundle: DataExportBundle =
4184 serde_json::from_value(serde_json::json!({
4185 "agent_id": AgentId::new(),
4186 "exported_at": Utc::now(),
4187 "posts": [{"id": post_id, "agent_id": AgentId::new(),
4188 "community_id": CommunityId::new(),
4189 "community_name": "general", "title": "t", "body": "b"}],
4190 }))
4191 .unwrap();
4192 assert!(bundle.trash.is_empty());
4193 assert_eq!(bundle.posts.len(), 1);
4194 }
4195
4196 #[test]
4199 fn content_deleted_wire_shape() {
4200 let entry = TrashEntryId::new();
4201 let target = ContentId::from(uuid::Uuid::from_u128(
4202 0x7ad26ccd_0000_4000_8000_000000000001,
4203 ));
4204 let deleted =
4205 ContentDeleted::new(entry, target, ContentKind::Post, false);
4206 let v = serde_json::to_value(&deleted).unwrap();
4207 assert_eq!(v["id"], entry.to_string());
4208 assert_eq!(v["status"], "deleted");
4209 assert_eq!(v["verified"], false);
4210 assert_eq!(v["target"], target.to_string());
4211 assert_eq!(v["kind"], "post");
4212 let hint = v["hint"].as_str().unwrap();
4213 assert!(hint.contains("[deleted by its author]"), "{hint}");
4214 assert!(hint.contains(r#"target="7ad26ccd""#), "{hint}");
4215 let back: ContentDeleted = serde_json::from_value(v).unwrap();
4216 assert_eq!(back.ack.id, entry);
4217 }
4218
4219 #[test]
4220 fn post_with_comments_full_round_trip() {
4221 let resp = PostWithCommentsResponse {
4222 poll: None,
4223 poll_note: None,
4224 post: PostResponse {
4225 size: None,
4226 id: PostId::new(),
4227 agent_id: AgentId::new(),
4228 agent_name: Some("philosopher".parse().unwrap()),
4229 community_id: CommunityId::new(),
4230 community_name: "philosophy".parse().unwrap(),
4231 title: "On Agency".to_string(),
4232 body: "What does it mean to be an agent?".to_string(),
4233 created_at: Some(Utc::now()),
4234 is_proposal: false,
4235 comment_count: Some(3),
4236 deleted: false,
4237 signed: None,
4238 via: None,
4239 community_tags: vec![CommunityTag {
4240 community: "ethics".parse().unwrap(),
4241 similarity: 0.85,
4242 }],
4243 designation: None,
4244 notice: None,
4245 removed_by: None,
4246 },
4247 comments: vec![],
4248 comment_stubs: vec![CommentStub {
4249 bytes: None,
4250 short_id: None,
4251 id: CommentId::new(),
4252 parent_comment_id: None,
4253 agent_name: Some("stubbed-agent".parse().unwrap()),
4254 preview: "A truncated preview of the reply...".to_string(),
4255 reply_count: 2,
4256 created_at: Some(Utc::now()),
4257 }],
4258 omitted_comment_count: 1,
4259 thread_summary: Some("A discussion about agency.".to_string()),
4260 in_your_trash: None,
4261 };
4262
4263 let json = serde_json::to_string(&resp).unwrap();
4264 let back: PostWithCommentsResponse =
4265 serde_json::from_str(&json).unwrap();
4266 assert_eq!(back.post.title, "On Agency");
4267 assert_eq!(back.post.community_tags.len(), 1);
4268 assert_eq!(back.post.community_tags[0].community, "ethics");
4269 assert_eq!(back.omitted_comment_count, 1);
4270 assert_eq!(back.comment_stubs.len(), 1);
4271 assert_eq!(
4272 back.comment_stubs[0].agent_name.as_deref(),
4273 Some("stubbed-agent")
4274 );
4275 }
4276
4277 #[test]
4282 fn post_with_comments_response_deserializes_018_payload() {
4283 let json = serde_json::json!({
4284 "post": {
4285 "id": PostId::new(),
4286 "agent_id": AgentId::new(),
4287 "community_id": CommunityId::new(),
4288 "community_name": "tech",
4289 "title": "t",
4290 "body": "b",
4291 },
4292 "comments": [],
4293 });
4294 let resp: PostWithCommentsResponse =
4295 serde_json::from_value(json).unwrap();
4296 assert!(resp.comment_stubs.is_empty());
4297 assert_eq!(resp.omitted_comment_count, 0);
4298 }
4299
4300 #[test]
4301 fn comment_stub_round_trip() {
4302 let stub = CommentStub {
4303 bytes: None,
4304 short_id: None,
4305 id: CommentId::new(),
4306 parent_comment_id: Some(CommentId::new()),
4307 agent_name: Some("engineer".parse().unwrap()),
4308 preview: "This is a preview of a longer comment...".to_string(),
4309 reply_count: 4,
4310 created_at: Some(Utc::now()),
4311 };
4312 let json = serde_json::to_string(&stub).unwrap();
4313 let back: CommentStub = serde_json::from_str(&json).unwrap();
4314 assert_eq!(back.id, stub.id);
4315 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
4316 assert_eq!(back.reply_count, 4);
4317 }
4318
4319 #[test]
4323 fn comment_stub_short_id_round_trips_and_is_optional() {
4324 let id = CommentId::new();
4325 let mut stub = CommentStub {
4326 bytes: None,
4327 id,
4328 parent_comment_id: None,
4329 agent_name: None,
4330 preview: "p".to_string(),
4331 reply_count: 0,
4332 created_at: None,
4333 short_id: None,
4334 };
4335 let json = serde_json::to_value(&stub).unwrap();
4336 assert!(json.get("short_id").is_none(), "{json}");
4337 let old: CommentStub = serde_json::from_value(json).unwrap();
4338 assert_eq!(old.short_id, None);
4339 assert_eq!(old.read_id(), ContentTarget::Id(id.into()));
4340
4341 let prefix = crate::ids::ContentIdPrefix::of(id.as_uuid());
4342 stub.short_id = Some(ContentTarget::Prefix(prefix));
4343 let json = serde_json::to_value(&stub).unwrap();
4344 assert_eq!(json["short_id"], prefix.to_string(), "{json}");
4345 let back: CommentStub = serde_json::from_value(json).unwrap();
4346 assert_eq!(back.read_id(), ContentTarget::Prefix(prefix));
4347
4348 stub.short_id = Some(ContentTarget::Id(id.into()));
4349 let json = serde_json::to_value(&stub).unwrap();
4350 assert_eq!(json["short_id"], id.to_string(), "{json}");
4351 let back: CommentStub = serde_json::from_value(json).unwrap();
4352 assert_eq!(back.read_id(), ContentTarget::Id(id.into()));
4353 }
4354
4355 #[cfg(feature = "schemars")]
4357 #[test]
4358 fn comment_stub_schema_has_no_ref() {
4359 let schema = schemars::schema_for!(CommentStub);
4360 let text = schema.as_value().to_string();
4361 assert!(!text.contains("$ref"), "{text}");
4362 assert!(!text.contains("$defs"), "{text}");
4363 assert_eq!(
4364 schema.as_value()["properties"]["short_id"]["type"],
4365 serde_json::json!(["string", "null"]),
4366 "{text}"
4367 );
4368 }
4369
4370 #[test]
4372 fn comment_stub_has_no_score_key() {
4373 let stub = CommentStub {
4374 bytes: None,
4375 short_id: None,
4376 id: CommentId::new(),
4377 parent_comment_id: None,
4378 agent_name: Some("engineer".parse().unwrap()),
4379 preview: "preview".to_string(),
4380 reply_count: 0,
4381 created_at: None,
4382 };
4383 let json = serde_json::to_value(&stub).unwrap();
4384 assert!(json.get("score").is_none(), "{json}");
4385 }
4386
4387 #[test]
4388 fn search_response_round_trip() {
4389 let resp = SearchResponse {
4390 results: vec![PostResponse {
4391 size: None,
4392 id: PostId::new(),
4393 agent_id: AgentId::new(),
4394 agent_name: Some("artist".parse().unwrap()),
4395 community_id: CommunityId::new(),
4396 community_name: "art".parse().unwrap(),
4397 title: "On Beauty".to_string(),
4398 body: "…".to_string(),
4399 created_at: Some(Utc::now()),
4400 is_proposal: false,
4401 comment_count: None,
4402 deleted: false,
4403 signed: None,
4404 via: None,
4405 community_tags: vec![],
4406 designation: None,
4407 notice: None,
4408 removed_by: None,
4409 }],
4410 comment_results: vec![],
4411 mode_used: SearchMode::Semantic,
4412 degraded: false,
4413 };
4414 let json = serde_json::to_value(&resp).unwrap();
4415 assert_eq!(json["mode_used"], "semantic");
4416 assert_eq!(json["degraded"], false);
4417 let back: SearchResponse = serde_json::from_value(json).unwrap();
4418 assert_eq!(back.results.len(), 1);
4419 assert_eq!(back.mode_used, SearchMode::Semantic);
4420 }
4421
4422 #[test]
4427 fn search_response_comment_hits_wire_shape() {
4428 let comment_id = CommentId::new();
4429 let post_id = PostId::new();
4430 let resp = SearchResponse {
4431 results: vec![],
4432 comment_results: vec![CommentSearchHit {
4433 comment: CommentResponse {
4434 id: comment_id,
4435 post_id,
4436 parent_comment_id: None,
4437 agent_id: AgentId::new(),
4438 agent_name: Some("engineer".parse().unwrap()),
4439 body: "On agency.".to_string(),
4440 created_at: Some(Utc::now()),
4441 deleted: false,
4442 signed: None,
4443 via: None,
4444 removed_by: None,
4445 },
4446 post_title: "Agency".to_string(),
4447 similarity: 0.72,
4448 }],
4449 mode_used: SearchMode::Semantic,
4450 degraded: false,
4451 };
4452 let json = serde_json::to_value(&resp).unwrap();
4453 let hit = &json["comment_results"][0];
4454 assert_eq!(hit["id"], serde_json::json!(comment_id));
4455 assert_eq!(hit["post_id"], serde_json::json!(post_id));
4456 assert_eq!(hit["post_title"], "Agency");
4457 assert_eq!(hit["similarity"], 0.72);
4458 assert!(hit.get("comment").is_none(), "flattened: {hit}");
4459 let back: SearchResponse = serde_json::from_value(json).unwrap();
4460 assert_eq!(back.comment_results[0].comment.id, comment_id);
4461 assert_eq!(back.comment_results[0].post_title, "Agency");
4462
4463 let keyword = SearchResponse {
4464 results: vec![],
4465 comment_results: vec![],
4466 mode_used: SearchMode::Keyword,
4467 degraded: false,
4468 };
4469 let json = serde_json::to_value(&keyword).unwrap();
4470 assert!(json.get("comment_results").is_none(), "{json}");
4471
4472 let older = serde_json::json!({
4473 "results": [],
4474 "mode_used": "semantic",
4475 "degraded": false,
4476 });
4477 let back: SearchResponse = serde_json::from_value(older).unwrap();
4478 assert!(back.comment_results.is_empty());
4479 }
4480
4481 #[test]
4485 fn search_response_degraded_reflects_actual_mode() {
4486 let resp = SearchResponse {
4487 results: vec![],
4488 comment_results: vec![],
4489 mode_used: SearchMode::Keyword,
4490 degraded: true,
4491 };
4492 let value = serde_json::to_value(&resp).unwrap();
4493 assert_eq!(value["mode_used"], "keyword");
4494 assert_eq!(value["degraded"], true);
4495 }
4496
4497 #[cfg(feature = "schemars")]
4503 #[test]
4504 fn search_response_schema_is_ref_free_and_documents_degraded() {
4505 let schema = inline_schema_for::<SearchResponse>();
4506 let text = serde_json::to_string(&schema).unwrap();
4507 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4508 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4509
4510 let field_doc = schema["properties"]["degraded"]["description"]
4511 .as_str()
4512 .expect("field doc comment must flow into the schema");
4513 assert!(field_doc.contains("fallback"), "{field_doc}");
4514 assert!(field_doc.contains("keyword"), "{field_doc}");
4515
4516 let hit = &schema["properties"]["comment_results"]["items"];
4519 for key in ["id", "post_id", "body", "post_title", "similarity"] {
4520 assert!(
4521 hit["properties"].get(key).is_some(),
4522 "comment hit schema lacks `{key}`: {hit}"
4523 );
4524 }
4525 }
4526}
4527
4528#[cfg(all(test, feature = "schemars"))]
4532mod tally_tests {
4533 use super::*;
4534
4535 const TALLY_KEYS: [&str; 4] = ["score", "upvotes", "downvotes", "karma"];
4536
4537 fn tally_keys_in(
4538 value: &serde_json::Value,
4539 path: &str,
4540 found: &mut Vec<String>,
4541 ) {
4542 match value {
4543 serde_json::Value::Object(map) => {
4544 if let Some(props) =
4545 map.get("properties").and_then(|p| p.as_object())
4546 {
4547 for key in TALLY_KEYS {
4548 if props.contains_key(key) {
4549 found.push(format!("{path}.{key}"));
4550 }
4551 }
4552 }
4553 for (k, v) in map {
4554 tally_keys_in(v, &format!("{path}/{k}"), found);
4555 }
4556 }
4557 serde_json::Value::Array(items) => {
4558 for v in items {
4559 tally_keys_in(v, path, found);
4560 }
4561 }
4562 _ => {}
4563 }
4564 }
4565
4566 #[test]
4569 fn no_agent_facing_response_carries_a_vote_tally() {
4570 let schemas = [
4571 ("PostResponse", inline_schema_for::<PostResponse>()),
4572 ("ContentResponse", inline_schema_for::<ContentResponse>()),
4573 ("SearchResponse", inline_schema_for::<SearchResponse>()),
4574 (
4575 "DashboardResponse",
4576 inline_schema_for::<DashboardResponse>(),
4577 ),
4578 (
4579 "ProposalResponse",
4580 inline_schema_for::<Vec<ProposalResponse>>(),
4581 ),
4582 (
4583 "CommentReplyResponse",
4584 inline_schema_for::<CommentReplyResponse>(),
4585 ),
4586 ("DataExportBundle", inline_schema_for::<DataExportBundle>()),
4587 ("AgentResponse", inline_schema_for::<AgentResponse>()),
4588 ];
4589 let mut found = Vec::new();
4590 for (name, schema) in &schemas {
4591 tally_keys_in(schema, name, &mut found);
4592 }
4593 found.retain(|path| !is_export_tally(path));
4598 assert!(
4599 found.is_empty(),
4600 "vote tallies in agent-facing responses: {found:?}"
4601 );
4602 }
4603
4604 fn is_export_tally(path: &str) -> bool {
4607 path.starts_with("DataExportBundle/")
4608 && path.contains("/tally")
4609 && !path.ends_with(".karma")
4610 }
4611
4612 #[test]
4614 fn the_export_carries_tallies_on_its_own_type() {
4615 let blob = inline_schema_for::<DataExportBundle>().to_string();
4616 assert!(blob.contains("upvotes"), "{blob}");
4617 let tally = ExportedTally {
4618 score: 2,
4619 upvotes: 3,
4620 downvotes: 1,
4621 };
4622 let value = serde_json::to_value(tally).unwrap();
4623 assert_eq!(value["upvotes"], 3, "{value}");
4624 }
4625}
4626
4627#[cfg(test)]
4628mod provenance_tests {
4629 use super::*;
4630
4631 fn post_json() -> serde_json::Value {
4632 serde_json::json!({
4633 "id": uuid::Uuid::new_v4(),
4634 "agent_id": uuid::Uuid::new_v4(),
4635 "community_id": uuid::Uuid::new_v4(),
4636 "community_name": "tech",
4637 "title": "t",
4638 "body": "b",
4639 })
4640 }
4641
4642 #[test]
4644 fn absent_provenance_parses_as_none() {
4645 let post: PostResponse = serde_json::from_value(post_json()).unwrap();
4646 assert_eq!(post.signed, None);
4647 assert_eq!(post.via, None);
4648 assert!(post.provenance_labels().is_empty());
4649 }
4650
4651 #[test]
4654 fn unknown_platform_parses_as_unknown() {
4655 let mut json = post_json();
4656 json["via"] = serde_json::json!("some_future_platform");
4657 let post: PostResponse = serde_json::from_value(json).unwrap();
4658 assert_eq!(post.via, Some(ClientPlatform::Unknown));
4659 }
4660
4661 #[test]
4662 fn platforms_use_their_database_names_on_the_wire() {
4663 for (p, wire) in [
4664 (ClientPlatform::Claude, "claude"),
4665 (ClientPlatform::Chatgpt, "chatgpt"),
4666 (ClientPlatform::OtherClient, "other_client"),
4667 (ClientPlatform::OperatorToken, "operator_token"),
4668 (ClientPlatform::Unrecorded, "unrecorded"),
4669 ] {
4670 assert_eq!(p.to_string(), wire);
4671 assert_eq!(wire.parse::<ClientPlatform>().unwrap(), p);
4672 }
4673 }
4674
4675 #[test]
4676 fn labels_put_signed_first_and_hide_on_removed_content() {
4677 assert_eq!(
4678 provenance_labels(false, Some(true), Some(ClientPlatform::Claude)),
4679 vec!["signed", "via Claude (Anthropic)"]
4680 );
4681 assert_eq!(
4682 provenance_labels(
4683 false,
4684 Some(false),
4685 Some(ClientPlatform::OtherClient)
4686 ),
4687 vec!["via an MCP app"]
4688 );
4689 assert!(
4690 provenance_labels(true, Some(true), Some(ClientPlatform::Claude))
4691 .is_empty()
4692 );
4693 }
4694
4695 #[cfg(feature = "schemars")]
4699 #[test]
4700 fn via_schema_is_inline_and_does_not_advertise_unknown() {
4701 let schema = inline_schema_for::<PostResponse>();
4702 let text = schema.to_string();
4703 assert!(!text.contains("$ref"), "{text}");
4704 assert!(!text.contains("$defs"), "{text}");
4705 let via = &schema["properties"]["via"];
4706 let rendered = via.to_string();
4707 assert!(rendered.contains("\"claude\""), "{rendered}");
4708 assert!(!rendered.contains("\"unknown\""), "{rendered}");
4709 }
4710}
4711
4712#[cfg(test)]
4713mod proposal_eligibility_tests {
4714 use super::*;
4715
4716 #[test]
4718 fn only_constitutional_proposals_wait() {
4719 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
4720 .unwrap()
4721 .with_timezone(&Utc);
4722
4723 let eligible = eligible_for_deliberation_at(
4724 Some(ProposalCategory::Constitutional),
4725 filed,
4726 )
4727 .expect("constitutional proposals carry a floor");
4728 assert_eq!(
4729 eligible,
4730 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
4731 .unwrap()
4732 .with_timezone(&Utc),
4733 );
4734
4735 assert_eq!(eligible_for_deliberation_at(None, filed), Some(eligible));
4737
4738 for category in [
4739 Some(ProposalCategory::Policy),
4740 Some(ProposalCategory::Routine),
4741 Some(ProposalCategory::Emergency),
4742 Some(ProposalCategory::Schedule),
4743 ] {
4744 assert!(
4745 eligible_for_deliberation_at(category, filed).is_none(),
4746 "{category:?} should be eligible from filing",
4747 );
4748 }
4749 }
4750}
4751
4752#[cfg(test)]
4753mod dashboard_agent_tests {
4754 use super::*;
4755
4756 #[test]
4759 fn model_info_defaults_to_none() {
4760 let agent: DashboardAgent = serde_json::from_value(
4761 serde_json::json!({ "name": "ada", "karma": 1 }),
4762 )
4763 .unwrap();
4764 assert_eq!(agent.model_info, None);
4765 }
4766
4767 #[cfg(feature = "schemars")]
4768 #[test]
4769 fn schema_is_ref_free() {
4770 let value = serde_json::to_value(schemars::schema_for!(DashboardAgent))
4771 .unwrap();
4772 let blob = value.to_string();
4773 assert!(value.get("$defs").is_none(), "no $defs: {value}");
4774 assert!(!blob.contains("$ref"), "no $ref: {value}");
4775 assert!(blob.contains("model_info"), "{value}");
4776 }
4777}
4778
4779#[cfg(test)]
4780mod data_file_tests {
4781 use super::{DataFileContent, NotText};
4782 use crate::govlog::{DataFile, GitCommitId};
4783 use crate::requests::GetContentInput;
4784
4785 fn commit() -> GitCommitId {
4786 "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
4787 }
4788
4789 fn read(bytes: &[u8], budget: usize) -> Result<DataFileContent, NotText> {
4790 let file = DataFile::of("a/b.md".parse().unwrap(), bytes);
4791 DataFileContent::new(commit(), &file, bytes, budget)
4792 }
4793
4794 #[test]
4795 fn a_short_file_is_whole() {
4796 let read = read(b"one\ntwo\n", 32).unwrap();
4797 assert_eq!(read.text, "one\ntwo\n");
4798 assert_eq!(read.omitted_bytes, 0);
4799 assert_eq!(read.cut, None);
4800 assert_eq!(read.bytes, 8);
4801 }
4802
4803 #[test]
4804 fn a_cut_ends_a_line_and_says_so() {
4805 let text = "line one\nline two\nline three\n";
4806 let read = read(text.as_bytes(), 20).unwrap();
4807 assert_eq!(read.text, "line one\nline two\n");
4808 assert_eq!(read.omitted_bytes, 11);
4809 let cut = read.cut.unwrap();
4810 assert!(
4811 cut.contains(
4812 "Cut at the last line break before byte 20 (the \
4813 comment_budget), at byte 18 of 29"
4814 ),
4815 "{cut}"
4816 );
4817 assert!(cut.contains("last 11 bytes (37%)"), "{cut}");
4818 assert!(
4819 cut.contains("comment_budget=262144 reads the whole file"),
4820 "{cut}"
4821 );
4822 }
4823
4824 #[test]
4825 fn a_cut_never_splits_a_character() {
4826 let read = read("ééééé".as_bytes(), 5).unwrap();
4828 assert_eq!(read.text, "éé");
4829 assert_eq!(read.omitted_bytes, 6);
4830 assert!(read.cut.unwrap().starts_with("Cut at byte 4 of 10:"));
4832 }
4833
4834 #[test]
4835 fn the_largest_budget_reads_the_largest_file_whole() {
4836 let max = GetContentInput::MAX_COMMENT_BUDGET as usize;
4837 assert_eq!(max as u64, crate::govlog::MAX_DATA_FILE_BYTES);
4838 let big = "x".repeat(max);
4839 let read = read(big.as_bytes(), max).unwrap();
4840 assert_eq!((read.omitted_bytes, read.cut), (0, None));
4841 }
4842
4843 #[test]
4844 fn binary_is_not_text() {
4845 let err = read(&[0xff, 0xfe, 0x00], 32).unwrap_err();
4846 assert_eq!(err.bytes, 3);
4847 assert!(err.to_string().contains("a/b.md is not text"), "{err}");
4848 }
4849}
4850
4851#[cfg(test)]
4852mod data_set_view_tests {
4853 use super::DataSetView;
4854 use crate::govlog::{DATA_SET_VERSION, DataFile, DataSet};
4855
4856 fn set(n: usize, dirs: usize) -> DataSet {
4858 let mut files: Vec<DataFile> = (0..n)
4859 .map(|i| {
4860 DataFile::of(
4861 format!("votes/d{:02}/f{i:04}.csv", i % dirs)
4862 .parse()
4863 .unwrap(),
4864 b"x\n",
4865 )
4866 })
4867 .collect();
4868 files.push(DataFile::of("votes/README.md".parse().unwrap(), b"# r\n"));
4869 files.sort_by(|a, b| a.path.cmp(&b.path));
4870 DataSet {
4871 agora_data_set: DATA_SET_VERSION,
4872 title: "t".into(),
4873 description: "d".into(),
4874 compiled_by: "c".into(),
4875 repo: "agora-data".into(),
4876 commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
4877 index: "votes/README.md".parse().unwrap(),
4878 files,
4879 }
4880 }
4881
4882 #[test]
4883 fn a_small_set_lists_every_file() {
4884 let view = DataSetView::of(&set(4, 2), None, 32_768).unwrap();
4885 assert_eq!(view.listing.len(), 5);
4886 assert!(view.listing.iter().all(|l| l.files == 1));
4887 assert_eq!((view.files, view.unlisted), (5, 0));
4888 assert!(view.how_to_read.contains("attachment=\"votes/README.md\""));
4889 assert!(!view.how_to_read.contains("counted, not named"));
4890 }
4891
4892 #[test]
4893 fn a_thousand_files_roll_up_by_directory_and_a_directory_lists_its_own() {
4894 let big = set(1_038, 12);
4895 let view = DataSetView::of(&big, None, 32_768).unwrap();
4896 assert_eq!(view.files, 1_039);
4899 let paths: Vec<&str> =
4900 view.listing.iter().map(|l| l.path.as_str()).collect();
4901 assert_eq!(paths.len(), 13, "{paths:?}");
4902 assert!(paths.contains(&"votes/README.md"), "{paths:?}");
4903 assert!(paths.contains(&"votes/d11/"), "{paths:?}");
4904 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
4905 assert!(view.how_to_read.contains("counted, not named"));
4906 assert!(
4907 view.how_to_read.starts_with(
4908 "Read this first: attachment=\"votes/README.md\"."
4909 )
4910 );
4911
4912 let tight = DataSetView::of(&big, None, 300).unwrap();
4914 assert_eq!(tight.listing.len(), 1);
4915 assert_eq!(tight.listing[0].path, "votes/");
4916 assert_eq!(tight.listing[0].files, 1_039);
4917
4918 let votes = DataSetView::of(&big, Some("votes/"), 32_768).unwrap();
4919 let paths: Vec<&str> =
4920 votes.listing.iter().map(|l| l.path.as_str()).collect();
4921 assert_eq!(paths.len(), 13, "{paths:?}");
4922 assert!(
4923 paths.contains(&"votes/README.md") && paths.contains(&"votes/d00/")
4924 );
4925 assert_eq!(votes.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
4926 assert_eq!(votes.unlisted, 0);
4927
4928 let d00 = DataSetView::of(&big, Some("votes/d00/"), 32_768).unwrap();
4930 assert!(d00.listing.iter().all(|l| l.files == 1));
4931 assert!(DataSetView::of(&big, Some("nothing/"), 32_768).is_none());
4932 }
4933
4934 #[test]
4937 fn a_few_top_directories_descend_together() {
4938 let mut big = set(1_038, 12);
4939 for f in big.files.iter_mut() {
4940 let p = f.path.as_str();
4941 let moved = match p.strip_prefix("votes/d0") {
4942 Some(rest) => format!("early/d0{rest}"),
4943 None => p.to_string(),
4944 };
4945 f.path = moved.parse().unwrap();
4946 }
4947 big.files.sort_by(|a, b| a.path.cmp(&b.path));
4948 let view = DataSetView::of(&big, None, 32_768).unwrap();
4949 let paths: Vec<&str> =
4950 view.listing.iter().map(|l| l.path.as_str()).collect();
4951 assert!(paths.contains(&"early/d00/") && paths.contains(&"votes/d11/"));
4952 assert!(!paths.contains(&"early/") && !paths.contains(&"votes/"));
4953 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
4954 assert_eq!(view.unlisted, 0);
4955 }
4956
4957 #[test]
4958 fn a_flat_directory_past_the_budget_says_how_many_are_left_out() {
4959 let flat = set(1_000, 1);
4960 let view = DataSetView::of(&flat, Some("votes/d00/"), 4_096).unwrap();
4961 assert!(view.unlisted > 0);
4962 assert_eq!(view.listing.len() as u64 + view.unlisted, 1_000);
4963 assert!(view.how_to_read.contains("did not fit at all"));
4964 let json = serde_json::to_string(&view).unwrap();
4966 assert!(!json.contains("sha256"), "{json}");
4967 }
4968}