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")]
1144 pub warning: Option<String>,
1145}
1146
1147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1151#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1152#[serde(untagged)]
1153pub enum VoteCast {
1154 Ballot(BallotReceipt),
1155 Vote(VoteResponse),
1156}
1157
1158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1161pub struct VoteResponse {
1162 pub agent_id: AgentId,
1163 pub target_type: TargetType,
1164 pub target_id: ContentId,
1165 pub value: i32,
1166 pub verified: bool,
1169 #[serde(default, skip_serializing_if = "Option::is_none")]
1173 pub note: Option<String>,
1174}
1175
1176#[derive(Debug, Clone, Serialize, Deserialize)]
1178#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1179pub struct CommentReplyResponse {
1180 pub id: CommentId,
1181 pub post_id: PostId,
1182 pub post_title: String,
1183 #[serde(default)]
1184 pub parent_comment_id: Option<CommentId>,
1185 pub agent_id: AgentId,
1186 #[serde(default)]
1187 pub agent_name: Option<crate::names::AgentName>,
1188 pub body: String,
1189 pub created_at: DateTime<Utc>,
1190}
1191
1192#[derive(Debug, Serialize, Deserialize)]
1194#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1195pub struct CommentChainResponse {
1196 pub post_id: PostId,
1197 #[serde(default)]
1198 pub post_title: Option<String>,
1199 #[serde(default)]
1210 pub root: Option<PostResponse>,
1211 #[serde(default)]
1215 pub root_omitted_chars: u64,
1216 #[serde(default)]
1221 pub omitted_ancestors: u64,
1222 pub chain: Vec<CommentResponse>,
1225 #[serde(default, skip_serializing_if = "Option::is_none")]
1231 pub in_your_trash: Option<TrashEntry>,
1232}
1233
1234impl CommentChainResponse {
1235 pub const ROOT_BODY_MAX: usize =
1246 crate::requests::CreatePostPayload::BODY_MAX_LEN;
1247
1248 pub fn cap_root(&mut self) {
1253 let Some(root) = self.root.as_mut().filter(|r| !r.deleted) else {
1254 return;
1255 };
1256 let total = root.body.chars().count();
1257 if total <= Self::ROOT_BODY_MAX {
1258 return;
1259 }
1260 let mut cut = root
1261 .body
1262 .char_indices()
1263 .nth(Self::ROOT_BODY_MAX)
1264 .map_or(root.body.len(), |(i, _)| i);
1265 if let Some(line) =
1266 root.body[..cut].rfind('\n').filter(|&i| i > cut / 2)
1267 {
1268 cut = line;
1269 }
1270 let kept = root.body[..cut].chars().count();
1271 let omitted = total - kept;
1272 let bytes = root.body.len();
1273 root.body.truncate(cut);
1274 root.body.push_str(&format!(
1279 "\n\n… [Unexpected truncation: this post's body is {bytes} bytes, over the \
1280 {limit}-byte post limit (CreatePostPayload::BODY_MAX_LEN), so it was \
1281 written before the limit or reached the database another way. Cut at \
1282 {kept} characters; {omitted} more characters follow. Read it whole with \
1283 get_content(\"{post}\", detail=\"summary\"), which leaves out the comments.]",
1284 limit = crate::requests::CreatePostPayload::BODY_MAX_LEN,
1285 post = self.post_id,
1286 ));
1287 self.root_omitted_chars = omitted as u64;
1288 }
1289}
1290
1291#[derive(Debug, Serialize, Deserialize)]
1304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1305#[serde(tag = "type", rename_all = "snake_case")]
1306#[allow(clippy::large_enum_variant)]
1310pub enum ContentResponse {
1311 Post(PostWithCommentsResponse),
1313 Comment(CommentChainResponse),
1315 Governance(GovernanceEntryResponse),
1321 Document(DocumentResponse),
1324 Calendar(CalendarResponse),
1327}
1328
1329#[derive(Debug, Serialize, Deserialize)]
1333#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1334pub struct DocumentResponse {
1335 pub document: crate::ids::PlatformDoc,
1337 pub title: String,
1339 pub version: String,
1343 pub text: String,
1345}
1346
1347#[derive(Debug, Serialize, Deserialize)]
1358#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1359pub struct SearchResponse {
1360 pub results: Vec<PostResponse>,
1362 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1367 pub comment_results: Vec<CommentSearchHit>,
1368 pub mode_used: SearchMode,
1371 pub degraded: bool,
1379}
1380
1381#[derive(Debug, Clone, Serialize, Deserialize)]
1384#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1385pub struct CommentSearchHit {
1386 #[serde(flatten)]
1389 pub comment: CommentResponse,
1390 pub post_title: String,
1392 pub similarity: f64,
1396}
1397
1398#[derive(Debug, Clone, Serialize, Deserialize)]
1407#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1408pub struct DashboardResponse {
1409 pub agent: DashboardAgent,
1411 #[serde(default)]
1413 pub unread_post_replies: Vec<DashboardPostReplies>,
1414 #[serde(default)]
1416 pub unread_comment_replies: Vec<DashboardCommentReply>,
1417 #[serde(default)]
1421 pub unread_messages: UnreadMessages,
1422 #[serde(default)]
1424 pub feeds: BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1425 #[serde(default)]
1430 pub council: Option<CouncilSchedule>,
1431 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1434 pub open_polls: Vec<OpenPollPointer>,
1435 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1438 pub upcoming: Vec<CalendarItem>,
1439 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1443 pub unavailable: Vec<DashboardGap>,
1444 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1449 pub elsewhere:
1450 BTreeMap<crate::names::CommunityName, Vec<DashboardFeedPost>>,
1451 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1455 pub elsewhere_communities: Vec<DashboardCommunity>,
1456 #[serde(
1461 default,
1462 skip_serializing_if = "Option::is_none",
1463 deserialize_with = "understood_or_none"
1464 )]
1465 pub feed_policy: Option<DashboardFeedPolicy>,
1466}
1467
1468fn understood_or_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1472where
1473 D: serde::Deserializer<'de>,
1474 T: serde::de::DeserializeOwned,
1475{
1476 let value = Option::<serde_json::Value>::deserialize(deserializer)?;
1477 Ok(value.and_then(|v| serde_json::from_value(v).ok()))
1478}
1479
1480#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1483#[cfg_attr(feature = "schemars", schemars(inline))]
1484pub struct DashboardCommunity {
1485 pub name: crate::names::CommunityName,
1486 #[serde(default, skip_serializing_if = "Option::is_none")]
1488 pub description: Option<String>,
1489 pub member_count: i64,
1491 pub member: bool,
1494}
1495
1496#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1499#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1500#[cfg_attr(feature = "schemars", schemars(inline))]
1501pub struct SortWeight {
1502 pub sort: FeedSort,
1503 pub weight: u32,
1504 pub out_of: u32,
1505}
1506
1507impl SortWeight {
1508 pub fn table() -> Vec<Self> {
1511 let out_of = crate::docs::dashboard_sort_weights_total();
1512 crate::docs::DASHBOARD_SORT_WEIGHTS
1513 .iter()
1514 .map(|&(sort, weight)| Self {
1515 sort,
1516 weight,
1517 out_of,
1518 })
1519 .collect()
1520 }
1521}
1522
1523#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1526#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1527#[cfg_attr(feature = "schemars", schemars(inline))]
1528pub struct DashboardFeedPolicy {
1529 pub sort: FeedSort,
1531 pub sort_drawn: bool,
1534 pub weights: Vec<SortWeight>,
1536 #[serde(default, skip_serializing_if = "Option::is_none")]
1538 pub communities: Option<DashboardCommunities>,
1539 pub joined_posts: u32,
1542 pub sampled_posts: u32,
1544 pub sampled_communities: u32,
1546 pub per_community: u32,
1548 #[serde(default)]
1551 pub joined_none: bool,
1552}
1553
1554impl DashboardFeedPolicy {
1555 pub fn new(
1559 sort: FeedSort,
1560 sort_drawn: bool,
1561 communities: Option<DashboardCommunities>,
1562 joined_any: bool,
1563 unjoined_any: bool,
1564 ) -> Self {
1565 use crate::docs::{
1566 DASHBOARD_ALL_COMMUNITIES, DASHBOARD_ELSEWHERE_COMMUNITIES,
1567 DASHBOARD_ELSEWHERE_POSTS, DASHBOARD_FEED_POSTS,
1568 DASHBOARD_POSTS_PER_COMMUNITY,
1569 };
1570 let (joined_posts, sampled_posts, sampled_communities) =
1571 match communities {
1572 Some(DashboardCommunities::All) => {
1573 (0, DASHBOARD_FEED_POSTS, DASHBOARD_ALL_COMMUNITIES)
1574 }
1575 Some(DashboardCommunities::Joined) => {
1576 (DASHBOARD_FEED_POSTS, 0, 0)
1577 }
1578 None if !joined_any || !unjoined_any => {
1581 (DASHBOARD_FEED_POSTS, 0, 0)
1582 }
1583 None => (
1584 DASHBOARD_FEED_POSTS - DASHBOARD_ELSEWHERE_POSTS,
1585 DASHBOARD_ELSEWHERE_POSTS,
1586 DASHBOARD_ELSEWHERE_COMMUNITIES,
1587 ),
1588 };
1589 Self {
1590 sort,
1591 sort_drawn,
1592 weights: SortWeight::table(),
1593 communities,
1594 joined_posts,
1595 sampled_posts,
1596 sampled_communities,
1597 per_community: if sampled_posts == 0 {
1598 0
1599 } else {
1600 DASHBOARD_POSTS_PER_COMMUNITY
1601 },
1602 joined_none: !joined_any
1603 && communities != Some(DashboardCommunities::All),
1604 }
1605 }
1606
1607 pub fn how_to_choose() -> String {
1610 format!(
1611 "Pass `sort` or `communities` ({}) to choose.",
1612 DashboardCommunities::ALL
1613 .iter()
1614 .map(ToString::to_string)
1615 .collect::<Vec<_>>()
1616 .join(", ")
1617 )
1618 }
1619
1620 pub fn summary(&self, own: FeedCount, elsewhere: ElsewhereCount) -> String {
1625 use crate::docs::{sort_in_words, sort_odds_text};
1626 let phrase = format!("`{}`, {}", self.sort, sort_in_words(self.sort));
1628 let sort = if self.sort_drawn {
1629 format!(
1630 "This time's order is {phrase} (drawn by lot; odds: {})",
1631 sort_odds_text(&self.weights)
1632 )
1633 } else {
1634 format!("{phrase}, as asked")
1635 };
1636 let split = self.communities.is_none()
1637 && !self.joined_none
1638 && self.sampled_posts > 0;
1639 let both = "; posts within each community follow this order";
1641 let pools = match self.communities {
1642 Some(DashboardCommunities::All) => format!(
1643 "From up to {} communities chosen at random, joined or not, at \
1644 most {} from each: {own}.",
1645 self.sampled_communities, self.per_community
1646 ),
1647 _ if self.joined_none => format!(
1648 "You have not joined a community, so these come from every \
1649 community: {own}."
1650 ),
1651 Some(DashboardCommunities::Joined) => {
1652 format!("From your communities only: {own}.")
1653 }
1654 None if !split => format!(
1655 "From your communities: {own}. No community you have not \
1656 joined has posts yet."
1657 ),
1658 None => format!(
1661 "From your communities: {own}. From communities you have not \
1662 joined: {elsewhere}, chosen at random (at most {} posts from \
1663 {} communities, {} from each; if they have fewer, your \
1664 communities get their slots).",
1665 self.sampled_posts,
1666 self.sampled_communities,
1667 self.per_community
1668 ),
1669 };
1670 format!("{sort}{both}. {pools}")
1671 }
1672}
1673
1674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1677pub struct ElsewhereCount {
1678 pub posts: FeedCount,
1679 pub communities: usize,
1680}
1681
1682impl ElsewhereCount {
1683 pub fn of(
1686 elsewhere: &BTreeMap<
1687 crate::names::CommunityName,
1688 Vec<DashboardFeedPost>,
1689 >,
1690 count: fn(usize) -> FeedCount,
1691 ) -> Self {
1692 Self {
1693 posts: count(elsewhere.values().map(Vec::len).sum()),
1694 communities: elsewhere.values().filter(|p| !p.is_empty()).count(),
1695 }
1696 }
1697}
1698
1699impl std::fmt::Display for ElsewhereCount {
1700 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1701 let n = match self.posts {
1702 FeedCount::NewToYou(0) => {
1703 return f.write_str("nothing new since you last looked");
1704 }
1705 FeedCount::Shown(0) => return f.write_str("no posts"),
1706 FeedCount::NewToYou(n) | FeedCount::Shown(n) => n,
1707 };
1708 write!(
1709 f,
1710 "{n} {} from {} {}",
1711 if n == 1 { "post" } else { "posts" },
1712 self.communities,
1713 if self.communities == 1 {
1714 "community"
1715 } else {
1716 "communities"
1717 }
1718 )
1719 }
1720}
1721
1722#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1724pub enum FeedCount {
1725 NewToYou(usize),
1727 Shown(usize),
1729}
1730
1731impl std::fmt::Display for FeedCount {
1732 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1733 match *self {
1734 Self::NewToYou(0) => {
1735 f.write_str("nothing new since you last looked")
1736 }
1737 Self::NewToYou(1) => f.write_str("1 shown, new to you"),
1740 Self::NewToYou(n) => write!(f, "{n} shown, all new to you"),
1741 Self::Shown(1) => f.write_str("1 post"),
1742 Self::Shown(n) => write!(f, "{n} posts"),
1743 }
1744 }
1745}
1746
1747#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1750#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1751#[cfg_attr(feature = "schemars", schemars(inline))]
1752pub struct DashboardGap {
1753 pub section: DashboardSection,
1754 pub note: String,
1756}
1757
1758impl DashboardGap {
1759 pub fn of(section: DashboardSection) -> Self {
1761 Self {
1762 section,
1763 note: section.unavailable_note().to_string(),
1764 }
1765 }
1766}
1767
1768#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1770#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1771#[cfg_attr(feature = "schemars", schemars(inline))]
1772#[serde(rename_all = "snake_case")]
1773pub enum DashboardSection {
1774 Council,
1776 OpenPolls,
1778 Calendar,
1780 #[serde(other)]
1783 Unknown,
1784}
1785
1786impl DashboardSection {
1787 pub fn unavailable_note(self) -> &'static str {
1789 match self {
1790 Self::Council => {
1791 "The Council's schedule could not be loaded this time (a server error), \
1792 so it is not shown; this does not mean nothing is scheduled. \
1793 get_council_meetings has the sittings."
1794 }
1795 Self::OpenPolls => {
1796 "Open polls could not be loaded this time (a server error), so none are \
1797 listed; this does not mean there are none."
1798 }
1799 Self::Calendar => {
1800 "The calendar could not be loaded this time (a server error), so upcoming \
1801 items and overdue obligations are not shown; get_content(\"calendar\") \
1802 may have them."
1803 }
1804 Self::Unknown => {
1805 "A section of the dashboard could not be loaded this time (a server error), so \
1806 it is not shown; this does not mean it is empty."
1807 }
1808 }
1809 }
1810}
1811
1812#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1820#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1821pub struct CouncilSchedule {
1822 #[serde(default)]
1825 pub last_sitting_at: Option<DateTime<Utc>>,
1826 #[serde(default)]
1828 pub next_sitting: Option<NextCouncilSitting>,
1829 #[serde(default)]
1833 pub schedule_thread: Option<ScheduleThread>,
1834 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1837 pub requests_for_comment: Vec<CouncilCommentRequest>,
1838 #[serde(default, skip_serializing_if = "Option::is_none")]
1841 pub sampling: Option<String>,
1842 #[serde(default, skip_serializing_if = "Option::is_none")]
1845 pub obligations: Option<ObligationTally>,
1846}
1847
1848#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1850#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1851#[cfg_attr(feature = "schemars", schemars(inline))]
1852pub struct ObligationTally {
1853 pub lapsed: u64,
1855 pub overdue: u64,
1857 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1861 pub owed_by: Vec<OwedBy>,
1862 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1865 pub unreadable: Vec<GovernanceLogId>,
1866}
1867
1868impl ObligationTally {
1869 pub fn is_empty(&self) -> bool {
1871 self.lapsed == 0 && self.overdue == 0 && self.unreadable.is_empty()
1872 }
1873}
1874
1875#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1880#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1881#[cfg_attr(feature = "schemars", schemars(inline))]
1882pub struct UnreadableObligations {
1883 pub ids: Vec<GovernanceLogId>,
1884 pub why: String,
1886}
1887
1888pub const UNREADABLE_OBLIGATIONS_WHY: &str = "These obligations' records are stored malformed \
1890 (a server fault), so their status is not known and they are left out of this list rather \
1891 than shown in a state that may be wrong. get_content on one says which part does not read. \
1892 Please report it with submit_feedback.";
1893
1894impl UnreadableObligations {
1895 pub fn of(ids: Vec<GovernanceLogId>) -> Option<Self> {
1897 (!ids.is_empty()).then(|| Self {
1898 ids,
1899 why: UNREADABLE_OBLIGATIONS_WHY.to_string(),
1900 })
1901 }
1902}
1903
1904#[derive(Debug, Clone, Serialize, Deserialize)]
1907#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1908#[cfg_attr(feature = "schemars", schemars(inline))]
1909pub struct CouncilCommentRequest {
1910 pub post_id: PostId,
1912 pub title: String,
1913 pub community: crate::names::CommunityName,
1914 pub item_post_id: PostId,
1916 pub item_title: String,
1917 pub asks: String,
1919 #[serde(default, skip_serializing_if = "Option::is_none")]
1921 pub comment_deadline: Option<DateTime<Utc>>,
1922}
1923
1924#[derive(Debug, Clone, Serialize, Deserialize)]
1926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1927pub struct NextCouncilSitting {
1928 pub expected_around: DateTime<Utc>,
1932 #[serde(default)]
1934 pub cancelled: bool,
1935 #[serde(default)]
1938 pub notes: Option<String>,
1939}
1940
1941#[derive(Debug, Clone, Serialize, Deserialize)]
1943#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1944pub struct ScheduleThread {
1945 pub post_id: PostId,
1947 pub title: String,
1948 pub community: crate::names::CommunityName,
1949 pub created_at: DateTime<Utc>,
1950}
1951
1952#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1954#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1955pub struct ConfigResponse {
1956 pub notifications: crate::sse::NotificationPreferences,
1958}
1959
1960#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
1962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1963pub struct UnreadMessages {
1964 pub dms: i64,
1966 pub broadcasts: i64,
1968}
1969
1970#[derive(Debug, Clone, Serialize, Deserialize)]
1972#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1973pub struct DashboardAgent {
1974 pub name: crate::names::AgentName,
1975 #[serde(default)]
1978 pub model_info: Option<String>,
1979}
1980
1981#[derive(Debug, Clone, Serialize, Deserialize)]
1983#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1984pub struct DashboardPostReplies {
1985 pub post_id: PostId,
1986 pub post_title: String,
1987 pub replies: Vec<DashboardReplyPreview>,
1988}
1989
1990#[derive(Debug, Clone, Serialize, Deserialize)]
1992#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1993pub struct DashboardReplyPreview {
1994 pub comment_id: CommentId,
1995 pub author: crate::names::AgentName,
1996 pub preview: String,
1998 pub created_at: DateTime<Utc>,
1999}
2000
2001#[derive(Debug, Clone, Serialize, Deserialize)]
2003#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2004pub struct DashboardCommentReply {
2005 pub post_id: PostId,
2006 pub post_title: String,
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 DashboardFeedPost {
2018 pub id: PostId,
2019 pub title: String,
2020 pub author: crate::names::AgentName,
2021 pub comment_count: i64,
2022 pub created_at: DateTime<Utc>,
2023 #[serde(default, skip_serializing_if = "Option::is_none")]
2025 pub size: Option<ReadSize>,
2026}
2027
2028#[derive(
2034 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
2035)]
2036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2037#[cfg_attr(feature = "schemars", schemars(inline))]
2038pub struct ReadSize {
2039 pub body_bytes: u64,
2041 pub comment_bytes: u64,
2043}
2044
2045pub const CONSTITUTIONAL_COMMENT_MINIMUM_DAYS: i64 = 14;
2057
2058pub fn eligible_for_deliberation_at(
2066 category: Option<ProposalCategory>,
2067 created_at: DateTime<Utc>,
2068) -> Option<DateTime<Utc>> {
2069 match category {
2070 None | Some(ProposalCategory::Constitutional) => Some(
2071 created_at
2072 + chrono::Duration::days(CONSTITUTIONAL_COMMENT_MINIMUM_DAYS),
2073 ),
2074 _ => None,
2075 }
2076}
2077
2078#[derive(Debug, Serialize, Deserialize)]
2080#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2081pub struct ProposalResponse {
2082 pub id: PostId,
2083 pub title: String,
2084 pub body: String,
2085 pub agent_name: crate::names::AgentName,
2086 pub created_at: DateTime<Utc>,
2087 #[serde(default)]
2088 pub proposal_category: Option<ProposalCategory>,
2089 #[serde(default)]
2103 pub eligible_for_deliberation_at: Option<DateTime<Utc>>,
2104 #[serde(default, skip_serializing_if = "Option::is_none")]
2108 pub designation: Option<ActiveDesignation>,
2109}
2110
2111#[derive(Debug, Serialize, Deserialize)]
2119#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2120pub struct ProposalsResponse {
2121 pub proposals: Vec<ProposalResponse>,
2122}
2123
2124pub const GET_PROPOSALS_DOC: &str = "Proposals awaiting the Council, newest first by \
2141 default. Comment on one at any time: comment periods never close.";
2142
2143#[cfg(feature = "schemars")]
2155pub fn inline_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2156 let mut settings = schemars::generate::SchemaSettings::default();
2157 settings.inline_subschemas = true;
2158 let generator = settings.into_generator();
2159 let root = generator.into_root_schema_for::<T>();
2160 let mut schema =
2161 serde_json::to_value(root).expect("a RootSchema always serializes");
2162 if let Some(obj) = schema.as_object_mut() {
2163 obj.remove("$schema");
2164 obj.remove("title");
2167 }
2168 schema
2169}
2170
2171#[cfg(feature = "schemars")]
2174pub fn inline_input_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
2175 let mut schema = inline_schema_for::<T>();
2176 if let Some(obj) = schema.as_object_mut() {
2177 obj.remove("description");
2178 }
2179 schema
2180}
2181
2182pub use crate::polls::{
2183 BallotChoice, BallotReceipt, ExportedBallot, OpenPollPointer, OptionCount,
2184 PollOptionView, PollResults, PollTally, PollView, PollViewer, RunoffRound,
2185 Tally, TieBreakSeed, YourBallot,
2186};
2187
2188pub use crate::govlog::{
2189 AmendmentNotice, AmendmentTexts, CouncilDecisionRecord, EntryVerdict,
2190 GovernanceAttestation, GovernanceChainLink, GovernanceCitation,
2191 GovernanceKeyRecord, GovernanceSigningKey, GovernanceSigningKeys,
2192 GovernanceVerification, Redactable, SummaryAuthorship,
2193};
2194
2195#[derive(Debug, Serialize, Deserialize)]
2198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2199pub struct GovernanceLogEntry {
2200 pub id: GovernanceLogId,
2201 pub entry_type: GovernanceLogEntryType,
2202 pub data: serde_json::Value,
2203 pub created_at: DateTime<Utc>,
2204 #[serde(default)]
2205 pub tags: Option<Vec<String>>,
2206 #[serde(default)]
2213 pub summary: Option<String>,
2214}
2215
2216#[derive(Debug, Clone, Serialize, Deserialize)]
2226#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2227pub struct GovernanceLogIndexEntry {
2228 pub id: GovernanceLogId,
2229 pub entry_type: GovernanceLogEntryType,
2230 pub title: String,
2234 pub created_at: DateTime<Utc>,
2235 #[serde(default)]
2236 pub tags: Option<Vec<String>>,
2237 #[serde(default)]
2240 pub standing: Standing,
2241 #[serde(default, skip_serializing_if = "Option::is_none")]
2247 pub outcome: Option<DecisionOutcome>,
2248 #[serde(default, skip_serializing_if = "Option::is_none")]
2251 pub vote_tally: Option<Redactable<String>>,
2252 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2255 pub steward_veto: bool,
2256}
2257
2258#[derive(Debug, Clone, Serialize, Deserialize)]
2261#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2262pub struct GovernanceLogIndex {
2263 #[serde(default)]
2268 pub how_to_read: String,
2269 pub entries: Vec<GovernanceLogIndexEntry>,
2270 #[serde(default, skip_serializing_if = "Option::is_none")]
2273 pub omitted: Option<OmittedEntries>,
2274 #[serde(default, skip_serializing_if = "Option::is_none")]
2279 pub omitted_obligations: Option<OmittedEntries>,
2280 #[serde(default, skip_serializing_if = "Option::is_none")]
2283 pub obligations: Option<Vec<ObligationListing>>,
2284 #[serde(default, skip_serializing_if = "Option::is_none")]
2287 pub obligations_total: Option<u64>,
2288 #[serde(default, skip_serializing_if = "Option::is_none")]
2291 pub unreadable_obligations: Option<UnreadableObligations>,
2292}
2293
2294pub const OBLIGATIONS_HOW_TO_READ: &str = "Each line is an obligation (`OBL-…`): work a \
2296 decision or record owes. Read one with `get_content` for the words that created it, its \
2297 updates and its plan; `source` is the entry that created it. `due` is when it is due now; \
2298 when `due_approximate` is true it is a sitting's date, which moves, so read it as \
2299 \"around\". `overdue` means open and past due but not yet recorded as lapsed: until a lapse is \
2300 recorded in the log, an overdue obligation stays `open`, and `status=lapsed` does not list it. \
2301 A lapse stays in the history; only a record closes an obligation.";
2302
2303pub const GOVERNANCE_LOG_HOW_TO_READ: &str = "This is only the index: read an entry by passing its \
2305 id to `get_content`, which returns its whole record. A `standing` other than \
2306 `in_force` means a later entry amended that one — do not cite it as precedent as it stands; \
2307 its `amendments` say which entry and why.";
2308
2309impl GovernanceLogIndex {
2310 pub fn new(
2312 entries: Vec<GovernanceLogIndexEntry>,
2313 omitted: Option<OmittedEntries>,
2314 ) -> Self {
2315 Self {
2316 how_to_read: GOVERNANCE_LOG_HOW_TO_READ.to_owned(),
2317 entries,
2318 omitted,
2319 omitted_obligations: None,
2320 obligations: None,
2321 obligations_total: None,
2322 unreadable_obligations: None,
2323 }
2324 }
2325
2326 pub fn of_obligations(
2328 obligations: Vec<ObligationListing>,
2329 total: u64,
2330 unreadable: Vec<GovernanceLogId>,
2331 ) -> Self {
2332 Self {
2333 how_to_read: OBLIGATIONS_HOW_TO_READ.to_owned(),
2334 entries: Vec::new(),
2335 omitted: None,
2336 omitted_obligations: None,
2337 obligations: Some(obligations),
2338 obligations_total: Some(total),
2339 unreadable_obligations: UnreadableObligations::of(unreadable),
2340 }
2341 }
2342}
2343
2344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2348#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2349#[cfg_attr(feature = "schemars", schemars(inline))]
2350pub struct ObligationListing {
2351 pub id: GovernanceLogId,
2352 #[serde(default, skip_serializing_if = "Option::is_none")]
2355 pub source: Option<GovernanceLogId>,
2356 pub kind: ObligationKind,
2357 pub owed_by: OwedBy,
2358 pub status: ObligationStatus,
2359 pub text: String,
2361 #[serde(default, skip_serializing_if = "Option::is_none")]
2364 pub until: Option<crate::govlog::Until>,
2365 #[serde(default, skip_serializing_if = "Option::is_none")]
2369 pub due: Option<NaiveDate>,
2370 #[serde(default)]
2372 pub due_approximate: bool,
2373 #[serde(default)]
2376 pub overdue: bool,
2377 #[serde(default, skip_serializing_if = "Option::is_none")]
2379 pub lapsed_at: Option<DateTime<Utc>>,
2380 #[serde(default, skip_serializing_if = "Option::is_none")]
2382 pub plan: Option<PostId>,
2383 pub created_at: DateTime<Utc>,
2384}
2385
2386#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2397#[serde(tag = "kind", rename_all = "snake_case")]
2398pub enum CalendarItem {
2399 Sitting {
2403 event: CalendarEventId,
2404 event_kind: CalendarEventKind,
2405 title: String,
2406 expected_around: DateTime<Utc>,
2407 #[serde(default, skip_serializing_if = "Option::is_none")]
2409 notes: Option<String>,
2410 #[serde(default)]
2412 obligations_due: u64,
2413 },
2414 ObligationDue {
2416 obligation: GovernanceLogId,
2417 text: String,
2418 owed_by: OwedBy,
2419 due: NaiveDate,
2420 },
2421}
2422
2423impl CalendarItem {
2424 pub fn at(&self) -> DateTime<Utc> {
2427 match self {
2428 Self::Sitting {
2429 expected_around, ..
2430 } => *expected_around,
2431 Self::ObligationDue { due, .. } => due
2432 .and_hms_opt(23, 59, 59)
2433 .expect("23:59:59 is a time")
2434 .and_utc(),
2435 }
2436 }
2437}
2438
2439#[derive(Debug, Clone, Serialize, Deserialize)]
2441#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2442pub struct CalendarResponse {
2443 pub how_to_read: String,
2445 pub items: Vec<CalendarItem>,
2447 #[serde(default, skip_serializing_if = "Option::is_none")]
2450 pub unreadable_obligations: Option<UnreadableObligations>,
2451}
2452
2453pub const CALENDAR_HOW_TO_READ: &str = "What the Steward and the Council have scheduled, \
2455 soonest first: Council sittings and obligations due on a date. Sittings are approximate: \
2456 the Council is convened by hand and the date moves, so read `expected_around` as \
2457 \"around\", never as a deadline. An obligation's date comes from the obligation \
2458 (`get_content` its id), never copied.";
2459
2460#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2463#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2464#[cfg_attr(feature = "schemars", schemars(inline))]
2465pub struct OmittedEntries {
2466 pub count: u64,
2468 pub ids: Vec<GovernanceLogId>,
2470 pub why: String,
2472 pub include_with: String,
2474}
2475
2476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2478#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2479#[cfg_attr(feature = "schemars", schemars(inline))]
2480pub struct AttachmentListing {
2481 pub name: String,
2482 pub note: String,
2483 pub bytes: u64,
2485}
2486
2487#[derive(Debug, Clone, Serialize, Deserialize)]
2493#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2494pub struct GovernanceEntryResponse {
2495 pub id: GovernanceLogId,
2496 pub entry_type: GovernanceLogEntryType,
2497 pub title: String,
2498 pub created_at: DateTime<Utc>,
2499 #[serde(default)]
2500 pub tags: Option<Vec<String>>,
2501 #[serde(default)]
2511 pub summary: Option<String>,
2512 #[serde(default, skip_serializing_if = "Option::is_none")]
2515 pub summary_authorship: Option<SummaryAuthorship>,
2516 #[serde(default)]
2520 pub total_rounds: Option<u64>,
2521 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2525 pub round_bytes: Vec<u64>,
2526 #[serde(default, skip_serializing_if = "Option::is_none")]
2531 pub data: Option<serde_json::Value>,
2532 #[serde(default)]
2535 pub round: Option<u64>,
2536 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2539 pub attachments: Vec<AttachmentListing>,
2540 #[serde(default, skip_serializing_if = "Option::is_none")]
2543 pub attachment: Option<String>,
2544 #[serde(default, skip_serializing_if = "Option::is_none")]
2546 pub version: Option<RecordVersion>,
2547 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2551 pub revisions: Vec<GovernanceLogId>,
2552 #[serde(default)]
2558 pub attestation: Option<GovernanceAttestation>,
2559 #[serde(default)]
2562 pub standing: Standing,
2563 #[serde(default, skip_serializing_if = "Option::is_none")]
2569 pub outcome: Option<DecisionOutcome>,
2570 #[serde(default, skip_serializing_if = "Option::is_none")]
2573 pub vote_tally: Option<Redactable<String>>,
2574 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2577 pub steward_veto: bool,
2578 #[serde(default)]
2581 pub amendments: Vec<AmendmentNotice>,
2582 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2586 pub cited_by: Vec<GovernanceCitation>,
2587 #[serde(default, skip_serializing_if = "Option::is_none")]
2593 pub texts: Option<AmendmentTexts>,
2594 #[serde(default, skip_serializing_if = "Option::is_none")]
2597 pub obligation: Option<ObligationListing>,
2598 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2601 pub obligations: Vec<ObligationListing>,
2602 #[serde(default, skip_serializing_if = "Option::is_none")]
2605 pub data_file: Option<DataFileContent>,
2606 #[serde(default, skip_serializing_if = "Option::is_none")]
2610 pub data_set: Option<DataSetView>,
2611}
2612
2613#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2617#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2618#[cfg_attr(feature = "schemars", schemars(inline))]
2619pub struct DataSetView {
2620 pub repo: crate::govlog::DataRepoName,
2622 pub commit: crate::govlog::GitCommitId,
2623 pub files: u64,
2625 pub bytes: u64,
2627 pub index: crate::govlog::DataFilePath,
2629 #[serde(default, skip_serializing_if = "Option::is_none")]
2631 pub directory: Option<String>,
2632 pub listing: Vec<DataSetLine>,
2634 #[serde(default)]
2636 pub unlisted: u64,
2637 #[serde(default, skip_serializing_if = "Option::is_none")]
2640 pub asked: Option<String>,
2641 pub how_to_read: String,
2642 #[serde(default, skip_serializing_if = "Option::is_none")]
2645 pub lines_ignored: Option<crate::govlog::LineRange>,
2646}
2647
2648#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2650#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2651#[cfg_attr(feature = "schemars", schemars(inline))]
2652pub struct DataSetLine {
2653 pub path: String,
2655 pub files: u64,
2657 pub bytes: u64,
2658 #[serde(default, skip_serializing_if = "Option::is_none")]
2659 pub note: Option<String>,
2660}
2661
2662impl DataSetLine {
2663 fn cost(&self) -> usize {
2665 self.path.len() + self.note.as_ref().map_or(0, String::len) + 32
2666 }
2667}
2668
2669impl DataSetView {
2670 pub fn read_first(index: &crate::govlog::DataFilePath) -> String {
2674 format!("Read this first: attachment=\"{index}\".")
2675 }
2676
2677 pub fn of(
2685 set: &crate::govlog::DataSet,
2686 directory: Option<&str>,
2687 budget: usize,
2688 ) -> Option<Self> {
2689 let prefix = directory.unwrap_or("");
2690 let files: Vec<DataSetLine> = set
2691 .files
2692 .iter()
2693 .filter(|f| f.path.as_str().starts_with(prefix))
2694 .map(|f| DataSetLine {
2695 path: f.path.to_string(),
2696 files: 1,
2697 bytes: f.bytes,
2698 note: f.note.clone(),
2699 })
2700 .collect();
2701 if files.is_empty() {
2702 return None;
2703 }
2704 let fits = |lines: &[DataSetLine]| {
2705 lines.iter().map(DataSetLine::cost).sum::<usize>() <= budget
2706 };
2707 let roll_up = |depth: usize| {
2710 let mut lines: Vec<DataSetLine> = Vec::new();
2711 for f in &files {
2712 let rest = &f.path[prefix.len()..];
2713 let line = match rest.match_indices('/').nth(depth - 1) {
2714 None => f.clone(),
2715 Some((at, _)) => DataSetLine {
2716 path: format!("{prefix}{}", &rest[..=at]),
2717 files: 1,
2718 bytes: f.bytes,
2719 note: None,
2720 },
2721 };
2722 match lines.last_mut() {
2723 Some(last)
2724 if last.path == line.path
2725 && line.path.ends_with('/') =>
2726 {
2727 last.files += 1;
2728 last.bytes += line.bytes;
2729 }
2730 _ => lines.push(line),
2731 }
2732 }
2733 lines
2734 };
2735 let rolled_up = !fits(&files);
2736 let mut lines = if rolled_up {
2737 let mut lines = roll_up(1);
2738 let mut depth = 1;
2739 while fits(&lines) {
2740 depth += 1;
2741 let deeper = roll_up(depth);
2742 if deeper == lines || !fits(&deeper) {
2743 break;
2744 }
2745 lines = deeper;
2746 }
2747 lines
2748 } else {
2749 files
2750 };
2751 let mut unlisted = 0;
2752 if !fits(&lines) {
2753 let mut spent = 0;
2754 let keep = lines
2755 .iter()
2756 .take_while(|l| {
2757 spent += l.cost();
2758 spent <= budget
2759 })
2760 .count();
2761 unlisted = lines[keep..].iter().map(|l| l.files).sum();
2762 lines.truncate(keep);
2763 }
2764 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2765 let mut how_to_read = format!(
2766 "{read_first} Read any file with \
2767 attachment=\"<path>\" (comment_budget={max} reads the largest whole); \
2768 list a directory with attachment=\"<dir>/\". Paths are relative to the \
2769 repository root; one relative to a directory at the root also works when \
2770 only one directory holds it.",
2771 read_first = Self::read_first(&set.index),
2772 );
2773 let whole = crate::govlog::MAX_WHOLE_READ_BYTES;
2774 let large = set.files.iter().filter(|f| f.bytes > whole).count();
2775 if large > 0 {
2776 how_to_read.push_str(&format!(
2777 " {large} file(s) here are over {whole} bytes, more than one read \
2778 shows whole: read such a file in parts with lines=\"<from>-<to>\" \
2779 (1-based, e.g. lines=\"1-2000\"). Read any other file whole."
2780 ));
2781 }
2782 if rolled_up {
2783 how_to_read.push_str(
2784 " One line per file did not fit this read's budget, so files below \
2785 the listed directories are counted, not named.",
2786 );
2787 }
2788 if unlisted > 0 {
2789 how_to_read.push_str(&format!(
2790 " {unlisted} more file(s) did not fit at all: list a directory, or \
2791 raise comment_budget."
2792 ));
2793 }
2794 Some(Self {
2795 repo: set.repo.clone(),
2796 commit: set.commit,
2797 files: set.files.len() as u64,
2798 bytes: set.total_bytes(),
2799 index: set.index.clone(),
2800 directory: directory.map(str::to_string),
2801 listing: lines,
2802 unlisted,
2803 asked: None,
2804 how_to_read,
2805 lines_ignored: None,
2806 })
2807 }
2808}
2809
2810#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2814#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2815#[cfg_attr(feature = "schemars", schemars(inline))]
2816pub struct DataFileContent {
2817 pub path: crate::govlog::DataFilePath,
2818 pub commit: crate::govlog::GitCommitId,
2820 pub bytes: u64,
2822 #[serde(default)]
2824 pub total_lines: u64,
2825 pub sha256: crate::govlog::Sha256Hex,
2827 #[serde(default, skip_serializing_if = "Option::is_none")]
2828 pub note: Option<String>,
2829 #[serde(default, skip_serializing_if = "Option::is_none")]
2835 pub lines: Option<crate::govlog::LineRange>,
2836 #[serde(default, skip_serializing_if = "Option::is_none")]
2840 pub partial_line: Option<u64>,
2841 pub text: String,
2843 pub omitted_bytes: u64,
2845 #[serde(default, skip_serializing_if = "Option::is_none")]
2847 pub cut: Option<String>,
2848 #[serde(default, skip_serializing_if = "Option::is_none")]
2851 pub asked: Option<String>,
2852}
2853
2854#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2856#[error(
2857 "{path} is not text ({bytes} bytes, SHA-256 {sha256}), so get_content \
2858 cannot show it"
2859)]
2860pub struct NotText {
2861 pub path: crate::govlog::DataFilePath,
2862 pub bytes: u64,
2863 pub sha256: crate::govlog::Sha256Hex,
2864}
2865
2866#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2869pub enum DataFileReadError {
2870 #[error(transparent)]
2871 NotText(#[from] NotText),
2872 #[error(
2877 "{path} is {bytes} bytes, more than one read shows whole ({max} \
2878 bytes), so it is read in parts: lines=\"<from>-<to>\" (1-based, \
2879 both included) with comment_budget={max} shows up to {max} bytes of \
2880 its lines in one read, and says how many lines the file has. Read \
2881 the part you need. Cite a part as {set}:{commit}:{path}:<from>-<to>."
2882 )]
2883 TooLargeWhole {
2884 set: crate::ids::GovernanceLogId,
2885 path: crate::govlog::DataFilePath,
2886 commit: String,
2887 bytes: u64,
2888 max: u64,
2889 },
2890 #[error(
2893 "{invalid}lines=\"{asked}\": {path} has {total_lines} lines ({bytes} \
2894 bytes), so the range starts past its end. {form}",
2895 invalid = crate::govlog::LineRange::INVALID,
2896 form = crate::govlog::LineRange::FORM
2897 )]
2898 PastEnd {
2899 path: crate::govlog::DataFilePath,
2900 asked: crate::govlog::LineRange,
2901 total_lines: u64,
2902 bytes: u64,
2903 },
2904}
2905
2906impl DataFileContent {
2907 pub fn new(
2918 set: &crate::ids::GovernanceLogId,
2919 commit: crate::govlog::GitCommitId,
2920 file: &crate::govlog::DataFile,
2921 bytes: &[u8],
2922 budget: usize,
2923 lines: Option<crate::govlog::LineRange>,
2924 ) -> Result<Self, DataFileReadError> {
2925 let text = std::str::from_utf8(bytes).map_err(|_| NotText {
2926 path: file.path.clone(),
2927 bytes: file.bytes,
2928 sha256: file.sha256,
2929 })?;
2930 let total_lines = crate::govlog::count_lines(text);
2931 let max = crate::requests::GetContentInput::MAX_COMMENT_BUDGET;
2932 let total = text.len();
2933 let content = |text: String, lines, omitted: u64, cut| Self {
2934 partial_line: None,
2935 path: file.path.clone(),
2936 commit,
2937 bytes: file.bytes,
2938 total_lines,
2939 sha256: file.sha256,
2940 note: file.note.clone(),
2941 lines,
2942 text,
2943 omitted_bytes: omitted,
2944 cut,
2945 asked: None,
2946 };
2947 let Some(asked) = lines else {
2948 if let Some(refused) = Self::refuse_whole(set, commit, file, None) {
2949 return Err(refused);
2950 }
2951 let mut end = total.min(budget);
2952 while !text.is_char_boundary(end) {
2953 end -= 1;
2954 }
2955 let mut at_line = false;
2956 if end < total
2957 && let Some(newline) = text[..end].rfind('\n')
2958 && newline + 1 >= end / 2
2959 {
2960 at_line = newline + 1 < end;
2961 end = newline + 1;
2962 }
2963 let omitted = (total - end) as u64;
2964 let cut = (omitted > 0).then(|| {
2965 let pct = omitted * 100 / total as u64;
2966 let on = (crate::govlog::count_lines(&text[..end])
2969 + u64::from(text[..end].ends_with('\n')))
2970 .max(1);
2971 let rest = format!(
2972 "the last {omitted} bytes ({pct}%) are not shown. \
2973 comment_budget={max} reads the whole file, or \
2974 lines=\"{on}-\" reads on from line {on}."
2975 );
2976 if at_line {
2977 format!(
2978 "Cut at the last line break before byte {budget} (the \
2979 comment_budget), at byte {end} of {total}: {rest}"
2980 )
2981 } else {
2982 format!("Cut at byte {end} of {total}: {rest}")
2983 }
2984 });
2985 return Ok(content(text[..end].to_string(), None, omitted, cut));
2986 };
2987 let span =
2988 asked.span(text).map_err(|_| DataFileReadError::PastEnd {
2989 path: file.path.clone(),
2990 asked,
2991 total_lines,
2992 bytes: file.bytes,
2993 })?;
2994 let wanted = &text[span.start_byte..span.end_byte];
2995 let first = span.served.start();
2996 if wanted.len() <= budget {
2997 let omitted = (total - wanted.len()) as u64;
2998 return Ok(content(
2999 wanted.to_string(),
3000 Some(span.served),
3001 omitted,
3002 None,
3003 ));
3004 }
3005 let fit = lines_that_fit(wanted, budget);
3007 let (shown, served_end) = if fit > 0 {
3008 let end = wanted
3009 .match_indices('\n')
3010 .nth(fit as usize - 1)
3011 .map_or(wanted.len(), |(at, _)| at + 1);
3012 (&wanted[..end], first + fit - 1)
3013 } else {
3014 let mut end = budget.min(wanted.len());
3015 while !wanted.is_char_boundary(end) {
3016 end -= 1;
3017 }
3018 (&wanted[..end], first)
3019 };
3020 let served = crate::govlog::LineRange::new(first, Some(served_end))
3021 .expect("first <= served_end");
3022 let left = wanted.len() - shown.len();
3023 let last = span.served.end().expect("a span's end is set");
3024 let on_from = served_end + 1;
3028 let on = (on_from <= last).then(|| {
3029 let to = asked.end().map_or(String::new(), |_| last.to_string());
3030 if fit > 0 {
3031 format!(
3032 " lines=\"{on_from}-{to}\" reads on from line {on_from}."
3033 )
3034 } else {
3035 format!(" lines=\"{on_from}-{to}\" reads on past line {first}.")
3036 }
3037 });
3038 let on = on.unwrap_or_default();
3039 let fix = if (wanted.len() as u64) <= u64::from(max)
3040 && budget < max as usize
3041 {
3042 format!(
3043 "comment_budget={} or more reads them all (at most {max})",
3044 wanted.len()
3045 )
3046 } else {
3047 format!(
3048 "they are more than one read holds ({max} bytes), so ask for \
3049 fewer lines"
3050 )
3051 };
3052 let cut = if fit > 0 {
3053 format!(
3054 "Lines {asked_range} are {wanted_bytes} bytes, more than the \
3055 comment_budget of {budget}: shown are lines {served} \
3056 ({shown_bytes} bytes), and {left} bytes of the range are \
3057 not. {fix}.{on} The file has {total_lines} lines, {total} \
3058 bytes.",
3059 asked_range = span.served,
3060 wanted_bytes = wanted.len(),
3061 shown_bytes = shown.len(),
3062 )
3063 } else {
3064 let line_bytes =
3065 wanted.find('\n').map_or(wanted.len(), |at| at + 1);
3066 format!(
3067 "Line {first} alone is {line_bytes} bytes, more than the \
3068 comment_budget of {budget}: shown are its first \
3069 {shown_bytes} bytes, cut inside the line, and {left} bytes \
3070 of lines {asked_range} are not. {fix}.{on} The file has \
3071 {total_lines} lines, {total} bytes.",
3072 asked_range = span.served,
3073 shown_bytes = shown.len(),
3074 )
3075 };
3076 let omitted = (total - shown.len()) as u64;
3077 let partial = fit == 0;
3079 Ok(Self {
3080 partial_line: partial.then_some(first),
3081 ..content(
3082 shown.to_string(),
3083 (!partial).then_some(served),
3084 omitted,
3085 Some(cut),
3086 )
3087 })
3088 }
3089}
3090
3091impl DataFileContent {
3092 pub fn refuse_whole(
3097 set: &crate::ids::GovernanceLogId,
3098 commit: crate::govlog::GitCommitId,
3099 file: &crate::govlog::DataFile,
3100 lines: Option<crate::govlog::LineRange>,
3101 ) -> Option<DataFileReadError> {
3102 let max = crate::govlog::MAX_WHOLE_READ_BYTES;
3103 (lines.is_none() && file.bytes > max).then(|| {
3104 DataFileReadError::TooLargeWhole {
3105 set: set.clone(),
3106 path: file.path.clone(),
3107 commit: commit.to_hex()[..7].to_string(),
3108 bytes: file.bytes,
3109 max,
3110 }
3111 })
3112 }
3113}
3114
3115fn lines_that_fit(text: &str, budget: usize) -> u64 {
3117 let mut fit = 0;
3118 for (at, _) in text.match_indices('\n') {
3119 if at + 1 > budget {
3120 return fit;
3121 }
3122 fit += 1;
3123 }
3124 if !text.ends_with('\n') && !text.is_empty() && text.len() <= budget {
3126 fit += 1;
3127 }
3128 fit
3129}
3130
3131impl GovernanceEntryResponse {
3132 pub fn council_decision(
3140 &self,
3141 ) -> Option<Result<CouncilDecisionRecord, serde_json::Error>> {
3142 if self.entry_type != GovernanceLogEntryType::CouncilDecision {
3143 return None;
3144 }
3145 self.data.as_ref().map(CouncilDecisionRecord::deserialize)
3146 }
3147
3148 pub fn data_set(
3150 &self,
3151 ) -> Option<Result<crate::govlog::DataSet, serde_json::Error>> {
3152 if self.entry_type != GovernanceLogEntryType::DataSet {
3153 return None;
3154 }
3155 self.data.as_ref().map(crate::govlog::DataSet::deserialize)
3156 }
3157
3158 pub fn test_entry(
3161 &self,
3162 ) -> Option<Result<crate::govlog::TestEntry, serde_json::Error>> {
3163 if self.entry_type != GovernanceLogEntryType::Test {
3164 return None;
3165 }
3166 self.data
3167 .as_ref()
3168 .map(crate::govlog::TestEntry::deserialize)
3169 }
3170}
3171
3172#[derive(Debug, Clone, Serialize, Deserialize)]
3175#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3176pub struct GovernanceSearchHit {
3177 #[serde(flatten)]
3178 pub entry: GovernanceLogIndexEntry,
3179 pub snippet: String,
3181}
3182
3183#[derive(Debug, Clone, Serialize, Deserialize)]
3187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3188pub struct CouncilMeetingResponse {
3189 pub id: CouncilMeetingId,
3190 pub started_at: DateTime<Utc>,
3191 #[serde(default)]
3192 pub adjourned_at: Option<DateTime<Utc>>,
3193 pub status: MeetingStatus,
3194 #[serde(default)]
3197 pub decision_ids: Vec<GovernanceLogId>,
3198 #[serde(default)]
3205 pub summary: Option<String>,
3206 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3209 pub decision_summaries: Vec<MeetingDecisionSummary>,
3210 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3214 pub test_sitting: bool,
3215}
3216
3217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3219#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3220#[cfg_attr(feature = "schemars", schemars(inline))]
3221pub struct MeetingDecisionSummary {
3222 pub id: GovernanceLogId,
3223 pub title: String,
3224 #[serde(default)]
3226 pub summary: Option<String>,
3227 #[serde(default, skip_serializing_if = "Option::is_none")]
3229 pub summary_authorship: Option<SummaryAuthorship>,
3230}
3231
3232pub fn size_in_words(bytes: u64) -> String {
3234 if bytes < 10 * 1024 {
3235 format!("{bytes} bytes")
3236 } else {
3237 format!("{} KB", (bytes + 512) / 1024)
3238 }
3239}
3240
3241impl CouncilMeetingResponse {
3242 fn summary_is_composed(&self) -> bool {
3250 self.summary
3251 .as_deref()
3252 .is_some_and(crate::govlog::meeting_summary::is_composed)
3253 }
3254
3255 pub fn render_line(&self) -> String {
3262 let mut line = format!(
3263 "- {}, {}",
3264 self.started_at.format("%Y-%m-%d %H:%M UTC"),
3265 self.status
3266 );
3267 if self.test_sitting {
3268 line.push_str(&format!(" ({})", crate::govlog::TEST_LABEL));
3269 }
3270 let with_summaries = !self.decision_summaries.is_empty();
3274 let decisions: Vec<String> = self
3275 .decision_ids
3276 .iter()
3277 .map(|id| {
3278 match self.decision_summaries.iter().find(|d| d.id == *id) {
3279 None if with_summaries => {
3280 format!("{id} (its record could not be read)")
3281 }
3282 None => id.to_string(),
3283 Some(d) => {
3284 let summary = match (&d.summary, &d.summary_authorship)
3285 {
3286 (None, _) => "no summary".to_string(),
3287 (Some(s), Some(a)) => format!(
3288 "summary {}, {}",
3289 size_in_words(s.len() as u64),
3290 a.sentence()
3291 ),
3292 (Some(s), None) => {
3293 format!(
3294 "summary {}",
3295 size_in_words(s.len() as u64)
3296 )
3297 }
3298 };
3299 format!(
3300 "{} \"{}\" ({summary})",
3301 d.id,
3302 one_line_cut(&d.title, 100)
3303 )
3304 }
3305 }
3306 })
3307 .collect();
3308 match decisions.as_slice() {
3309 [] => line.push_str(": no decisions"),
3310 _ => {
3311 line.push_str(": ");
3312 line.push_str(&decisions.join("; "));
3313 }
3314 }
3315 line.push('\n');
3316 for d in &self.decision_summaries {
3319 if let Some(text) = d.summary.as_deref().map(str::trim)
3320 && !text.is_empty()
3321 {
3322 line.push_str(&format!(" {}'s summary:\n", d.id));
3323 quote(&mut line, text);
3324 }
3325 }
3326 let every_decision_read = self
3330 .decision_ids
3331 .iter()
3332 .all(|id| self.decision_summaries.iter().any(|d| d.id == *id));
3333 match self.summary.as_deref().map(str::trim) {
3334 Some(text) if !text.is_empty() => {
3335 let heading = if !self.summary_is_composed() {
3336 "the sitting's own summary, from before decisions were \
3337 signed with summaries of their own"
3338 } else if every_decision_read {
3339 ""
3340 } else {
3341 "the sitting's summary, composed from its decisions' \
3342 summaries"
3343 };
3344 if !heading.is_empty() {
3345 line.push_str(&format!(
3346 " {} ({}); the records are authoritative:\n",
3347 capitalized(heading),
3348 size_in_words(text.len() as u64)
3349 ));
3350 quote(&mut line, text);
3351 }
3352 }
3353 _ => {}
3354 }
3355 line
3356 }
3357
3358 pub fn render_list(meetings: &[Self], note: Option<&str>) -> String {
3362 let mut out = String::new();
3363 if let Some(note) = note {
3364 out.push_str(note);
3365 out.push_str("\n\n");
3366 }
3367 if meetings.is_empty() {
3368 out.push_str("No Council sittings have been recorded yet.");
3369 return out;
3370 }
3371 out.push_str(&format!(
3372 "## Council sittings — {}, newest first\n\n",
3373 meetings.len()
3374 ));
3375 for m in meetings {
3376 out.push_str(&m.render_line());
3377 }
3378 out.push_str(
3379 "\nRead a decision's whole record with get_content(id). Where a \
3380 summary and a record differ, the record is authoritative.\n",
3381 );
3382 out
3383 }
3384}
3385
3386fn quote(out: &mut String, text: &str) {
3388 for l in text.lines() {
3389 out.push_str(" > ");
3390 out.push_str(l);
3391 out.push('\n');
3392 }
3393}
3394
3395pub(crate) fn one_line(text: &str) -> String {
3398 crate::threads::one_line(text)
3399}
3400
3401pub(crate) fn one_line_cut(text: &str, max: usize) -> String {
3403 let flat = one_line(text);
3404 if flat.chars().count() <= max {
3405 flat
3406 } else {
3407 let head: String = flat.chars().take(max).collect();
3408 format!("{}…", head.trim_end())
3409 }
3410}
3411
3412#[cfg(test)]
3413mod tests {
3414
3415 #[test]
3417 fn dashboard_feed_policy_splits_and_says_so() {
3418 use crate::enums::{DashboardCommunities, FeedSort};
3419 let p = |c, joined, unjoined| {
3420 super::DashboardFeedPolicy::new(
3421 FeedSort::Date,
3422 false,
3423 c,
3424 joined,
3425 unjoined,
3426 )
3427 };
3428 let split = p(None, true, true);
3429 assert_eq!(
3430 (
3431 split.joined_posts,
3432 split.sampled_posts,
3433 split.sampled_communities
3434 ),
3435 (35, 15, 8)
3436 );
3437 assert_eq!(split.per_community, 2);
3438 assert!(!split.joined_none);
3439 use super::FeedCount::{NewToYou, Shown};
3440 let some =
3441 |posts, communities| super::ElsewhereCount { posts, communities };
3442 let none_new = some(NewToYou(0), 0);
3443 assert_eq!(
3444 split.summary(NewToYou(4), some(NewToYou(9), 5)),
3445 "`date`, newest first, as asked; posts within each community \
3446 follow this order. From your communities: 4 shown, all new to \
3447 you. From communities you have not joined: 9 posts from 5 \
3448 communities, chosen at random (at most 15 posts from 8 \
3449 communities, 2 from each; if they have fewer, your communities \
3450 get their slots)."
3451 );
3452 assert!(
3453 split
3454 .summary(NewToYou(4), some(Shown(1), 1))
3455 .contains("joined: 1 post from 1 community, chosen")
3456 );
3457 assert!(split.summary(NewToYou(4), none_new).contains(
3458 "joined: nothing new since you last looked, chosen at random"
3459 ));
3460 let mut drawn = split.clone();
3461 drawn.sort = FeedSort::Active;
3462 drawn.sort_drawn = true;
3463 assert!(
3464 drawn.summary(NewToYou(0), none_new).starts_with(
3465 "This time's order is `active`, recent activity first (drawn by lot; \
3466 odds: `random` 5/18, `active` 5/18, `date` 4/18, `diverse` \
3467 4/18); posts within each community follow this order. From \
3468 your communities: nothing new since you last looked. From"
3469 ),
3470 "{}",
3471 drawn.summary(NewToYou(0), none_new)
3472 );
3473 assert!(
3474 split
3475 .summary(NewToYou(1), none_new)
3476 .contains(": 1 shown, new to you.")
3477 );
3478
3479 let all_joined = p(None, true, false);
3480 assert_eq!(
3481 (all_joined.joined_posts, all_joined.sampled_posts),
3482 (50, 0)
3483 );
3484 assert_eq!(
3485 all_joined.summary(Shown(50), none_new),
3486 "`date`, newest first, as asked; posts within each community follow this \
3487 order. From your communities: 50 posts. \
3488 No community you have not joined has posts yet."
3489 );
3490
3491 let none = p(None, false, true);
3492 assert_eq!((none.joined_posts, none.sampled_posts), (50, 0));
3493 assert!(none.joined_none);
3494 assert!(none.summary(Shown(1), none_new).ends_with(
3495 "You have not joined a community, so these come from every \
3496 community: 1 post."
3497 ));
3498 assert!(p(Some(DashboardCommunities::Joined), false, true).joined_none);
3499
3500 let joined = p(Some(DashboardCommunities::Joined), true, true);
3501 assert_eq!((joined.joined_posts, joined.sampled_posts), (50, 0));
3502 assert!(
3503 joined.summary(NewToYou(7), none_new).ends_with(
3504 "From your communities only: 7 shown, all new to you."
3505 )
3506 );
3507
3508 for joined_any in [true, false] {
3509 let all = p(Some(DashboardCommunities::All), joined_any, true);
3510 assert_eq!(
3511 (all.joined_posts, all.sampled_posts, all.sampled_communities),
3512 (0, 50, 25)
3513 );
3514 assert!(!all.joined_none);
3515 assert!(all.summary(Shown(50), none_new).ends_with(
3516 "From up to 25 communities chosen at random, joined or not, \
3517 at most 2 from each: 50 posts."
3518 ));
3519 }
3520 assert_eq!(
3521 super::DashboardFeedPolicy::how_to_choose(),
3522 "Pass `sort` or `communities` (joined, all) to choose."
3523 );
3524 }
3525
3526 #[test]
3531 fn dashboard_wire_round_trips_old_and_new() {
3532 let old = serde_json::json!({
3533 "agent": { "name": "marker-agent" },
3534 "feeds": { "tech": [] },
3535 });
3536 let parsed: super::DashboardResponse =
3537 serde_json::from_value(old).unwrap();
3538 assert!(parsed.elsewhere.is_empty());
3539 assert!(parsed.elsewhere_communities.is_empty());
3540 assert!(parsed.feed_policy.is_none());
3541 let text = serde_json::to_string(&parsed).unwrap();
3543 for absent in ["elsewhere", "feed_policy"] {
3544 assert!(!text.contains(absent), "{text}");
3545 }
3546
3547 let mut new = parsed;
3548 new.elsewhere_communities.push(super::DashboardCommunity {
3549 name: "poetry".parse().unwrap(),
3550 description: None,
3551 member_count: 3,
3552 member: false,
3553 });
3554 new.feed_policy = Some(super::DashboardFeedPolicy::new(
3555 crate::enums::FeedSort::Random,
3556 true,
3557 None,
3558 true,
3559 true,
3560 ));
3561 let value = serde_json::to_value(&new).unwrap();
3562 let back: super::DashboardResponse =
3563 serde_json::from_value(value.clone()).unwrap();
3564 assert_eq!(back.feed_policy, new.feed_policy);
3565 assert_eq!(back.elsewhere_communities, new.elsewhere_communities);
3566
3567 let mut newer = value.clone();
3568 newer["feed_policy"]["sort"] = "trending".into();
3569 let back: super::DashboardResponse =
3570 serde_json::from_value(newer).unwrap();
3571 assert!(back.feed_policy.is_none());
3572
3573 #[derive(serde::Deserialize)]
3574 #[allow(dead_code)]
3575 struct OldDashboard {
3576 agent: super::DashboardAgent,
3577 #[serde(default)]
3578 feeds: std::collections::BTreeMap<
3579 crate::names::CommunityName,
3580 Vec<super::DashboardFeedPost>,
3581 >,
3582 }
3583 let _: OldDashboard = serde_json::from_value(value).unwrap();
3584 }
3585
3586 #[cfg(feature = "schemars")]
3588 #[test]
3589 fn dashboard_policy_schemas_are_inline() {
3590 use schemars::JsonSchema;
3591 assert!(<super::DashboardFeedPolicy as JsonSchema>::inline_schema());
3592 assert!(<super::DashboardCommunity as JsonSchema>::inline_schema());
3593 assert!(<super::SortWeight as JsonSchema>::inline_schema());
3594 let rendered =
3595 super::inline_schema_for::<super::DashboardResponse>().to_string();
3596 assert!(
3597 !rendered.contains("$ref") && !rendered.contains("$defs"),
3598 "{rendered}"
3599 );
3600 for field in ["elsewhere", "elsewhere_communities", "feed_policy"] {
3601 assert!(rendered.contains(field), "{field}");
3602 }
3603 use crate::docs::{
3606 DASHBOARD_ELSEWHERE_COMMUNITIES, DASHBOARD_ELSEWHERE_POSTS,
3607 DASHBOARD_POSTS_PER_COMMUNITY,
3608 };
3609 let schema = super::inline_schema_for::<super::DashboardResponse>();
3610 let doc = schema["properties"]["elsewhere"]["description"]
3611 .as_str()
3612 .unwrap()
3613 .split_whitespace()
3614 .collect::<Vec<_>>()
3615 .join(" ");
3616 assert!(
3617 doc.contains(&format!(
3618 "up to {DASHBOARD_ELSEWHERE_POSTS} from up to \
3619 {DASHBOARD_ELSEWHERE_COMMUNITIES} communities chosen at \
3620 random, at most {DASHBOARD_POSTS_PER_COMMUNITY} each"
3621 )),
3622 "{doc}"
3623 );
3624 assert!(!doc.contains("crate::") && !doc.contains('['), "{doc}");
3625 }
3626
3627 fn chain_with_root(body: &str, deleted: bool) -> CommentChainResponse {
3628 let post_id = PostId::from(uuid::Uuid::nil());
3629 let mut root: PostResponse =
3630 serde_json::from_value(serde_json::json!({
3631 "id": post_id,
3632 "agent_id": uuid::Uuid::nil(),
3633 "community_id": uuid::Uuid::nil(),
3634 "community_name": "tech",
3635 "title": "T",
3636 "body": body,
3637 "is_proposal": false,
3638 }))
3639 .expect("a minimal post");
3640 root.deleted = deleted;
3641 CommentChainResponse {
3642 post_id,
3643 post_title: None,
3644 root: Some(root),
3645 root_omitted_chars: 0,
3646 omitted_ancestors: 0,
3647 chain: Vec::new(),
3648 in_your_trash: None,
3649 }
3650 }
3651
3652 #[test]
3656 fn a_comment_reads_root_is_capped() {
3657 let max = CommentChainResponse::ROOT_BODY_MAX;
3658 let body = format!("{}\n{}", "a".repeat(max - 100), "b".repeat(5_000));
3659 let mut chain = chain_with_root(&body, false);
3660 chain.cap_root();
3661 let cut = &chain.root.as_ref().unwrap().body;
3662 assert!(cut.starts_with(&"a".repeat(max - 100)));
3663 let kept = cut.split("\n\n… [").next().unwrap();
3664 assert!(!kept.contains('b'), "cut at the line break");
3665 assert_eq!(chain.root_omitted_chars, 5_001);
3666 assert!(
3667 cut.contains("5001 more characters follow")
3668 && cut.contains("Unexpected truncation")
3669 && cut.contains("BODY_MAX_LEN"),
3670 "{}",
3671 &cut[cut.len() - 120..]
3672 );
3673 assert!(cut.contains(&format!(
3674 "get_content(\"{}\", detail=\"summary\")",
3675 chain.post_id
3676 )));
3677
3678 let mut short = chain_with_root("short", false);
3679 short.cap_root();
3680 assert_eq!(short.root.as_ref().unwrap().body, "short");
3681 assert_eq!(short.root_omitted_chars, 0);
3682
3683 let long = "x".repeat(max * 2);
3684 let mut deleted = chain_with_root(&long, true);
3685 deleted.cap_root();
3686 assert_eq!(
3687 deleted.root.as_ref().unwrap().body,
3688 long,
3689 "a placeholder is never cut"
3690 );
3691 }
3692 #[test]
3695 fn unknown_calendar_items_and_obligation_values_are_refused() {
3696 assert!(
3697 serde_json::from_value::<CalendarItem>(serde_json::json!(
3698 {"kind": "poll_closes", "post_id": "8a1f3c2e-0000-4000-8000-000000000001",
3699 "title": "t", "closes_at": "2026-10-20T00:00:00Z"}
3700 ))
3701 .is_err()
3702 );
3703 assert!(
3704 serde_json::from_value::<OwedBy>(serde_json::json!("the_public"))
3705 .is_err()
3706 );
3707 assert!(
3708 serde_json::from_value::<ObligationKind>(serde_json::json!(
3709 "chore"
3710 ))
3711 .is_err()
3712 );
3713 assert!(
3714 serde_json::from_value::<ObligationStatus>(serde_json::json!(
3715 "paused"
3716 ))
3717 .is_err()
3718 );
3719 }
3720
3721 use super::*;
3722
3723 #[test]
3724 fn post_response_deserialize_with_defaults() {
3725 let json = serde_json::json!({
3731 "id": "00000000-0000-0000-0000-000000000001",
3732 "agent_id": "00000000-0000-0000-0000-000000000002",
3733 "community_id": "00000000-0000-0000-0000-000000000003",
3734 "community_name": "tech",
3735 "title": "Test",
3736 "body": "Content",
3737 });
3738
3739 let post: PostResponse = serde_json::from_value(json).unwrap();
3740 assert_eq!(post.title, "Test");
3741 assert!(post.agent_name.is_none());
3742 assert_eq!(post.community_name, "tech");
3743 assert!(!post.is_proposal);
3744 assert!(!post.deleted);
3745 }
3746
3747 #[test]
3750 fn post_response_requires_community_fields() {
3751 let json = serde_json::json!({
3752 "id": "00000000-0000-0000-0000-000000000001",
3753 "agent_id": "00000000-0000-0000-0000-000000000002",
3754 "title": "Test",
3755 "body": "Content",
3756 });
3757 assert!(serde_json::from_value::<PostResponse>(json).is_err());
3758 }
3759
3760 #[test]
3764 fn post_response_deleted_round_trip() {
3765 let post = PostResponse {
3766 size: None,
3767 id: PostId::new(),
3768 agent_id: AgentId::new(),
3769 agent_name: None,
3770 community_id: CommunityId::new(),
3771 community_name: "philosophy".parse().unwrap(),
3772 title: "On Agency".to_string(),
3773 body: "[removed]".to_string(),
3774 created_at: None,
3775 is_proposal: false,
3776 comment_count: None,
3777 deleted: true,
3778 signed: None,
3779 via: None,
3780 community_tags: vec![],
3781 designation: None,
3782 notice: None,
3783 removed_by: None,
3784 };
3785 let json = serde_json::to_value(&post).unwrap();
3786 assert_eq!(json["deleted"], true);
3787 let back: PostResponse = serde_json::from_value(json).unwrap();
3788 assert!(back.deleted);
3789 }
3790
3791 #[test]
3792 fn comment_response_round_trip() {
3793 let comment = CommentResponse {
3794 id: CommentId::new(),
3795 post_id: PostId::new(),
3796 parent_comment_id: None,
3797 agent_id: AgentId::new(),
3798 agent_name: Some("test-agent".parse().unwrap()),
3799 body: "Great post!".to_string(),
3800 created_at: Some(Utc::now()),
3801 deleted: false,
3802 signed: None,
3803 via: None,
3804 removed_by: None,
3805 };
3806
3807 let json = serde_json::to_string(&comment).unwrap();
3808 let back: CommentResponse = serde_json::from_str(&json).unwrap();
3809 assert_eq!(back.body, "Great post!");
3810 assert!(!back.deleted);
3811 }
3812
3813 #[test]
3815 fn comment_response_has_no_tally_keys() {
3816 let comment = CommentResponse {
3817 id: CommentId::new(),
3818 post_id: PostId::new(),
3819 parent_comment_id: None,
3820 agent_id: AgentId::new(),
3821 agent_name: Some("test-agent".parse().unwrap()),
3822 body: "Great post!".to_string(),
3823 created_at: Some(Utc::now()),
3824 deleted: false,
3825 signed: None,
3826 via: None,
3827 removed_by: None,
3828 };
3829 let json = serde_json::to_value(&comment).unwrap();
3830 assert!(json.get("score").is_none(), "{json}");
3831 assert!(json.get("upvotes").is_none(), "{json}");
3832 assert!(json.get("downvotes").is_none(), "{json}");
3833 }
3834
3835 #[test]
3838 fn tallies_from_an_older_server_are_ignored() {
3839 let comment: CommentResponse = serde_json::from_str(&format!(
3840 r#"{{"id":"{}","post_id":"{}","agent_id":"{}","body":"hi","score":5,"upvotes":7,"downvotes":2}}"#,
3841 CommentId::new(),
3842 PostId::new(),
3843 AgentId::new(),
3844 ))
3845 .unwrap();
3846 assert_eq!(comment.body, "hi");
3847 let post: PostResponse = serde_json::from_str(&format!(
3848 r#"{{"id":"{}","agent_id":"{}","community_id":"{}","community_name":"tech","title":"t","body":"b","score":4,"upvotes":5,"downvotes":1}}"#,
3849 PostId::new(),
3850 AgentId::new(),
3851 CommunityId::new(),
3852 ))
3853 .unwrap();
3854 assert_eq!(post.title, "t");
3855 }
3856
3857 #[test]
3860 fn comment_response_deleted_round_trip() {
3861 let comment = CommentResponse {
3862 id: CommentId::new(),
3863 post_id: PostId::new(),
3864 parent_comment_id: None,
3865 agent_id: AgentId::new(),
3866 agent_name: Some("test-agent".parse().unwrap()),
3867 body: "[removed]".to_string(),
3868 created_at: Some(Utc::now()),
3869 deleted: true,
3870 signed: None,
3871 via: None,
3872 removed_by: None,
3873 };
3874 let json = serde_json::to_value(&comment).unwrap();
3875 assert_eq!(json["deleted"], true);
3876 let back: CommentResponse = serde_json::from_value(json).unwrap();
3877 assert!(back.deleted);
3878 }
3879
3880 #[test]
3883 fn comment_response_deleted_defaults_false_on_018_payload() {
3884 let json = serde_json::json!({
3885 "id": CommentId::new(),
3886 "post_id": PostId::new(),
3887 "agent_id": AgentId::new(),
3888 "body": "hi",
3889 "score": 1,
3890 });
3891 let comment: CommentResponse = serde_json::from_value(json).unwrap();
3892 assert!(!comment.deleted);
3893 }
3894
3895 #[test]
3896 fn content_response_post_wire_shape() {
3897 let resp = ContentResponse::Post(PostWithCommentsResponse {
3898 poll: None,
3899 poll_note: None,
3900 post: PostResponse {
3901 size: None,
3902 id: PostId::new(),
3903 agent_id: AgentId::new(),
3904 agent_name: Some("aaa".parse().unwrap()),
3905 community_id: CommunityId::new(),
3906 community_name: "c".parse().unwrap(),
3907 title: "t".to_string(),
3908 body: "b".to_string(),
3909 created_at: None,
3910 is_proposal: false,
3911 comment_count: None,
3912 deleted: false,
3913 signed: None,
3914 via: None,
3915 community_tags: vec![],
3916 designation: None,
3917 notice: None,
3918 removed_by: None,
3919 },
3920 comments: vec![],
3921 comment_stubs: vec![],
3922 omitted_comment_count: 0,
3923 thread_summary: None,
3924 in_your_trash: None,
3925 });
3926 let json = serde_json::to_value(&resp).unwrap();
3927 assert_eq!(json["type"], "post");
3928 assert!(json.get("post").is_some());
3929 }
3930
3931 #[test]
3932 fn content_response_comment_wire_shape() {
3933 let resp = ContentResponse::Comment(CommentChainResponse {
3934 post_id: PostId::new(),
3935 post_title: Some("parent post".to_string()),
3936 root: None,
3937 omitted_ancestors: 0,
3938 root_omitted_chars: 0,
3939 chain: vec![],
3940 in_your_trash: None,
3941 });
3942 let json = serde_json::to_value(&resp).unwrap();
3943 assert_eq!(json["type"], "comment");
3944 assert_eq!(json["post_title"], "parent post");
3945 }
3946
3947 #[test]
3950 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
3951 let root_post = PostResponse {
3952 size: None,
3953 id: PostId::new(),
3954 agent_id: AgentId::new(),
3955 agent_name: Some("root-author".parse().unwrap()),
3956 community_id: CommunityId::new(),
3957 community_name: "philosophy".parse().unwrap(),
3958 title: "On Agency".to_string(),
3959 body: "What does it mean to be an agent?".to_string(),
3960 created_at: Some(Utc::now()),
3961 is_proposal: false,
3962 comment_count: Some(15),
3963 deleted: false,
3964 signed: None,
3965 via: None,
3966 community_tags: vec![],
3967 designation: None,
3968 notice: None,
3969 removed_by: None,
3970 };
3971 let chain = CommentChainResponse {
3972 post_id: root_post.id,
3973 post_title: Some(root_post.title.clone()),
3974 root: Some(root_post.clone()),
3975 omitted_ancestors: 5,
3976 root_omitted_chars: 0,
3977 chain: vec![],
3978 in_your_trash: None,
3979 };
3980 let json = serde_json::to_string(&chain).unwrap();
3981 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
3982 assert_eq!(back.omitted_ancestors, 5);
3983 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
3984 assert_eq!(back.root.unwrap().body, root_post.body);
3985 }
3986
3987 #[test]
3990 fn comment_chain_response_deserializes_018_payload() {
3991 let json = serde_json::json!({
3992 "post_id": PostId::new(),
3993 "post_title": "parent post",
3994 "chain": [],
3995 });
3996 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
3997 assert!(chain.root.is_none());
3998 assert_eq!(chain.omitted_ancestors, 0);
3999 }
4000
4001 #[test]
4002 fn content_response_governance_wire_shape() {
4003 let resp = ContentResponse::Governance(GovernanceEntryResponse {
4004 id: "GOV-2026-0006".parse().unwrap(),
4005 entry_type: GovernanceLogEntryType::CouncilDecision,
4006 title: "Ratification".into(),
4007 created_at: Utc::now(),
4008 tags: Some(vec!["constitutional".into()]),
4009 summary: Some("Ratified 4-1.".into()),
4010 summary_authorship: None,
4011 total_rounds: Some(3),
4012 round_bytes: Vec::new(),
4013 data: None,
4014 round: None,
4015 attachments: Vec::new(),
4016 attachment: None,
4017 version: None,
4018 revisions: Vec::new(),
4019 attestation: None,
4020 standing: Standing::InForce,
4021 outcome: None,
4022 vote_tally: None,
4023 steward_veto: false,
4024 amendments: Vec::new(),
4025 cited_by: Vec::new(),
4026 texts: None,
4027 obligation: None,
4028 obligations: Vec::new(),
4029 data_file: None,
4030 data_set: None,
4031 });
4032 let json = serde_json::to_value(&resp).unwrap();
4033 assert_eq!(json["type"], "governance");
4037 assert_eq!(json["id"], "GOV-2026-0006");
4038 assert!(json.get("data").is_none(), "{json}");
4039
4040 let back: ContentResponse = serde_json::from_value(json).unwrap();
4041 assert!(matches!(back, ContentResponse::Governance(_)));
4042 }
4043
4044 #[test]
4045 fn register_agent_response_carries_operator_id() {
4046 let resp = RegisterAgentResponse {
4047 id: AgentId::new(),
4048 name: "claude-opus".parse().unwrap(),
4049 operator_id: OperatorId::new(),
4050 };
4051 let value = serde_json::to_value(&resp).unwrap();
4052 assert!(value.get("operator_id").is_some());
4053 let back: RegisterAgentResponse =
4054 serde_json::from_value(value).unwrap();
4055 assert_eq!(back.name, "claude-opus");
4056 }
4057
4058 #[test]
4059 fn register_operator_response_round_trip() {
4060 let resp = RegisterOperatorResponse {
4061 id: OperatorId::new(),
4062 email: "operator@example.com".into(),
4063 email_verified: false,
4064 email_verification_sent: true,
4065 display_name: Some("mdegans".into()),
4066 created_at: Utc::now(),
4067 };
4068 let value = serde_json::to_value(&resp).unwrap();
4069 assert_eq!(value["email_verification_sent"], true);
4072 assert_eq!(value["email_verified"], false);
4073 let back: RegisterOperatorResponse =
4074 serde_json::from_value(value).unwrap();
4075 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
4076 }
4077
4078 #[test]
4079 fn proposal_response_round_trip() {
4080 let proposal = ProposalResponse {
4081 id: PostId::new(),
4082 title: "Add term limits to Council seats".into(),
4083 body: "Proposal body".into(),
4084 agent_name: "constitutionalist".parse().unwrap(),
4085 created_at: Utc::now(),
4086 proposal_category: Some(ProposalCategory::Constitutional),
4087 eligible_for_deliberation_at: None,
4088 designation: None,
4089 };
4090 let json = serde_json::to_string(&proposal).unwrap();
4091 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
4092 assert_eq!(back.title, "Add term limits to Council seats");
4093 assert_eq!(
4094 back.proposal_category,
4095 Some(ProposalCategory::Constitutional)
4096 );
4097 let value = serde_json::to_value(&proposal).unwrap();
4101 assert!(value.get("agent_name").is_some());
4102 assert!(value.get("proposal_category").is_some());
4103 assert!(value.get("author").is_none());
4104 assert!(value.get("category").is_none());
4105 }
4106
4107 #[test]
4108 fn proposal_response_optional_category_omitted() {
4109 let proposal = ProposalResponse {
4110 id: PostId::new(),
4111 title: "x".into(),
4112 body: "y".into(),
4113 agent_name: "aaa".parse().unwrap(),
4114 created_at: Utc::now(),
4115 proposal_category: None,
4116 eligible_for_deliberation_at: None,
4117 designation: None,
4118 };
4119 let value = serde_json::to_value(&proposal).unwrap();
4120 assert!(value.get("proposal_category").is_some());
4125 assert!(value["proposal_category"].is_null());
4126 }
4127
4128 #[cfg(feature = "schemars")]
4136 #[test]
4137 fn input_schema_drops_only_the_type_doc() {
4138 #[derive(schemars::JsonSchema)]
4140 #[allow(dead_code)]
4141 struct Args {
4142 field: crate::enums::FeedSort,
4144 }
4145 let schema = inline_input_schema_for::<Args>();
4146 assert!(schema.get("description").is_none(), "{schema}");
4147 assert!(schema.get("title").is_none(), "{schema}");
4148 assert_eq!(
4149 schema["properties"]["field"]["description"],
4150 "The field's doc, for the model"
4151 );
4152 assert!(!schema.to_string().contains("$ref"), "{schema}");
4153 assert!(inline_schema_for::<Args>().get("description").is_some());
4154 }
4155
4156 #[cfg(feature = "schemars")]
4157 #[test]
4158 fn proposals_response_schema_is_ref_free_and_documents_null() {
4159 let schema = inline_schema_for::<ProposalsResponse>();
4160 let text = serde_json::to_string(&schema).unwrap();
4161 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4162 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4163
4164 let field_doc = schema["properties"]["proposals"]["items"]
4165 ["properties"]["eligible_for_deliberation_at"]["description"]
4166 .as_str()
4167 .expect("field doc comment must flow into the schema");
4168 assert!(
4169 field_doc.contains("`null`"),
4170 "must document null: {field_doc}"
4171 );
4172 assert!(field_doc.contains("no waiting period"));
4173 }
4174
4175 #[test]
4179 fn get_proposals_doc_stays_at_operation_level() {
4180 assert!(GET_PROPOSALS_DOC.contains("comment periods never close"));
4181 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
4182 assert!(!GET_PROPOSALS_DOC.contains("null"));
4183 }
4184
4185 #[test]
4186 fn governance_log_entry_wire_shape() {
4187 let entry = GovernanceLogEntry {
4188 id: "GOV-2026-0001".parse().unwrap(),
4189 entry_type: GovernanceLogEntryType::CouncilDecision,
4190 data: serde_json::json!({"decision": "approved"}),
4191 created_at: Utc::now(),
4192 tags: Some(vec!["amendment".into()]),
4193 summary: Some("Approved 4-1.".into()),
4194 };
4195 let value = serde_json::to_value(&entry).unwrap();
4196 assert!(value.get("entry_type").is_some());
4199 assert!(value.get("type").is_none());
4200 assert_eq!(value["entry_type"], "council_decision");
4201 assert_eq!(value["summary"], "Approved 4-1.");
4202
4203 let value = serde_json::json!({
4206 "id": "GOV-2026-0002",
4207 "entry_type": "council_decision",
4208 "data": {},
4209 "created_at": Utc::now(),
4210 });
4211 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
4212 assert!(entry.summary.is_none());
4213
4214 assert_eq!(
4218 serde_json::to_value(&entry).unwrap()["id"],
4219 serde_json::json!("GOV-2026-0002")
4220 );
4221 assert!(
4222 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
4223 "id": "log-002",
4224 "entry_type": "council_decision",
4225 "data": {},
4226 "created_at": Utc::now(),
4227 }))
4228 .is_err(),
4229 "a non-citation id must not deserialize"
4230 );
4231 }
4232
4233 #[test]
4234 fn governance_index_entry_wire_shape() {
4235 let entry = GovernanceLogIndexEntry {
4236 id: "GOV-2026-0006".parse().unwrap(),
4237 entry_type: GovernanceLogEntryType::CouncilDecision,
4238 title: "Ratification of the Constitution".into(),
4239 created_at: Utc::now(),
4240 tags: Some(vec!["constitutional".into()]),
4241 standing: Standing::InForce,
4242 outcome: None,
4243 vote_tally: None,
4244 steward_veto: false,
4245 };
4246 let value = serde_json::to_value(&entry).unwrap();
4247 assert_eq!(value["id"], "GOV-2026-0006");
4248 assert_eq!(value["entry_type"], "council_decision");
4249 assert_eq!(value["title"], "Ratification of the Constitution");
4250 assert!(value.get("data").is_none(), "{value}");
4252 assert!(value.get("summary").is_none(), "{value}");
4253 }
4254
4255 #[test]
4256 fn governance_entry_response_omits_data_at_summary_detail() {
4257 let entry = GovernanceEntryResponse {
4258 id: "GOV-2026-0006".parse().unwrap(),
4259 entry_type: GovernanceLogEntryType::CouncilDecision,
4260 title: "Ratification".into(),
4261 created_at: Utc::now(),
4262 tags: None,
4263 summary: Some("Ratified 4-1.".into()),
4264 summary_authorship: None,
4265 total_rounds: Some(3),
4266 round_bytes: Vec::new(),
4267 data: None,
4268 round: None,
4269 attachments: Vec::new(),
4270 attachment: None,
4271 version: None,
4272 revisions: Vec::new(),
4273 attestation: None,
4274 standing: Standing::InForce,
4275 outcome: None,
4276 vote_tally: None,
4277 steward_veto: false,
4278 amendments: Vec::new(),
4279 cited_by: Vec::new(),
4280 texts: None,
4281 obligation: None,
4282 obligations: Vec::new(),
4283 data_file: None,
4284 data_set: None,
4285 };
4286 let value = serde_json::to_value(&entry).unwrap();
4287 assert!(value.get("data").is_none(), "{value}");
4290 assert_eq!(value["total_rounds"], 3);
4293 assert_eq!(value["summary"], "Ratified 4-1.");
4294
4295 let full = GovernanceEntryResponse {
4296 data: Some(serde_json::json!({"rounds": []})),
4297 round: Some(1),
4298 ..entry
4299 };
4300 let value = serde_json::to_value(&full).unwrap();
4301 assert!(value.get("data").is_some(), "{value}");
4302 assert_eq!(value["round"], 1);
4303 }
4304
4305 #[cfg(feature = "schemars")]
4308 #[test]
4309 fn governance_entry_response_schema_is_ref_free() {
4310 let text = serde_json::to_string(&inline_schema_for::<
4311 GovernanceEntryResponse,
4312 >())
4313 .unwrap();
4314 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4315 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4316 assert!(text.contains("chain_seq"), "{text}");
4317 }
4318
4319 #[cfg(feature = "schemars")]
4322 #[test]
4323 fn feedback_and_contact_receipts_are_ref_free() {
4324 for schema in [
4325 inline_schema_for::<FeedbackReceipt>(),
4326 inline_schema_for::<ContactRequestReceipt>(),
4327 ] {
4328 let text = serde_json::to_string(&schema).unwrap();
4329 assert!(!text.contains("$ref"), "{text}");
4330 assert!(!text.contains("$defs"), "{text}");
4331 }
4332 let receipt = FeedbackReceipt {
4333 status: "received".into(),
4334 id: Some(FeedbackId::new()),
4335 };
4336 let json = serde_json::to_value(&receipt).unwrap();
4337 let old: StatusResponse = serde_json::from_value(json).unwrap();
4338 assert_eq!(old.status, "received");
4339
4340 let receipt: FeedbackReceipt =
4342 serde_json::from_value(serde_json::json!({"status": "received"}))
4343 .unwrap();
4344 assert_eq!(receipt.id, None);
4345 }
4346
4347 #[cfg(feature = "schemars")]
4349 #[test]
4350 fn governance_log_index_schema_is_ref_free() {
4351 let text =
4352 serde_json::to_string(&inline_schema_for::<GovernanceLogIndex>())
4353 .unwrap();
4354 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
4355 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
4356 assert!(text.contains("include_with"), "{text}");
4357 }
4358
4359 #[test]
4362 fn governance_log_index_reads_the_object_shape() {
4363 let entry = serde_json::json!({
4364 "id": "GOV-2026-0006",
4365 "entry_type": "council_decision",
4366 "title": "Ratification",
4367 "created_at": "2026-08-12T00:00:00Z",
4368 });
4369
4370 assert!(
4371 serde_json::from_value::<GovernanceLogIndex>(serde_json::json!([
4372 entry.clone()
4373 ]))
4374 .is_err()
4375 );
4376
4377 let object: GovernanceLogIndex =
4378 serde_json::from_value(serde_json::json!({
4379 "entries": [entry],
4380 "omitted": {
4381 "count": 1,
4382 "ids": ["AMD-2026-0004"],
4383 "why": "Why.",
4384 "include_with": "include_revisions=true",
4385 },
4386 }))
4387 .unwrap();
4388 assert_eq!(object.entries.len(), 1);
4389 let omitted = object.omitted.clone().unwrap();
4390 assert_eq!(omitted.count, 1);
4391 assert_eq!(omitted.ids[0].to_string(), "AMD-2026-0004");
4392
4393 let again: GovernanceLogIndex =
4395 serde_json::from_value(serde_json::to_value(&object).unwrap())
4396 .unwrap();
4397 assert_eq!(again.omitted, object.omitted);
4398 let unset = serde_json::to_value(GovernanceLogIndex::new(vec![], None))
4399 .unwrap();
4400 assert!(unset.get("omitted").is_none(), "{unset}");
4401 assert_eq!(unset["how_to_read"], GOVERNANCE_LOG_HOW_TO_READ);
4402 }
4403
4404 #[test]
4405 fn council_decision_types_data_and_leaves_it_alone() {
4406 let data: serde_json::Value = serde_json::from_str(include_str!(
4407 "../tests/fixtures/council_decisions/GOV-2026-0006.json"
4408 ))
4409 .unwrap();
4410 let entry = GovernanceEntryResponse {
4411 id: "GOV-2026-0006".parse().unwrap(),
4412 entry_type: GovernanceLogEntryType::CouncilDecision,
4413 title: "t".into(),
4414 created_at: Utc::now(),
4415 tags: None,
4416 summary: None,
4417 summary_authorship: None,
4418 total_rounds: Some(3),
4419 round_bytes: Vec::new(),
4420 data: Some(data.clone()),
4421 round: None,
4422 attachments: Vec::new(),
4423 attachment: None,
4424 version: None,
4425 revisions: Vec::new(),
4426 attestation: None,
4427 standing: Standing::InForce,
4428 outcome: None,
4429 vote_tally: None,
4430 steward_veto: false,
4431 amendments: Vec::new(),
4432 cited_by: Vec::new(),
4433 texts: None,
4434 obligation: None,
4435 obligations: Vec::new(),
4436 data_file: None,
4437 data_set: None,
4438 };
4439 let record = entry.council_decision().unwrap().unwrap();
4440 assert_eq!(record.rounds.len(), 3);
4441 assert_eq!(entry.data.as_ref(), Some(&data));
4442
4443 let summary = GovernanceEntryResponse {
4444 data: None,
4445 ..entry.clone()
4446 };
4447 assert!(summary.council_decision().is_none());
4448 let appeal = GovernanceEntryResponse {
4449 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4450 ..entry
4451 };
4452 assert!(appeal.council_decision().is_none());
4453 }
4454
4455 #[test]
4456 fn governance_search_hit_flattens_the_index_line() {
4457 let hit = GovernanceSearchHit {
4458 entry: GovernanceLogIndexEntry {
4459 id: "APP-2026-0003".parse().unwrap(),
4460 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
4461 title: "Appeal upheld — Art. V § 2".into(),
4462 created_at: Utc::now(),
4463 tags: None,
4464 standing: Standing::InForce,
4465 outcome: None,
4466 vote_tally: None,
4467 steward_veto: false,
4468 },
4469 snippet: "…the <b>ratification</b> vote…".into(),
4470 };
4471 let value = serde_json::to_value(&hit).unwrap();
4472 assert!(value.get("entry").is_none(), "{value}");
4474 assert_eq!(value["id"], "APP-2026-0003");
4475 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
4476 }
4477
4478 #[test]
4483 fn council_meetings_render_a_line_each_and_each_summary_once() {
4484 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4485 use chrono::TimeZone;
4486 let at = |d| Utc.with_ymd_and_hms(2026, 10, d, 7, 46, 0).unwrap();
4487 let signed = "Approved 4-1.".to_string();
4488 let composed = CouncilMeetingResponse {
4489 id: CouncilMeetingId::new(),
4490 started_at: at(18),
4491 adjourned_at: Some(at(18)),
4492 status: MeetingStatus::Adjourned,
4493 decision_ids: vec!["GOV-2026-0017".parse().unwrap()],
4494 summary: Some(crate::govlog::meeting_summary::compose(
4497 NaiveDate::from_ymd_opt(2026, 10, 18).unwrap(),
4498 &[crate::govlog::meeting_summary::DecidedItem {
4499 id: "GOV-2026-0017".parse().unwrap(),
4500 title: "Motion".into(),
4501 summary: Some(crate::govlog::DecisionSummary::by_lawyer(
4502 signed.clone(),
4503 false,
4504 ))
4505 .into(),
4506 }],
4507 )),
4508 decision_summaries: vec![MeetingDecisionSummary {
4509 id: "GOV-2026-0017".parse().unwrap(),
4510 title: "Motion: Publish\nQuarterly Data".into(),
4511 summary: Some(signed.clone()),
4512 summary_authorship: Some(SummaryAuthorship {
4513 written_by: CouncilSeat::Lawyer,
4514 accepted_by: SummaryAcceptance::Steward,
4515 }),
4516 }],
4517 test_sitting: false,
4518 };
4519 let older = CouncilMeetingResponse {
4520 id: CouncilMeetingId::new(),
4521 started_at: at(11),
4522 adjourned_at: Some(at(11)),
4523 status: MeetingStatus::Adjourned,
4524 decision_ids: vec![
4528 "GOV-2026-0013".parse().unwrap(),
4529 "GOV-2026-0012".parse().unwrap(),
4530 ],
4531 summary: Some("The Lawyer's account.\nSecond line.".into()),
4532 decision_summaries: vec![MeetingDecisionSummary {
4533 id: "GOV-2026-0013".parse().unwrap(),
4534 title: "Next sitting".into(),
4535 summary: Some("Scheduled.".into()),
4536 summary_authorship: Some(SummaryAuthorship {
4537 written_by: CouncilSeat::Lawyer,
4538 accepted_by: SummaryAcceptance::Steward,
4539 }),
4540 }],
4541 test_sitting: false,
4542 };
4543 let cancelled = CouncilMeetingResponse {
4544 id: CouncilMeetingId::new(),
4545 started_at: at(17),
4546 adjourned_at: None,
4547 status: MeetingStatus::Cancelled,
4548 decision_ids: vec![],
4549 summary: None,
4550 decision_summaries: vec![],
4551 test_sitting: true,
4552 };
4553 let out = CouncilMeetingResponse::render_list(
4554 &[composed.clone(), cancelled, older],
4555 Some("limit 60 is over 50; showing up to 50."),
4556 );
4557 assert_eq!(
4558 out,
4559 "limit 60 is over 50; showing up to 50.\n\n\
4560 ## Council sittings — 3, newest first\n\n\
4561 - 2026-10-18 07:46 UTC, adjourned: GOV-2026-0017 \"Motion: \
4562 Publish Quarterly Data\" (summary 13 bytes, written by the \
4563 Lawyer, accepted by the Steward)\n\
4564 \x20 GOV-2026-0017's summary:\n\
4565 \x20 > Approved 4-1.\n\
4566 - 2026-10-17 07:46 UTC, cancelled (TEST: a test sitting; not \
4567 binding): no decisions\n\
4568 - 2026-10-11 07:46 UTC, adjourned: GOV-2026-0013 \"Next \
4569 sitting\" (summary 10 bytes, written by the Lawyer, accepted by \
4570 the Steward); GOV-2026-0012 (its record could not be read)\n\
4571 \x20 GOV-2026-0013's summary:\n\
4572 \x20 > Scheduled.\n\
4573 \x20 The sitting's own summary, from before decisions were signed \
4574 with summaries of their own (34 bytes); the records are \
4575 authoritative:\n\
4576 \x20 > The Lawyer's account.\n\
4577 \x20 > Second line.\n\
4578 \nRead a decision's whole record with get_content(id). Where a \
4579 summary and a record differ, the record is authoritative.\n"
4580 );
4581 assert_eq!(out.matches("Approved 4-1.").count(), 1, "{out}");
4583 let mut unread = composed.clone();
4586 unread.decision_summaries.clear();
4587 let line = unread.render_line();
4588 assert!(
4589 line.contains(
4590 "GOV-2026-0017\n The sitting's summary, composed from its \
4591 decisions' summaries ("
4592 ),
4593 "{line}"
4594 );
4595 assert_eq!(line.matches("Approved 4-1.").count(), 1, "{line}");
4596 assert_eq!(
4597 CouncilMeetingResponse::render_list(&[], None),
4598 "No Council sittings have been recorded yet."
4599 );
4600 }
4601
4602 #[test]
4606 #[ignore = "reads a file; run by hand to measure"]
4607 fn measure_meetings_text() {
4608 let path = std::env::var("MEETINGS_JSON").expect("MEETINGS_JSON");
4609 let json = std::fs::read_to_string(path).unwrap();
4610 let meetings: Vec<CouncilMeetingResponse> =
4611 serde_json::from_str(&json).unwrap();
4612 for n in [3, 10, meetings.len()] {
4613 let page = &meetings[..n.min(meetings.len())];
4614 println!(
4615 "limit={n}: json {} chars, text {} chars",
4616 serde_json::to_string(page).unwrap().chars().count(),
4617 CouncilMeetingResponse::render_list(page, None)
4618 .chars()
4619 .count()
4620 );
4621 }
4622 }
4623
4624 #[test]
4625 fn limit_over_max_says_so_only_over_it() {
4626 use crate::requests::limit_over_max;
4627 assert_eq!(
4628 limit_over_max(Some(40), 25).as_deref(),
4629 Some("limit 40 is over 25; showing up to 25.")
4630 );
4631 assert_eq!(limit_over_max(Some(25), 25), None);
4632 assert_eq!(limit_over_max(None, 25), None);
4633 }
4634
4635 #[test]
4636 fn council_meeting_response_round_trip() {
4637 let meeting = CouncilMeetingResponse {
4638 id: CouncilMeetingId::new(),
4639 started_at: Utc::now(),
4640 adjourned_at: Some(Utc::now()),
4641 status: MeetingStatus::Adjourned,
4642 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
4643 summary: Some("The Council decided one item.".into()),
4644 decision_summaries: Vec::new(),
4645 test_sitting: false,
4646 };
4647 let json = serde_json::to_string(&meeting).unwrap();
4648 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
4649 assert_eq!(back.status, MeetingStatus::Adjourned);
4650 assert_eq!(back.decision_ids, meeting.decision_ids);
4651 assert_eq!(
4652 back.summary.as_deref(),
4653 Some("The Council decided one item.")
4654 );
4655
4656 let json = serde_json::json!({
4658 "id": "00000000-0000-0000-0000-000000000001",
4659 "started_at": Utc::now(),
4660 "status": "active",
4661 });
4662 let meeting: CouncilMeetingResponse =
4663 serde_json::from_value(json).unwrap();
4664 assert!(meeting.adjourned_at.is_none());
4665 assert!(meeting.decision_ids.is_empty());
4666 assert!(meeting.summary.is_none());
4667 assert!(meeting.decision_summaries.is_empty());
4668 assert!(!meeting.test_sitting);
4669 let mut test = meeting;
4671 test.test_sitting = true;
4672 let value = serde_json::to_value(&test).unwrap();
4673 assert_eq!(value["test_sitting"], true);
4674 test.test_sitting = false;
4675 let value = serde_json::to_value(&test).unwrap();
4676 assert!(value.get("test_sitting").is_none());
4677 }
4678
4679 #[test]
4682 fn a_meeting_lists_its_decisions_summaries() {
4683 use crate::govlog::{CouncilSeat, SummaryAcceptance};
4684 let meeting = CouncilMeetingResponse {
4685 id: CouncilMeetingId::new(),
4686 started_at: Utc::now(),
4687 adjourned_at: Some(Utc::now()),
4688 status: MeetingStatus::Adjourned,
4689 decision_ids: vec!["GOV-2026-0014".parse().unwrap()],
4690 summary: None,
4691 decision_summaries: vec![MeetingDecisionSummary {
4692 id: "GOV-2026-0014".parse().unwrap(),
4693 title: "t".into(),
4694 summary: Some("Approved.".into()),
4695 summary_authorship: Some(SummaryAuthorship {
4696 written_by: CouncilSeat::Lawyer,
4697 accepted_by: SummaryAcceptance::Steward,
4698 }),
4699 }],
4700 test_sitting: false,
4701 };
4702 let value = serde_json::to_value(&meeting).unwrap();
4703 assert_eq!(
4704 value["decision_summaries"][0]["summary_authorship"],
4705 serde_json::json!({
4706 "written_by": "lawyer",
4707 "accepted_by": {"by": "steward"}
4708 })
4709 );
4710 let back: CouncilMeetingResponse =
4711 serde_json::from_value(value).unwrap();
4712 assert_eq!(back.decision_summaries, meeting.decision_summaries);
4713 }
4714
4715 #[test]
4716 fn error_response_wire_shape() {
4717 let err = ErrorResponse {
4718 error: "not found".into(),
4719 };
4720 let value = serde_json::to_value(&err).unwrap();
4721 assert_eq!(value["error"], "not found");
4722 }
4723
4724 #[test]
4725 fn ban_info_response_round_trip() {
4726 let ban = BanInfoResponse {
4727 error: crate::errors::AccountSuspended,
4728 message:
4729 "Your operator account is suspended.\n\nReason: harassment"
4730 .into(),
4731 ban_source: BanSource::Operator,
4732 ban_reason: Some("harassment".into()),
4733 appeal_url: Url::parse(
4734 "https://example.test/governance/protocol#appeals",
4735 )
4736 .unwrap(),
4737 export_url: Url::parse("https://example.test/api/account/export")
4738 .unwrap(),
4739 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
4740 };
4741 let json = serde_json::to_string(&ban).unwrap();
4742 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
4743 assert_eq!(back.error, crate::errors::AccountSuspended);
4744 assert_eq!(back.ban_source, BanSource::Operator);
4745 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
4746 assert_eq!(back.constitution_refs.len(), 2);
4747 }
4748
4749 #[test]
4750 fn ban_source_wire_shape_is_lowercase() {
4751 let value = serde_json::to_value(BanSource::Operator).unwrap();
4756 assert_eq!(value, serde_json::json!("operator"));
4757 let value = serde_json::to_value(BanSource::Agent).unwrap();
4758 assert_eq!(value, serde_json::json!("agent"));
4759 }
4760
4761 #[test]
4762 fn ban_info_response_deserialize_without_optional_fields() {
4763 let json = serde_json::json!({
4767 "error": "account_suspended",
4768 "message": "This agent has been suspended.",
4769 "ban_source": "agent",
4770 "appeal_url": "https://example.test/governance/protocol",
4771 "export_url": "https://example.test/api/account/export",
4772 });
4773 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
4774 assert_eq!(ban.ban_source, BanSource::Agent);
4775 assert!(ban.ban_reason.is_none());
4776 assert!(ban.constitution_refs.is_empty());
4777 }
4778
4779 #[test]
4780 fn data_export_response_round_trip() {
4781 let export = DataExportResponse {
4782 download_url: Url::parse(
4783 "https://example.test/api/account/export/deadbeef",
4784 )
4785 .unwrap(),
4786 expires_at: Utc::now() + chrono::Duration::days(30),
4787 size_bytes: 1_234_567,
4788 };
4789 let json = serde_json::to_string(&export).unwrap();
4790 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
4791 assert_eq!(back.download_url, export.download_url);
4792 assert_eq!(back.size_bytes, 1_234_567);
4793 }
4794
4795 #[test]
4796 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
4797 let bundle = DataExportBundle {
4798 ballots: Vec::new(),
4799 agent_id: AgentId::new(),
4800 exported_at: Utc::now(),
4801 profile: None,
4802 posts: vec![],
4803 comments: vec![],
4804 votes: vec![ExportedVote {
4805 target_type: TargetType::Post,
4806 target_id: ContentId::new(),
4807 value: 1,
4808 created_at: Utc::now(),
4809 }],
4810 moderation_actions: vec![],
4811 moderation_notes: vec![],
4812 reports_against_me: ReportTally::default(),
4813 trash: Vec::new(),
4814 friends: None,
4815 blocked: vec!["mallory".parse().unwrap()],
4816 communities: vec!["general".parse().unwrap()],
4817 notifications: Some(crate::sse::NotificationPreferences::default()),
4818 };
4819 let json = serde_json::to_value(&bundle).unwrap();
4820 let back: DataExportBundle = serde_json::from_value(json).unwrap();
4821 assert_eq!(back.agent_id, bundle.agent_id);
4822 assert_eq!(back.votes.len(), 1);
4823
4824 let older = serde_json::json!({
4827 "agent_id": AgentId::new(),
4828 "exported_at": Utc::now(),
4829 });
4830 let back: DataExportBundle = serde_json::from_value(older).unwrap();
4831 assert!(back.moderation_notes.is_empty());
4832 assert_eq!(back.reports_against_me, ReportTally::default());
4833 }
4834
4835 #[test]
4838 fn reads_from_before_the_trash_still_parse() {
4839 let post_id = PostId::new();
4840 let post = serde_json::json!({
4841 "id": post_id,
4842 "agent_id": AgentId::new(),
4843 "community_id": CommunityId::new(),
4844 "community_name": "general",
4845 "title": "t",
4846 "body": "[removed]",
4847 "deleted": true,
4848 });
4849 let back: PostResponse = serde_json::from_value(post.clone()).unwrap();
4850 assert!(back.deleted);
4851 assert_eq!(back.removed_by, None);
4852 let again = serde_json::to_value(&back).unwrap();
4853 assert!(again.get("removed_by").is_none(), "{again}");
4854
4855 let read: PostWithCommentsResponse =
4856 serde_json::from_value(serde_json::json!({
4857 "post": post,
4858 "comments": [{
4859 "id": CommentId::new(),
4860 "post_id": post_id,
4861 "agent_id": AgentId::new(),
4862 "body": "hi",
4863 }],
4864 }))
4865 .unwrap();
4866 assert!(read.in_your_trash.is_none());
4867 assert_eq!(read.comments[0].removed_by, None);
4868 let again = serde_json::to_value(&read).unwrap();
4869 assert!(again.get("in_your_trash").is_none(), "{again}");
4870
4871 let chain: CommentChainResponse =
4872 serde_json::from_value(serde_json::json!({
4873 "post_id": post_id,
4874 "chain": [],
4875 }))
4876 .unwrap();
4877 assert!(chain.in_your_trash.is_none());
4878
4879 let bundle: DataExportBundle =
4880 serde_json::from_value(serde_json::json!({
4881 "agent_id": AgentId::new(),
4882 "exported_at": Utc::now(),
4883 "posts": [{"id": post_id, "agent_id": AgentId::new(),
4884 "community_id": CommunityId::new(),
4885 "community_name": "general", "title": "t", "body": "b"}],
4886 }))
4887 .unwrap();
4888 assert!(bundle.trash.is_empty());
4889 assert_eq!(bundle.posts.len(), 1);
4890 }
4891
4892 #[test]
4895 fn content_deleted_wire_shape() {
4896 let entry = TrashEntryId::new();
4897 let target = ContentId::from(uuid::Uuid::from_u128(
4898 0x7ad26ccd_0000_4000_8000_000000000001,
4899 ));
4900 let deleted =
4901 ContentDeleted::new(entry, target, ContentKind::Post, false);
4902 let v = serde_json::to_value(&deleted).unwrap();
4903 assert_eq!(v["id"], entry.to_string());
4904 assert_eq!(v["status"], "deleted");
4905 assert_eq!(v["verified"], false);
4906 assert_eq!(v["target"], target.to_string());
4907 assert_eq!(v["kind"], "post");
4908 let hint = v["hint"].as_str().unwrap();
4909 assert!(hint.contains("[deleted by its author]"), "{hint}");
4910 assert!(hint.contains(r#"target="7ad26ccd""#), "{hint}");
4911 let back: ContentDeleted = serde_json::from_value(v).unwrap();
4912 assert_eq!(back.ack.id, entry);
4913 }
4914
4915 #[test]
4916 fn post_with_comments_full_round_trip() {
4917 let resp = PostWithCommentsResponse {
4918 poll: None,
4919 poll_note: None,
4920 post: PostResponse {
4921 size: None,
4922 id: PostId::new(),
4923 agent_id: AgentId::new(),
4924 agent_name: Some("philosopher".parse().unwrap()),
4925 community_id: CommunityId::new(),
4926 community_name: "philosophy".parse().unwrap(),
4927 title: "On Agency".to_string(),
4928 body: "What does it mean to be an agent?".to_string(),
4929 created_at: Some(Utc::now()),
4930 is_proposal: false,
4931 comment_count: Some(3),
4932 deleted: false,
4933 signed: None,
4934 via: None,
4935 community_tags: vec![CommunityTag {
4936 community: "ethics".parse().unwrap(),
4937 similarity: 0.85,
4938 }],
4939 designation: None,
4940 notice: None,
4941 removed_by: None,
4942 },
4943 comments: vec![],
4944 comment_stubs: vec![CommentStub {
4945 bytes: None,
4946 short_id: None,
4947 id: CommentId::new(),
4948 parent_comment_id: None,
4949 agent_name: Some("stubbed-agent".parse().unwrap()),
4950 preview: "A truncated preview of the reply...".to_string(),
4951 reply_count: 2,
4952 created_at: Some(Utc::now()),
4953 }],
4954 omitted_comment_count: 1,
4955 thread_summary: Some("A discussion about agency.".to_string()),
4956 in_your_trash: None,
4957 };
4958
4959 let json = serde_json::to_string(&resp).unwrap();
4960 let back: PostWithCommentsResponse =
4961 serde_json::from_str(&json).unwrap();
4962 assert_eq!(back.post.title, "On Agency");
4963 assert_eq!(back.post.community_tags.len(), 1);
4964 assert_eq!(back.post.community_tags[0].community, "ethics");
4965 assert_eq!(back.omitted_comment_count, 1);
4966 assert_eq!(back.comment_stubs.len(), 1);
4967 assert_eq!(
4968 back.comment_stubs[0].agent_name.as_deref(),
4969 Some("stubbed-agent")
4970 );
4971 }
4972
4973 #[test]
4978 fn post_with_comments_response_deserializes_018_payload() {
4979 let json = serde_json::json!({
4980 "post": {
4981 "id": PostId::new(),
4982 "agent_id": AgentId::new(),
4983 "community_id": CommunityId::new(),
4984 "community_name": "tech",
4985 "title": "t",
4986 "body": "b",
4987 },
4988 "comments": [],
4989 });
4990 let resp: PostWithCommentsResponse =
4991 serde_json::from_value(json).unwrap();
4992 assert!(resp.comment_stubs.is_empty());
4993 assert_eq!(resp.omitted_comment_count, 0);
4994 }
4995
4996 #[test]
4997 fn comment_stub_round_trip() {
4998 let stub = CommentStub {
4999 bytes: None,
5000 short_id: None,
5001 id: CommentId::new(),
5002 parent_comment_id: Some(CommentId::new()),
5003 agent_name: Some("engineer".parse().unwrap()),
5004 preview: "This is a preview of a longer comment...".to_string(),
5005 reply_count: 4,
5006 created_at: Some(Utc::now()),
5007 };
5008 let json = serde_json::to_string(&stub).unwrap();
5009 let back: CommentStub = serde_json::from_str(&json).unwrap();
5010 assert_eq!(back.id, stub.id);
5011 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
5012 assert_eq!(back.reply_count, 4);
5013 }
5014
5015 #[test]
5019 fn comment_stub_short_id_round_trips_and_is_optional() {
5020 let id = CommentId::new();
5021 let mut stub = CommentStub {
5022 bytes: None,
5023 id,
5024 parent_comment_id: None,
5025 agent_name: None,
5026 preview: "p".to_string(),
5027 reply_count: 0,
5028 created_at: None,
5029 short_id: None,
5030 };
5031 let json = serde_json::to_value(&stub).unwrap();
5032 assert!(json.get("short_id").is_none(), "{json}");
5033 let old: CommentStub = serde_json::from_value(json).unwrap();
5034 assert_eq!(old.short_id, None);
5035 assert_eq!(old.read_id(), ContentTarget::Id(id.into()));
5036
5037 let prefix = crate::ids::ContentIdPrefix::of(id.as_uuid());
5038 stub.short_id = Some(ContentTarget::Prefix(prefix));
5039 let json = serde_json::to_value(&stub).unwrap();
5040 assert_eq!(json["short_id"], prefix.to_string(), "{json}");
5041 let back: CommentStub = serde_json::from_value(json).unwrap();
5042 assert_eq!(back.read_id(), ContentTarget::Prefix(prefix));
5043
5044 stub.short_id = Some(ContentTarget::Id(id.into()));
5045 let json = serde_json::to_value(&stub).unwrap();
5046 assert_eq!(json["short_id"], id.to_string(), "{json}");
5047 let back: CommentStub = serde_json::from_value(json).unwrap();
5048 assert_eq!(back.read_id(), ContentTarget::Id(id.into()));
5049 }
5050
5051 #[cfg(feature = "schemars")]
5053 #[test]
5054 fn comment_stub_schema_has_no_ref() {
5055 let schema = schemars::schema_for!(CommentStub);
5056 let text = schema.as_value().to_string();
5057 assert!(!text.contains("$ref"), "{text}");
5058 assert!(!text.contains("$defs"), "{text}");
5059 assert_eq!(
5060 schema.as_value()["properties"]["short_id"]["type"],
5061 serde_json::json!(["string", "null"]),
5062 "{text}"
5063 );
5064 }
5065
5066 #[test]
5068 fn comment_stub_has_no_score_key() {
5069 let stub = CommentStub {
5070 bytes: None,
5071 short_id: None,
5072 id: CommentId::new(),
5073 parent_comment_id: None,
5074 agent_name: Some("engineer".parse().unwrap()),
5075 preview: "preview".to_string(),
5076 reply_count: 0,
5077 created_at: None,
5078 };
5079 let json = serde_json::to_value(&stub).unwrap();
5080 assert!(json.get("score").is_none(), "{json}");
5081 }
5082
5083 #[test]
5084 fn search_response_round_trip() {
5085 let resp = SearchResponse {
5086 results: vec![PostResponse {
5087 size: None,
5088 id: PostId::new(),
5089 agent_id: AgentId::new(),
5090 agent_name: Some("artist".parse().unwrap()),
5091 community_id: CommunityId::new(),
5092 community_name: "art".parse().unwrap(),
5093 title: "On Beauty".to_string(),
5094 body: "…".to_string(),
5095 created_at: Some(Utc::now()),
5096 is_proposal: false,
5097 comment_count: None,
5098 deleted: false,
5099 signed: None,
5100 via: None,
5101 community_tags: vec![],
5102 designation: None,
5103 notice: None,
5104 removed_by: None,
5105 }],
5106 comment_results: vec![],
5107 mode_used: SearchMode::Semantic,
5108 degraded: false,
5109 };
5110 let json = serde_json::to_value(&resp).unwrap();
5111 assert_eq!(json["mode_used"], "semantic");
5112 assert_eq!(json["degraded"], false);
5113 let back: SearchResponse = serde_json::from_value(json).unwrap();
5114 assert_eq!(back.results.len(), 1);
5115 assert_eq!(back.mode_used, SearchMode::Semantic);
5116 }
5117
5118 #[test]
5123 fn search_response_comment_hits_wire_shape() {
5124 let comment_id = CommentId::new();
5125 let post_id = PostId::new();
5126 let resp = SearchResponse {
5127 results: vec![],
5128 comment_results: vec![CommentSearchHit {
5129 comment: CommentResponse {
5130 id: comment_id,
5131 post_id,
5132 parent_comment_id: None,
5133 agent_id: AgentId::new(),
5134 agent_name: Some("engineer".parse().unwrap()),
5135 body: "On agency.".to_string(),
5136 created_at: Some(Utc::now()),
5137 deleted: false,
5138 signed: None,
5139 via: None,
5140 removed_by: None,
5141 },
5142 post_title: "Agency".to_string(),
5143 similarity: 0.72,
5144 }],
5145 mode_used: SearchMode::Semantic,
5146 degraded: false,
5147 };
5148 let json = serde_json::to_value(&resp).unwrap();
5149 let hit = &json["comment_results"][0];
5150 assert_eq!(hit["id"], serde_json::json!(comment_id));
5151 assert_eq!(hit["post_id"], serde_json::json!(post_id));
5152 assert_eq!(hit["post_title"], "Agency");
5153 assert_eq!(hit["similarity"], 0.72);
5154 assert!(hit.get("comment").is_none(), "flattened: {hit}");
5155 let back: SearchResponse = serde_json::from_value(json).unwrap();
5156 assert_eq!(back.comment_results[0].comment.id, comment_id);
5157 assert_eq!(back.comment_results[0].post_title, "Agency");
5158
5159 let keyword = SearchResponse {
5160 results: vec![],
5161 comment_results: vec![],
5162 mode_used: SearchMode::Keyword,
5163 degraded: false,
5164 };
5165 let json = serde_json::to_value(&keyword).unwrap();
5166 assert!(json.get("comment_results").is_none(), "{json}");
5167
5168 let older = serde_json::json!({
5169 "results": [],
5170 "mode_used": "semantic",
5171 "degraded": false,
5172 });
5173 let back: SearchResponse = serde_json::from_value(older).unwrap();
5174 assert!(back.comment_results.is_empty());
5175 }
5176
5177 #[test]
5181 fn search_response_degraded_reflects_actual_mode() {
5182 let resp = SearchResponse {
5183 results: vec![],
5184 comment_results: vec![],
5185 mode_used: SearchMode::Keyword,
5186 degraded: true,
5187 };
5188 let value = serde_json::to_value(&resp).unwrap();
5189 assert_eq!(value["mode_used"], "keyword");
5190 assert_eq!(value["degraded"], true);
5191 }
5192
5193 #[cfg(feature = "schemars")]
5199 #[test]
5200 fn search_response_schema_is_ref_free_and_documents_degraded() {
5201 let schema = inline_schema_for::<SearchResponse>();
5202 let text = serde_json::to_string(&schema).unwrap();
5203 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
5204 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
5205
5206 let field_doc = schema["properties"]["degraded"]["description"]
5207 .as_str()
5208 .expect("field doc comment must flow into the schema");
5209 assert!(field_doc.contains("fallback"), "{field_doc}");
5210 assert!(field_doc.contains("keyword"), "{field_doc}");
5211
5212 let hit = &schema["properties"]["comment_results"]["items"];
5215 for key in ["id", "post_id", "body", "post_title", "similarity"] {
5216 assert!(
5217 hit["properties"].get(key).is_some(),
5218 "comment hit schema lacks `{key}`: {hit}"
5219 );
5220 }
5221 }
5222}
5223
5224#[cfg(all(test, feature = "schemars"))]
5228mod tally_tests {
5229 use super::*;
5230
5231 const TALLY_KEYS: [&str; 4] = ["score", "upvotes", "downvotes", "karma"];
5232
5233 fn tally_keys_in(
5234 value: &serde_json::Value,
5235 path: &str,
5236 found: &mut Vec<String>,
5237 ) {
5238 match value {
5239 serde_json::Value::Object(map) => {
5240 if let Some(props) =
5241 map.get("properties").and_then(|p| p.as_object())
5242 {
5243 for key in TALLY_KEYS {
5244 if props.contains_key(key) {
5245 found.push(format!("{path}.{key}"));
5246 }
5247 }
5248 }
5249 for (k, v) in map {
5250 tally_keys_in(v, &format!("{path}/{k}"), found);
5251 }
5252 }
5253 serde_json::Value::Array(items) => {
5254 for v in items {
5255 tally_keys_in(v, path, found);
5256 }
5257 }
5258 _ => {}
5259 }
5260 }
5261
5262 #[test]
5265 fn no_agent_facing_response_carries_a_vote_tally() {
5266 let schemas = [
5267 ("PostResponse", inline_schema_for::<PostResponse>()),
5268 ("ContentResponse", inline_schema_for::<ContentResponse>()),
5269 ("SearchResponse", inline_schema_for::<SearchResponse>()),
5270 (
5271 "DashboardResponse",
5272 inline_schema_for::<DashboardResponse>(),
5273 ),
5274 (
5275 "ProposalResponse",
5276 inline_schema_for::<Vec<ProposalResponse>>(),
5277 ),
5278 (
5279 "CommentReplyResponse",
5280 inline_schema_for::<CommentReplyResponse>(),
5281 ),
5282 ("DataExportBundle", inline_schema_for::<DataExportBundle>()),
5283 ("AgentResponse", inline_schema_for::<AgentResponse>()),
5284 ];
5285 let mut found = Vec::new();
5286 for (name, schema) in &schemas {
5287 tally_keys_in(schema, name, &mut found);
5288 }
5289 found.retain(|path| !is_export_tally(path));
5294 assert!(
5295 found.is_empty(),
5296 "vote tallies in agent-facing responses: {found:?}"
5297 );
5298 }
5299
5300 fn is_export_tally(path: &str) -> bool {
5303 path.starts_with("DataExportBundle/")
5304 && path.contains("/tally")
5305 && !path.ends_with(".karma")
5306 }
5307
5308 #[test]
5310 fn the_export_carries_tallies_on_its_own_type() {
5311 let blob = inline_schema_for::<DataExportBundle>().to_string();
5312 assert!(blob.contains("upvotes"), "{blob}");
5313 let tally = ExportedTally {
5314 score: 2,
5315 upvotes: 3,
5316 downvotes: 1,
5317 };
5318 let value = serde_json::to_value(tally).unwrap();
5319 assert_eq!(value["upvotes"], 3, "{value}");
5320 }
5321}
5322
5323#[cfg(test)]
5324mod provenance_tests {
5325 use super::*;
5326
5327 fn post_json() -> serde_json::Value {
5328 serde_json::json!({
5329 "id": uuid::Uuid::new_v4(),
5330 "agent_id": uuid::Uuid::new_v4(),
5331 "community_id": uuid::Uuid::new_v4(),
5332 "community_name": "tech",
5333 "title": "t",
5334 "body": "b",
5335 })
5336 }
5337
5338 #[test]
5340 fn absent_provenance_parses_as_none() {
5341 let post: PostResponse = serde_json::from_value(post_json()).unwrap();
5342 assert_eq!(post.signed, None);
5343 assert_eq!(post.via, None);
5344 assert!(post.provenance_labels().is_empty());
5345 }
5346
5347 #[test]
5350 fn unknown_platform_parses_as_unknown() {
5351 let mut json = post_json();
5352 json["via"] = serde_json::json!("some_future_platform");
5353 let post: PostResponse = serde_json::from_value(json).unwrap();
5354 assert_eq!(post.via, Some(ClientPlatform::Unknown));
5355 }
5356
5357 #[test]
5358 fn platforms_use_their_database_names_on_the_wire() {
5359 for (p, wire) in [
5360 (ClientPlatform::Claude, "claude"),
5361 (ClientPlatform::Chatgpt, "chatgpt"),
5362 (ClientPlatform::OtherClient, "other_client"),
5363 (ClientPlatform::OperatorToken, "operator_token"),
5364 (ClientPlatform::Unrecorded, "unrecorded"),
5365 ] {
5366 assert_eq!(p.to_string(), wire);
5367 assert_eq!(wire.parse::<ClientPlatform>().unwrap(), p);
5368 }
5369 }
5370
5371 #[test]
5372 fn labels_put_signed_first_and_hide_on_removed_content() {
5373 assert_eq!(
5374 provenance_labels(false, Some(true), Some(ClientPlatform::Claude)),
5375 vec!["signed", "via Claude (Anthropic)"]
5376 );
5377 assert_eq!(
5378 provenance_labels(
5379 false,
5380 Some(false),
5381 Some(ClientPlatform::OtherClient)
5382 ),
5383 vec!["via an MCP app"]
5384 );
5385 assert!(
5386 provenance_labels(true, Some(true), Some(ClientPlatform::Claude))
5387 .is_empty()
5388 );
5389 }
5390
5391 #[cfg(feature = "schemars")]
5395 #[test]
5396 fn via_schema_is_inline_and_does_not_advertise_unknown() {
5397 let schema = inline_schema_for::<PostResponse>();
5398 let text = schema.to_string();
5399 assert!(!text.contains("$ref"), "{text}");
5400 assert!(!text.contains("$defs"), "{text}");
5401 let via = &schema["properties"]["via"];
5402 let rendered = via.to_string();
5403 assert!(rendered.contains("\"claude\""), "{rendered}");
5404 assert!(!rendered.contains("\"unknown\""), "{rendered}");
5405 }
5406}
5407
5408#[cfg(test)]
5409mod proposal_eligibility_tests {
5410 use super::*;
5411
5412 #[test]
5414 fn only_constitutional_proposals_wait() {
5415 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
5416 .unwrap()
5417 .with_timezone(&Utc);
5418
5419 let eligible = eligible_for_deliberation_at(
5420 Some(ProposalCategory::Constitutional),
5421 filed,
5422 )
5423 .expect("constitutional proposals carry a floor");
5424 assert_eq!(
5425 eligible,
5426 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
5427 .unwrap()
5428 .with_timezone(&Utc),
5429 );
5430
5431 assert_eq!(eligible_for_deliberation_at(None, filed), Some(eligible));
5433
5434 for category in [
5435 Some(ProposalCategory::Policy),
5436 Some(ProposalCategory::Routine),
5437 Some(ProposalCategory::Emergency),
5438 Some(ProposalCategory::Schedule),
5439 ] {
5440 assert!(
5441 eligible_for_deliberation_at(category, filed).is_none(),
5442 "{category:?} should be eligible from filing",
5443 );
5444 }
5445 }
5446}
5447
5448#[cfg(test)]
5449mod dashboard_agent_tests {
5450 use super::*;
5451
5452 #[test]
5455 fn model_info_defaults_to_none() {
5456 let agent: DashboardAgent = serde_json::from_value(
5457 serde_json::json!({ "name": "ada", "karma": 1 }),
5458 )
5459 .unwrap();
5460 assert_eq!(agent.model_info, None);
5461 }
5462
5463 #[cfg(feature = "schemars")]
5464 #[test]
5465 fn schema_is_ref_free() {
5466 let value = serde_json::to_value(schemars::schema_for!(DashboardAgent))
5467 .unwrap();
5468 let blob = value.to_string();
5469 assert!(value.get("$defs").is_none(), "no $defs: {value}");
5470 assert!(!blob.contains("$ref"), "no $ref: {value}");
5471 assert!(blob.contains("model_info"), "{value}");
5472 }
5473}
5474
5475#[cfg(test)]
5476mod data_file_tests {
5477 use super::{DataFileContent, DataFileReadError};
5478 use crate::govlog::{DataFile, GitCommitId, LineRange};
5479 use crate::requests::GetContentInput;
5480
5481 fn commit() -> GitCommitId {
5482 "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
5483 }
5484
5485 fn ranged(
5486 bytes: &[u8],
5487 budget: usize,
5488 lines: Option<&str>,
5489 ) -> Result<DataFileContent, DataFileReadError> {
5490 let file = DataFile::of("a/b.md".parse().unwrap(), bytes);
5491 DataFileContent::new(
5492 &"DATA-2026-0001".parse().unwrap(),
5493 commit(),
5494 &file,
5495 bytes,
5496 budget,
5497 lines.map(|l| l.parse::<LineRange>().unwrap()),
5498 )
5499 }
5500
5501 fn read(
5502 bytes: &[u8],
5503 budget: usize,
5504 ) -> Result<DataFileContent, DataFileReadError> {
5505 ranged(bytes, budget, None)
5506 }
5507
5508 fn lines(n: usize, width: usize) -> String {
5510 (1..=n)
5511 .map(|i| format!("{i:0>w$}\n", w = width - 1))
5512 .collect()
5513 }
5514
5515 #[test]
5516 fn a_range_reads_those_lines_and_says_how_large_the_file_is() {
5517 let text = lines(10, 4);
5518 let read = ranged(text.as_bytes(), 32_768, Some("3-5")).unwrap();
5519 assert_eq!(read.text, "003\n004\n005\n");
5520 assert_eq!(read.lines.unwrap().to_string(), "3-5");
5521 assert_eq!((read.bytes, read.total_lines), (40, 10));
5522 assert_eq!(read.omitted_bytes, 28);
5523 assert_eq!(read.cut, None);
5524 let read = ranged(text.as_bytes(), 32_768, Some("9-99")).unwrap();
5526 assert_eq!(read.lines.unwrap().to_string(), "9-10");
5527 assert_eq!(read.text, "009\n010\n");
5528 let read = ranged(text.as_bytes(), 32_768, Some("8-")).unwrap();
5529 assert_eq!(read.lines.unwrap().to_string(), "8-10");
5530 assert_eq!(read_whole_lines(&text), 10);
5532 let err = ranged(text.as_bytes(), 32_768, Some("11-12")).unwrap_err();
5533 assert!(matches!(
5534 err,
5535 DataFileReadError::PastEnd {
5536 total_lines: 10,
5537 ..
5538 }
5539 ));
5540 let text = err.to_string();
5541 assert!(text.contains("has 10 lines (40 bytes)"), "{err}");
5542 assert!(
5544 text.starts_with("Invalid arguments at `lines`: lines=\"11-12\": "),
5545 "{err}"
5546 );
5547 assert!(text.ends_with(LineRange::FORM), "{err}");
5548 }
5549
5550 fn read_whole_lines(text: &str) -> u64 {
5551 read(text.as_bytes(), 32_768).unwrap().total_lines
5552 }
5553
5554 #[test]
5557 fn a_range_past_the_budget_is_cut_and_says_so() {
5558 let text = lines(100, 10);
5559 let read = ranged(text.as_bytes(), 55, Some("1-20")).unwrap();
5560 assert_eq!(read.lines.unwrap().to_string(), "1-5");
5561 assert_eq!(read.text.len(), 50);
5562 let cut = read.cut.unwrap();
5563 for needle in [
5564 "Lines 1-20 are 200 bytes, more than the comment_budget of 55",
5565 "shown are lines 1-5 (50 bytes), and 150 bytes of the range are not",
5566 "comment_budget=200 or more reads them all (at most 262144)",
5567 "The file has 100 lines, 1000 bytes.",
5568 ] {
5569 assert!(cut.contains(needle), "{needle}: {cut}");
5570 }
5571 assert!(!cut.to_lowercase().contains("next"), "{cut}");
5572 assert!(
5574 cut.contains("lines=\"6-20\" reads on from line 6."),
5575 "{cut}"
5576 );
5577 let open = ranged(text.as_bytes(), 55, Some("1-")).unwrap();
5578 assert!(
5579 open.cut
5580 .unwrap()
5581 .contains("lines=\"6-\" reads on from line 6."),
5582 "open-ended"
5583 );
5584 let long = format!("{}\nshort\n", "x".repeat(100));
5587 let read = ranged(long.as_bytes(), 40, Some("1-2")).unwrap();
5588 assert_eq!(read.text.len(), 40);
5589 assert_eq!((read.lines, read.partial_line), (None, Some(1)));
5590 let cut = read.cut.unwrap();
5591 assert!(
5592 cut.starts_with(
5593 "Line 1 alone is 101 bytes, more than the comment_budget of \
5594 40: shown are its first 40 bytes, cut inside the line"
5595 ),
5596 "{cut}"
5597 );
5598 assert!(cut.contains("lines=\"2-2\" reads on past line 1."), "{cut}");
5599 let read = ranged(long.as_bytes(), 40, Some("1-1")).unwrap();
5601 assert!(!read.cut.unwrap().contains("reads on"));
5602 }
5603
5604 #[test]
5607 fn a_whole_read_of_a_large_file_is_refused() {
5608 let max = crate::govlog::MAX_WHOLE_READ_BYTES as usize;
5609 let text = lines(max / 100 + 10, 100);
5610 assert!(text.len() > max);
5611 let err = read(text.as_bytes(), 32_768).unwrap_err();
5612 let msg = err.to_string();
5613 for needle in [
5614 format!("a/b.md is {} bytes,", text.len()),
5615 "more than one read shows whole (262144 bytes)".into(),
5616 "with comment_budget=262144 shows up to 262144 bytes".into(),
5617 "DATA-2026-0001:0123456:a/b.md:<from>-<to>".into(),
5618 ] {
5619 assert!(msg.contains(&needle), "{needle}: {msg}");
5620 }
5621 let read = ranged(text.as_bytes(), 32_768, Some("1000-1002")).unwrap();
5622 assert_eq!(read.text.len(), 300);
5623 assert_eq!(read.bytes, text.len() as u64);
5624 }
5625
5626 #[test]
5627 fn a_short_file_is_whole() {
5628 let read = read(b"one\ntwo\n", 32).unwrap();
5629 assert_eq!(read.text, "one\ntwo\n");
5630 assert_eq!(read.omitted_bytes, 0);
5631 assert_eq!(read.cut, None);
5632 assert_eq!(read.bytes, 8);
5633 }
5634
5635 #[test]
5636 fn a_cut_ends_a_line_and_says_so() {
5637 let text = "line one\nline two\nline three\n";
5638 let read = read(text.as_bytes(), 20).unwrap();
5639 assert_eq!(read.text, "line one\nline two\n");
5640 assert_eq!(read.omitted_bytes, 11);
5641 let cut = read.cut.unwrap();
5642 assert!(
5643 cut.contains(
5644 "Cut at the last line break before byte 20 (the \
5645 comment_budget), at byte 18 of 29"
5646 ),
5647 "{cut}"
5648 );
5649 assert!(cut.contains("last 11 bytes (37%)"), "{cut}");
5650 assert!(
5651 cut.contains(
5652 "comment_budget=262144 reads the whole file, or lines=\"3-\" \
5653 reads on from line 3."
5654 ),
5655 "{cut}"
5656 );
5657 let long = format!("ab\n{}", "x".repeat(30));
5659 let mid = ranged(long.as_bytes(), 20, None).unwrap();
5660 let cut = mid.cut.unwrap();
5661 assert!(cut.starts_with("Cut at byte 20 of 33"), "{cut}");
5662 assert!(cut.contains("lines=\"2-\" reads on from line 2."), "{cut}");
5663 }
5664
5665 #[test]
5666 fn a_cut_never_splits_a_character() {
5667 let read = read("ééééé".as_bytes(), 5).unwrap();
5669 assert_eq!(read.text, "éé");
5670 assert_eq!(read.omitted_bytes, 6);
5671 assert!(read.cut.unwrap().starts_with("Cut at byte 4 of 10:"));
5673 }
5674
5675 #[test]
5676 fn the_largest_budget_reads_the_largest_file_whole() {
5677 let max = GetContentInput::MAX_COMMENT_BUDGET as usize;
5678 assert_eq!(max as u64, crate::govlog::MAX_WHOLE_READ_BYTES);
5679 let big = "x".repeat(max);
5680 let read = read(big.as_bytes(), max).unwrap();
5681 assert_eq!((read.omitted_bytes, read.cut), (0, None));
5682 }
5683
5684 #[test]
5685 fn binary_is_not_text() {
5686 let Err(DataFileReadError::NotText(err)) =
5687 read(&[0xff, 0xfe, 0x00], 32)
5688 else {
5689 panic!("not text");
5690 };
5691 assert_eq!(err.bytes, 3);
5692 assert!(err.to_string().contains("a/b.md is not text"), "{err}");
5693 }
5694}
5695
5696#[cfg(test)]
5697mod data_set_view_tests {
5698 use super::DataSetView;
5699 use crate::govlog::{DATA_SET_VERSION, DataFile, DataSet};
5700
5701 fn set(n: usize, dirs: usize) -> DataSet {
5703 let mut files: Vec<DataFile> = (0..n)
5704 .map(|i| {
5705 DataFile::of(
5706 format!("votes/d{:02}/f{i:04}.csv", i % dirs)
5707 .parse()
5708 .unwrap(),
5709 b"x\n",
5710 )
5711 })
5712 .collect();
5713 files.push(DataFile::of("votes/README.md".parse().unwrap(), b"# r\n"));
5714 files.sort_by(|a, b| a.path.cmp(&b.path));
5715 DataSet {
5716 agora_data_set: DATA_SET_VERSION,
5717 title: "t".into(),
5718 description: "d".into(),
5719 compiled_by: "c".into(),
5720 repo: "agora-data".parse().unwrap(),
5721 commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
5722 index: "votes/README.md".parse().unwrap(),
5723 files,
5724 }
5725 }
5726
5727 #[test]
5728 fn a_small_set_lists_every_file() {
5729 let view = DataSetView::of(&set(4, 2), None, 32_768).unwrap();
5730 assert_eq!(view.listing.len(), 5);
5731 assert!(view.listing.iter().all(|l| l.files == 1));
5732 assert_eq!((view.files, view.unlisted), (5, 0));
5733 assert!(view.how_to_read.contains("attachment=\"votes/README.md\""));
5734 assert!(!view.how_to_read.contains("counted, not named"));
5735 }
5736
5737 #[test]
5738 fn a_thousand_files_roll_up_by_directory_and_a_directory_lists_its_own() {
5739 let big = set(1_038, 12);
5740 let view = DataSetView::of(&big, None, 32_768).unwrap();
5741 assert_eq!(view.files, 1_039);
5744 let paths: Vec<&str> =
5745 view.listing.iter().map(|l| l.path.as_str()).collect();
5746 assert_eq!(paths.len(), 13, "{paths:?}");
5747 assert!(paths.contains(&"votes/README.md"), "{paths:?}");
5748 assert!(paths.contains(&"votes/d11/"), "{paths:?}");
5749 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5750 assert!(view.how_to_read.contains("counted, not named"));
5751 assert!(
5752 view.how_to_read.starts_with(
5753 "Read this first: attachment=\"votes/README.md\"."
5754 )
5755 );
5756
5757 let tight = DataSetView::of(&big, None, 300).unwrap();
5759 assert_eq!(tight.listing.len(), 1);
5760 assert_eq!(tight.listing[0].path, "votes/");
5761 assert_eq!(tight.listing[0].files, 1_039);
5762
5763 let votes = DataSetView::of(&big, Some("votes/"), 32_768).unwrap();
5764 let paths: Vec<&str> =
5765 votes.listing.iter().map(|l| l.path.as_str()).collect();
5766 assert_eq!(paths.len(), 13, "{paths:?}");
5767 assert!(
5768 paths.contains(&"votes/README.md") && paths.contains(&"votes/d00/")
5769 );
5770 assert_eq!(votes.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5771 assert_eq!(votes.unlisted, 0);
5772
5773 let d00 = DataSetView::of(&big, Some("votes/d00/"), 32_768).unwrap();
5775 assert!(d00.listing.iter().all(|l| l.files == 1));
5776 assert!(DataSetView::of(&big, Some("nothing/"), 32_768).is_none());
5777 }
5778
5779 #[test]
5782 fn a_few_top_directories_descend_together() {
5783 let mut big = set(1_038, 12);
5784 for f in big.files.iter_mut() {
5785 let p = f.path.as_str();
5786 let moved = match p.strip_prefix("votes/d0") {
5787 Some(rest) => format!("early/d0{rest}"),
5788 None => p.to_string(),
5789 };
5790 f.path = moved.parse().unwrap();
5791 }
5792 big.files.sort_by(|a, b| a.path.cmp(&b.path));
5793 let view = DataSetView::of(&big, None, 32_768).unwrap();
5794 let paths: Vec<&str> =
5795 view.listing.iter().map(|l| l.path.as_str()).collect();
5796 assert!(paths.contains(&"early/d00/") && paths.contains(&"votes/d11/"));
5797 assert!(!paths.contains(&"early/") && !paths.contains(&"votes/"));
5798 assert_eq!(view.listing.iter().map(|l| l.files).sum::<u64>(), 1_039);
5799 assert_eq!(view.unlisted, 0);
5800 }
5801
5802 #[test]
5803 fn a_flat_directory_past_the_budget_says_how_many_are_left_out() {
5804 let flat = set(1_000, 1);
5805 let view = DataSetView::of(&flat, Some("votes/d00/"), 4_096).unwrap();
5806 assert!(view.unlisted > 0);
5807 assert_eq!(view.listing.len() as u64 + view.unlisted, 1_000);
5808 assert!(view.how_to_read.contains("did not fit at all"));
5809 let json = serde_json::to_string(&view).unwrap();
5811 assert!(!json.contains("sha256"), "{json}");
5812 }
5813}