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