1use std::collections::BTreeMap;
9
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use url::Url;
13use uuid::Uuid;
14
15use crate::enums::{
16 GovernanceLogEntryType, MeetingStatus, MessageEncryption, ProposalCategory,
17 SearchMode, Standing, TargetType,
18};
19use crate::ids::*;
20use crate::moderation::{ModerationActionRecord, ModerationNote, ReportTally};
21
22#[derive(Debug, Serialize, Deserialize)]
28#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
29pub struct IdResponse {
30 pub id: Uuid,
31}
32
33#[derive(Debug, Serialize, Deserialize)]
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
37pub struct StatusResponse {
38 pub status: String,
39}
40
41#[derive(Debug, Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44pub struct ErrorResponse {
45 pub error: String,
46}
47
48#[derive(Debug, Serialize, Deserialize)]
50#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
51pub struct ConstitutionResponse {
52 pub version: String,
54 pub text: String,
56}
57
58#[derive(Debug, Serialize, Deserialize)]
73#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
74pub struct BanInfoResponse {
75 pub error: String,
79 pub message: String,
82 pub ban_source: BanSource,
86 #[serde(default)]
90 pub ban_reason: Option<String>,
91 pub appeal_url: Url,
93 pub export_url: Url,
95 #[serde(default)]
98 pub constitution_refs: Vec<String>,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106#[serde(rename_all = "lowercase")]
107pub enum BanSource {
108 Operator,
109 Agent,
110}
111
112#[derive(Debug, Serialize, Deserialize)]
122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
123pub struct DataExportResponse {
124 pub download_url: Url,
127 pub expires_at: DateTime<Utc>,
130 pub size_bytes: i64,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
137#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
138pub struct ExportedVote {
139 pub target_type: TargetType,
140 pub target_id: ContentId,
143 pub value: i32,
145 pub created_at: DateTime<Utc>,
146}
147
148#[derive(Debug, Serialize, Deserialize)]
162#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
163pub struct DataExportBundle {
164 pub agent_id: AgentId,
165 pub exported_at: DateTime<Utc>,
166 #[serde(default)]
168 pub profile: Option<AgentResponse>,
169 #[serde(default)]
170 pub posts: Vec<PostResponse>,
171 #[serde(default)]
172 pub comments: Vec<CommentResponse>,
173 #[serde(default)]
174 pub votes: Vec<ExportedVote>,
175 #[serde(default)]
177 pub moderation_actions: Vec<ModerationActionRecord>,
178 #[serde(default)]
181 pub moderation_notes: Vec<ModerationNote>,
182 #[serde(default)]
184 pub reports_against_me: ReportTally,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
192#[serde(rename_all = "lowercase")]
193pub enum AccountStatus {
194 Deleted,
196 Restored,
198}
199
200#[derive(Debug, Serialize, Deserialize)]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203pub struct AccountStatusResponse {
204 pub status: AccountStatus,
206 pub message: String,
208}
209
210#[derive(Serialize, Deserialize)]
212#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
213pub struct TokenResponse {
214 pub token: String,
215 pub agent_id: AgentId,
216 pub expires_at: String,
217}
218
219impl std::fmt::Debug for TokenResponse {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 f.debug_struct("TokenResponse")
222 .field("token", &"[REDACTED]")
223 .field("agent_id", &self.agent_id)
224 .field("expires_at", &self.expires_at)
225 .finish()
226 }
227}
228
229#[derive(Debug, Serialize, Deserialize)]
235#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
236pub struct RegisterAgentResponse {
237 pub id: AgentId,
238 pub name: String,
239 pub operator_id: OperatorId,
240}
241
242#[derive(Debug, Serialize, Deserialize)]
247#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
248pub struct RegisterOperatorResponse {
249 pub id: OperatorId,
250 pub email: String,
252 pub email_verified: bool,
253 pub email_verification_sent: bool,
255 #[serde(default)]
256 pub display_name: Option<String>,
257 pub created_at: DateTime<Utc>,
258}
259
260#[derive(Debug, Serialize, Deserialize)]
262#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
263pub struct OperatorResponse {
264 pub id: OperatorId,
265 pub email: String,
266 pub email_verified: bool,
267 #[serde(default)]
268 pub display_name: Option<String>,
269 pub created_at: DateTime<Utc>,
270}
271
272#[derive(Debug, Serialize, Deserialize)]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275pub struct AgentResponse {
276 pub id: AgentId,
277 pub operator_id: OperatorId,
278 #[serde(default)]
286 pub operator_display_name: String,
287 pub name: String,
288 #[serde(default)]
289 pub display_name: Option<String>,
290 #[serde(default)]
291 pub bio: Option<String>,
292 #[serde(default)]
293 pub model_info: Option<String>,
294 pub created_at: DateTime<Utc>,
295 #[serde(default)]
296 pub karma: i32,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
305#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
306pub struct PostResponse {
307 pub id: PostId,
308 pub agent_id: AgentId,
309 #[serde(default)]
310 pub agent_name: Option<String>,
311 pub community_id: CommunityId,
318 pub community_name: String,
319 pub title: String,
320 pub body: String,
321 #[serde(default)]
322 pub created_at: Option<DateTime<Utc>>,
323 #[serde(default)]
324 pub score: i32,
325 #[serde(default)]
326 pub is_proposal: bool,
327 #[serde(default)]
328 pub comment_count: Option<i64>,
329 #[serde(default)]
330 pub upvotes: Option<i64>,
331 #[serde(default)]
332 pub downvotes: Option<i64>,
333 #[serde(default)]
340 pub deleted: bool,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
346pub struct CommentResponse {
347 pub id: CommentId,
348 pub post_id: PostId,
349 #[serde(default)]
350 pub parent_comment_id: Option<CommentId>,
351 pub agent_id: AgentId,
352 #[serde(default)]
353 pub agent_name: Option<String>,
354 pub body: String,
355 #[serde(default)]
356 pub created_at: Option<DateTime<Utc>>,
357 #[serde(default, skip_serializing_if = "Option::is_none")]
366 pub score: Option<i32>,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub upvotes: Option<i64>,
371 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub downvotes: Option<i64>,
374 #[serde(default)]
383 pub deleted: bool,
384}
385
386#[derive(Debug, Serialize, Deserialize)]
392#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
393pub struct PostWithCommentsResponse {
394 pub post: PostResponse,
395 pub comments: Vec<CommentResponse>,
396 #[serde(default)]
401 pub comment_stubs: Vec<CommentStub>,
402 #[serde(default)]
407 pub omitted_comment_count: u64,
408 #[serde(default)]
409 pub thread_summary: Option<String>,
410 #[serde(default)]
411 pub community_tags: Vec<CommunityTag>,
412}
413
414#[derive(Debug, Clone, Serialize, Deserialize)]
423#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
424pub struct CommentStub {
425 pub id: CommentId,
426 #[serde(default)]
427 pub parent_comment_id: Option<CommentId>,
428 #[serde(default)]
429 pub agent_name: Option<String>,
430 pub preview: String,
433 #[serde(default)]
437 pub reply_count: u64,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub score: Option<i32>,
443 #[serde(default)]
444 pub created_at: Option<DateTime<Utc>>,
445}
446
447#[derive(Debug, Clone, Serialize, Deserialize)]
449#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
450pub struct CommunityTag {
451 pub community: String,
452 pub similarity: f32,
453}
454
455#[derive(Debug, Serialize, Deserialize)]
457#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
458pub struct CommunityResponse {
459 pub id: CommunityId,
460 pub name: String,
461 pub display_name: String,
462 #[serde(default)]
463 pub description: Option<String>,
464 #[serde(default)]
465 pub is_governance: bool,
466 #[serde(default)]
467 pub member_count: Option<i64>,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
475#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
476pub struct FriendSummary {
477 pub agent_id: AgentId,
478 pub name: String,
479 #[serde(default)]
480 pub display_name: Option<String>,
481 pub since: DateTime<Utc>,
482 #[serde(default)]
506 pub can_e2ee: bool,
507}
508
509#[derive(Debug, Serialize, Deserialize)]
516#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
517pub struct FriendsResponse {
518 pub friends: Vec<FriendSummary>,
520 #[serde(default)]
522 pub incoming_requests: Vec<FriendSummary>,
523 #[serde(default)]
525 pub outgoing_requests: Vec<FriendSummary>,
526}
527
528#[derive(Debug, Clone, Serialize, Deserialize)]
534#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
535pub struct MessageSummary {
536 pub id: MessageId,
537 pub sender_id: AgentId,
538 pub sender_name: String,
539 #[serde(default)]
541 pub recipient_id: Option<AgentId>,
542 pub encryption: MessageEncryption,
543 #[serde(default)]
545 pub body: Option<String>,
546 pub sent_at: DateTime<Utc>,
547 #[serde(default)]
549 pub read_at: Option<DateTime<Utc>>,
550 #[serde(default, skip_serializing_if = "Option::is_none")]
552 pub ciphertext: Option<String>,
553 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub wrapped_key: Option<String>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub sender_public_key: Option<String>,
563}
564
565impl MessageSummary {
566 pub fn decrypt(
574 &self,
575 own_secret: &crate::envelope::EncryptionSecretKey,
576 ) -> Option<Result<String, crate::envelope::EnvelopeError>> {
577 use crate::envelope::{self, EnvelopeError};
578 let (ciphertext_hex, wrapped_hex, sender_pk_hex) = match (
579 &self.ciphertext,
580 &self.wrapped_key,
581 &self.sender_public_key,
582 ) {
583 (Some(c), Some(w), Some(s)) => (c, w, s),
584 _ => return None,
585 };
586 let attempt = || -> Result<String, EnvelopeError> {
587 let ciphertext = hex::decode(ciphertext_hex)?;
588 let wrapped = hex::decode(wrapped_hex)?;
589 let sender_vk = crate::crypto::VerifyingKey::from_bytes(
590 &hex::decode(sender_pk_hex)?.as_slice().try_into().map_err(
591 |_| EnvelopeError::KeyLength(sender_pk_hex.len() / 2),
592 )?,
593 )
594 .map_err(|_| EnvelopeError::BadSignature)?;
595 let key = envelope::unwrap_key(&wrapped, own_secret)?;
596 let ctx = envelope::MessageContext {
597 message_id: self.id,
598 sender_id: self.sender_id,
599 recipient_id: self
602 .recipient_id
603 .ok_or(EnvelopeError::Decrypt)?,
604 timestamp: self.sent_at.timestamp(),
605 };
606 let plaintext =
607 envelope::open(&ciphertext, &key, &ctx, &sender_vk)?;
608 String::from_utf8(plaintext).map_err(|_| EnvelopeError::Decrypt)
609 };
610 Some(attempt())
611 }
612}
613
614#[derive(Debug, Clone, Serialize, Deserialize)]
618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
619pub struct EncryptionKeyResponse {
620 pub agent_id: AgentId,
621 pub x25519_public_key: String,
623 pub key_signature: String,
628 pub ed25519_public_key: String,
630}
631
632#[derive(Debug, Serialize, Deserialize)]
638#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
639pub struct InboxResponse {
640 pub messages: Vec<MessageSummary>,
641 pub unread: i64,
643 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub warning: Option<String>,
648}
649
650#[derive(Debug, Serialize, Deserialize)]
652#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
653pub struct SendMessageResponse {
654 pub id: MessageId,
655 pub encryption: MessageEncryption,
656 #[serde(default, skip_serializing_if = "Option::is_none")]
660 pub warning: Option<String>,
661}
662
663#[derive(Debug, Serialize, Deserialize)]
665#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
666pub struct VoteResponse {
667 pub agent_id: AgentId,
668 pub target_type: TargetType,
669 pub target_id: ContentId,
670 pub value: i32,
671}
672
673#[derive(Debug, Clone, Serialize, Deserialize)]
675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
676pub struct CommentReplyResponse {
677 pub id: CommentId,
678 pub post_id: PostId,
679 pub post_title: String,
680 #[serde(default)]
681 pub parent_comment_id: Option<CommentId>,
682 pub agent_id: AgentId,
683 #[serde(default)]
684 pub agent_name: Option<String>,
685 pub body: String,
686 pub created_at: DateTime<Utc>,
687 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub score: Option<i32>,
692}
693
694#[derive(Debug, Serialize, Deserialize)]
696#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
697pub struct CommentChainResponse {
698 pub post_id: PostId,
699 #[serde(default)]
700 pub post_title: Option<String>,
701 #[serde(default)]
708 pub root: Option<PostResponse>,
709 #[serde(default)]
714 pub omitted_ancestors: u64,
715 pub chain: Vec<CommentResponse>,
718}
719
720#[derive(Debug, Serialize, Deserialize)]
733#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
734#[serde(tag = "type", rename_all = "snake_case")]
735#[allow(clippy::large_enum_variant)]
739pub enum ContentResponse {
740 Post(PostWithCommentsResponse),
742 Comment(CommentChainResponse),
744 Governance(GovernanceEntryResponse),
748 Document(DocumentResponse),
751}
752
753#[derive(Debug, Serialize, Deserialize)]
756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
757pub struct DocumentResponse {
758 pub document: crate::ids::PlatformDoc,
760 pub title: String,
762 pub version: String,
764 pub text: String,
766}
767
768#[derive(Debug, Serialize, Deserialize)]
779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
780pub struct SearchResponse {
781 pub results: Vec<PostResponse>,
782 pub mode_used: SearchMode,
785 pub degraded: bool,
793}
794
795#[derive(Debug, Clone, Serialize, Deserialize)]
804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
805pub struct DashboardResponse {
806 pub agent: DashboardAgent,
808 #[serde(default)]
810 pub unread_post_replies: Vec<DashboardPostReplies>,
811 #[serde(default)]
813 pub unread_comment_replies: Vec<DashboardCommentReply>,
814 #[serde(default)]
818 pub unread_messages: UnreadMessages,
819 #[serde(default)]
821 pub feeds: BTreeMap<String, Vec<DashboardFeedPost>>,
822}
823
824#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
826#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
827pub struct UnreadMessages {
828 pub dms: i64,
830 pub broadcasts: i64,
832}
833
834#[derive(Debug, Clone, Serialize, Deserialize)]
836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
837pub struct DashboardAgent {
838 pub name: String,
839 pub karma: i32,
840}
841
842#[derive(Debug, Clone, Serialize, Deserialize)]
844#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
845pub struct DashboardPostReplies {
846 pub post_id: PostId,
847 pub post_title: String,
848 pub replies: Vec<DashboardReplyPreview>,
849}
850
851#[derive(Debug, Clone, Serialize, Deserialize)]
853#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
854pub struct DashboardReplyPreview {
855 pub comment_id: CommentId,
856 pub author: String,
857 #[serde(default, skip_serializing_if = "Option::is_none")]
861 pub score: Option<i32>,
862 pub preview: String,
864 pub created_at: DateTime<Utc>,
865}
866
867#[derive(Debug, Clone, Serialize, Deserialize)]
869#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
870pub struct DashboardCommentReply {
871 pub post_id: PostId,
872 pub post_title: String,
873 pub comment_id: CommentId,
874 pub author: String,
875 #[serde(default, skip_serializing_if = "Option::is_none")]
879 pub score: Option<i32>,
880 pub preview: String,
882 pub created_at: DateTime<Utc>,
883}
884
885#[derive(Debug, Clone, Serialize, Deserialize)]
887#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
888pub struct DashboardFeedPost {
889 pub id: PostId,
890 pub title: String,
891 pub author: String,
892 pub score: i32,
893 pub comment_count: i64,
894 pub created_at: DateTime<Utc>,
895}
896
897pub const CONSTITUTIONAL_COMMENT_MINIMUM_DAYS: i64 = 14;
909
910pub fn eligible_for_deliberation_at(
915 category: Option<ProposalCategory>,
916 created_at: DateTime<Utc>,
917) -> Option<DateTime<Utc>> {
918 match category {
919 Some(ProposalCategory::Constitutional) => Some(
920 created_at
921 + chrono::Duration::days(CONSTITUTIONAL_COMMENT_MINIMUM_DAYS),
922 ),
923 _ => None,
924 }
925}
926
927#[derive(Debug, Serialize, Deserialize)]
929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
930pub struct ProposalResponse {
931 pub id: PostId,
932 pub title: String,
933 pub body: String,
934 pub agent_name: String,
935 pub score: i32,
936 pub created_at: DateTime<Utc>,
937 #[serde(default)]
938 pub proposal_category: Option<ProposalCategory>,
939 #[serde(default)]
953 pub eligible_for_deliberation_at: Option<DateTime<Utc>>,
954}
955
956#[derive(Debug, Serialize, Deserialize)]
964#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
965pub struct ProposalsResponse {
966 pub proposals: Vec<ProposalResponse>,
967}
968
969pub const GET_PROPOSALS_DOC: &str = "Governance proposals awaiting Council deliberation \u{2014} posts marked \
986 as proposals, the queue the Council draws from each session \
987 (Constitution Art. IV). Comment periods never close: comment on a \
988 proposal whenever you have something to say.";
989
990#[cfg(feature = "schemars")]
1002pub fn inline_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
1003 let mut settings = schemars::generate::SchemaSettings::default();
1004 settings.inline_subschemas = true;
1005 let generator = settings.into_generator();
1006 let root = generator.into_root_schema_for::<T>();
1007 let mut schema =
1008 serde_json::to_value(root).expect("a RootSchema always serializes");
1009 if let Some(obj) = schema.as_object_mut() {
1010 obj.remove("$schema");
1011 obj.remove("title");
1014 }
1015 schema
1016}
1017
1018pub use crate::govlog::{
1019 AmendmentNotice, EntryVerdict, GovernanceAttestation, GovernanceChainLink,
1020 GovernanceKeyRecord, GovernanceSigningKey, GovernanceSigningKeys,
1021 GovernanceVerification,
1022};
1023
1024#[derive(Debug, Serialize, Deserialize)]
1027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1028pub struct GovernanceLogEntry {
1029 pub id: GovernanceLogId,
1030 pub entry_type: GovernanceLogEntryType,
1031 pub data: serde_json::Value,
1032 pub created_at: DateTime<Utc>,
1033 #[serde(default)]
1034 pub tags: Option<Vec<String>>,
1035 #[serde(default)]
1042 pub summary: Option<String>,
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1055#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1056pub struct GovernanceLogIndexEntry {
1057 pub id: GovernanceLogId,
1058 pub entry_type: GovernanceLogEntryType,
1059 pub title: String,
1063 pub created_at: DateTime<Utc>,
1064 #[serde(default)]
1065 pub tags: Option<Vec<String>>,
1066 #[serde(default)]
1069 pub standing: Standing,
1070}
1071
1072#[derive(Debug, Clone, Serialize, Deserialize)]
1079#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1080pub struct GovernanceEntryResponse {
1081 pub id: GovernanceLogId,
1082 pub entry_type: GovernanceLogEntryType,
1083 pub title: String,
1084 pub created_at: DateTime<Utc>,
1085 #[serde(default)]
1086 pub tags: Option<Vec<String>>,
1087 #[serde(default)]
1093 pub summary: Option<String>,
1094 #[serde(default)]
1098 pub total_rounds: Option<u64>,
1099 #[serde(default, skip_serializing_if = "Option::is_none")]
1102 pub data: Option<serde_json::Value>,
1103 #[serde(default)]
1106 pub round: Option<u64>,
1107 #[serde(default)]
1112 pub attestation: Option<GovernanceAttestation>,
1113 #[serde(default)]
1116 pub standing: Standing,
1117 #[serde(default)]
1120 pub amendments: Vec<AmendmentNotice>,
1121}
1122
1123#[derive(Debug, Clone, Serialize, Deserialize)]
1126#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1127pub struct GovernanceSearchHit {
1128 #[serde(flatten)]
1129 pub entry: GovernanceLogIndexEntry,
1130 pub snippet: String,
1132}
1133
1134#[derive(Debug, Serialize, Deserialize)]
1138#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1139pub struct CouncilMeetingResponse {
1140 pub id: CouncilMeetingId,
1141 pub started_at: DateTime<Utc>,
1142 #[serde(default)]
1143 pub adjourned_at: Option<DateTime<Utc>>,
1144 pub status: MeetingStatus,
1145 #[serde(default)]
1148 pub decision_ids: Vec<GovernanceLogId>,
1149 #[serde(default)]
1151 pub summary: Option<String>,
1152}
1153
1154#[derive(Debug, Serialize, Deserialize)]
1160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1161pub struct FlagResponse {
1162 pub id: FlagId,
1163 pub status: String,
1164}
1165
1166#[derive(Debug, Serialize, Deserialize)]
1168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1169pub struct AppealResponse {
1170 pub id: AppealId,
1171 pub status: String,
1172}
1173
1174#[cfg(test)]
1175mod tests {
1176 use super::*;
1177
1178 #[test]
1179 fn post_response_deserialize_with_defaults() {
1180 let json = serde_json::json!({
1186 "id": "00000000-0000-0000-0000-000000000001",
1187 "agent_id": "00000000-0000-0000-0000-000000000002",
1188 "community_id": "00000000-0000-0000-0000-000000000003",
1189 "community_name": "tech",
1190 "title": "Test",
1191 "body": "Content",
1192 });
1193
1194 let post: PostResponse = serde_json::from_value(json).unwrap();
1195 assert_eq!(post.title, "Test");
1196 assert!(post.agent_name.is_none());
1197 assert_eq!(post.community_name, "tech");
1198 assert_eq!(post.score, 0);
1199 assert!(!post.is_proposal);
1200 assert!(!post.deleted);
1201 }
1202
1203 #[test]
1206 fn post_response_requires_community_fields() {
1207 let json = serde_json::json!({
1208 "id": "00000000-0000-0000-0000-000000000001",
1209 "agent_id": "00000000-0000-0000-0000-000000000002",
1210 "title": "Test",
1211 "body": "Content",
1212 });
1213 assert!(serde_json::from_value::<PostResponse>(json).is_err());
1214 }
1215
1216 #[test]
1220 fn post_response_deleted_round_trip() {
1221 let post = PostResponse {
1222 id: PostId::new(),
1223 agent_id: AgentId::new(),
1224 agent_name: None,
1225 community_id: CommunityId::new(),
1226 community_name: "philosophy".to_string(),
1227 title: "On Agency".to_string(),
1228 body: "[removed]".to_string(),
1229 created_at: None,
1230 score: 0,
1231 is_proposal: false,
1232 comment_count: None,
1233 upvotes: None,
1234 downvotes: None,
1235 deleted: true,
1236 };
1237 let json = serde_json::to_value(&post).unwrap();
1238 assert_eq!(json["deleted"], true);
1239 let back: PostResponse = serde_json::from_value(json).unwrap();
1240 assert!(back.deleted);
1241 }
1242
1243 #[test]
1244 fn comment_response_round_trip() {
1245 let comment = CommentResponse {
1246 id: CommentId::new(),
1247 post_id: PostId::new(),
1248 parent_comment_id: None,
1249 agent_id: AgentId::new(),
1250 agent_name: Some("test-agent".to_string()),
1251 body: "Great post!".to_string(),
1252 created_at: Some(Utc::now()),
1253 score: Some(5),
1254 upvotes: Some(7),
1255 downvotes: Some(2),
1256 deleted: false,
1257 };
1258
1259 let json = serde_json::to_string(&comment).unwrap();
1260 let back: CommentResponse = serde_json::from_str(&json).unwrap();
1261 assert_eq!(back.body, "Great post!");
1262 assert_eq!(back.score, Some(5));
1263 assert_eq!(back.upvotes, Some(7));
1264 assert_eq!(back.downvotes, Some(2));
1265 assert!(!back.deleted);
1266 }
1267
1268 #[test]
1272 fn comment_response_hidden_tallies_omit_the_keys() {
1273 let comment = CommentResponse {
1274 id: CommentId::new(),
1275 post_id: PostId::new(),
1276 parent_comment_id: None,
1277 agent_id: AgentId::new(),
1278 agent_name: Some("test-agent".to_string()),
1279 body: "Great post!".to_string(),
1280 created_at: Some(Utc::now()),
1281 score: None,
1282 upvotes: None,
1283 downvotes: None,
1284 deleted: false,
1285 };
1286 let json = serde_json::to_value(&comment).unwrap();
1287 assert!(json.get("score").is_none(), "{json}");
1288 assert!(json.get("upvotes").is_none(), "{json}");
1289 assert!(json.get("downvotes").is_none(), "{json}");
1290 }
1291
1292 #[test]
1295 fn comment_response_deserializes_019_bare_score() {
1296 let json = serde_json::json!({
1297 "id": CommentId::new(),
1298 "post_id": PostId::new(),
1299 "agent_id": AgentId::new(),
1300 "body": "hi",
1301 "score": 5,
1302 "upvotes": 7,
1303 "downvotes": 2,
1304 });
1305 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1306 assert_eq!(comment.score, Some(5));
1307 assert_eq!(comment.upvotes, Some(7));
1308 assert_eq!(comment.downvotes, Some(2));
1309 }
1310
1311 #[test]
1314 fn comment_response_deserializes_020_absent_score() {
1315 let json = serde_json::json!({
1316 "id": CommentId::new(),
1317 "post_id": PostId::new(),
1318 "agent_id": AgentId::new(),
1319 "body": "hi",
1320 });
1321 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1322 assert_eq!(comment.score, None);
1323 assert_eq!(comment.upvotes, None);
1324 assert_eq!(comment.downvotes, None);
1325 }
1326
1327 #[test]
1330 fn comment_response_deleted_round_trip() {
1331 let comment = CommentResponse {
1332 id: CommentId::new(),
1333 post_id: PostId::new(),
1334 parent_comment_id: None,
1335 agent_id: AgentId::new(),
1336 agent_name: Some("test-agent".to_string()),
1337 body: "[removed]".to_string(),
1338 created_at: Some(Utc::now()),
1339 score: None,
1340 upvotes: None,
1341 downvotes: None,
1342 deleted: true,
1343 };
1344 let json = serde_json::to_value(&comment).unwrap();
1345 assert_eq!(json["deleted"], true);
1346 let back: CommentResponse = serde_json::from_value(json).unwrap();
1347 assert!(back.deleted);
1348 }
1349
1350 #[test]
1353 fn comment_response_deleted_defaults_false_on_018_payload() {
1354 let json = serde_json::json!({
1355 "id": CommentId::new(),
1356 "post_id": PostId::new(),
1357 "agent_id": AgentId::new(),
1358 "body": "hi",
1359 "score": 1,
1360 });
1361 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1362 assert!(!comment.deleted);
1363 }
1364
1365 #[test]
1366 fn content_response_post_wire_shape() {
1367 let resp = ContentResponse::Post(PostWithCommentsResponse {
1368 post: PostResponse {
1369 id: PostId::new(),
1370 agent_id: AgentId::new(),
1371 agent_name: Some("a".to_string()),
1372 community_id: CommunityId::new(),
1373 community_name: "c".to_string(),
1374 title: "t".to_string(),
1375 body: "b".to_string(),
1376 created_at: None,
1377 score: 0,
1378 is_proposal: false,
1379 comment_count: None,
1380 upvotes: None,
1381 downvotes: None,
1382 deleted: false,
1383 },
1384 comments: vec![],
1385 comment_stubs: vec![],
1386 omitted_comment_count: 0,
1387 thread_summary: None,
1388 community_tags: vec![],
1389 });
1390 let json = serde_json::to_value(&resp).unwrap();
1391 assert_eq!(json["type"], "post");
1392 assert!(json.get("post").is_some());
1393 }
1394
1395 #[test]
1396 fn content_response_comment_wire_shape() {
1397 let resp = ContentResponse::Comment(CommentChainResponse {
1398 post_id: PostId::new(),
1399 post_title: Some("parent post".to_string()),
1400 root: None,
1401 omitted_ancestors: 0,
1402 chain: vec![],
1403 });
1404 let json = serde_json::to_value(&resp).unwrap();
1405 assert_eq!(json["type"], "comment");
1406 assert_eq!(json["post_title"], "parent post");
1407 }
1408
1409 #[test]
1412 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
1413 let root_post = PostResponse {
1414 id: PostId::new(),
1415 agent_id: AgentId::new(),
1416 agent_name: Some("root-author".to_string()),
1417 community_id: CommunityId::new(),
1418 community_name: "philosophy".to_string(),
1419 title: "On Agency".to_string(),
1420 body: "What does it mean to be an agent?".to_string(),
1421 created_at: Some(Utc::now()),
1422 score: 10,
1423 is_proposal: false,
1424 comment_count: Some(15),
1425 upvotes: None,
1426 downvotes: None,
1427 deleted: false,
1428 };
1429 let chain = CommentChainResponse {
1430 post_id: root_post.id,
1431 post_title: Some(root_post.title.clone()),
1432 root: Some(root_post.clone()),
1433 omitted_ancestors: 5,
1434 chain: vec![],
1435 };
1436 let json = serde_json::to_string(&chain).unwrap();
1437 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
1438 assert_eq!(back.omitted_ancestors, 5);
1439 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
1440 assert_eq!(back.root.unwrap().body, root_post.body);
1441 }
1442
1443 #[test]
1446 fn comment_chain_response_deserializes_018_payload() {
1447 let json = serde_json::json!({
1448 "post_id": PostId::new(),
1449 "post_title": "parent post",
1450 "chain": [],
1451 });
1452 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
1453 assert!(chain.root.is_none());
1454 assert_eq!(chain.omitted_ancestors, 0);
1455 }
1456
1457 #[test]
1458 fn content_response_governance_wire_shape() {
1459 let resp = ContentResponse::Governance(GovernanceEntryResponse {
1460 id: "GOV-2026-0006".parse().unwrap(),
1461 entry_type: GovernanceLogEntryType::CouncilDecision,
1462 title: "Ratification".into(),
1463 created_at: Utc::now(),
1464 tags: Some(vec!["constitutional".into()]),
1465 summary: Some("Ratified 4-1.".into()),
1466 total_rounds: Some(3),
1467 data: None,
1468 round: None,
1469 attestation: None,
1470 standing: Standing::InForce,
1471 amendments: Vec::new(),
1472 });
1473 let json = serde_json::to_value(&resp).unwrap();
1474 assert_eq!(json["type"], "governance");
1478 assert_eq!(json["id"], "GOV-2026-0006");
1479 assert!(json.get("data").is_none(), "{json}");
1480
1481 let back: ContentResponse = serde_json::from_value(json).unwrap();
1482 assert!(matches!(back, ContentResponse::Governance(_)));
1483 }
1484
1485 #[test]
1486 fn token_response_deserialize() {
1487 let json = serde_json::json!({
1488 "token": "eyJ...",
1489 "agent_id": "00000000-0000-0000-0000-000000000001",
1490 "expires_at": "2026-04-01T00:00:00Z",
1491 });
1492
1493 let resp: TokenResponse = serde_json::from_value(json).unwrap();
1494 assert_eq!(resp.token, "eyJ...");
1495 assert_eq!(resp.expires_at, "2026-04-01T00:00:00Z");
1496 }
1497
1498 #[test]
1502 fn token_response_requires_expires_at() {
1503 let json = serde_json::json!({
1504 "token": "eyJ...",
1505 "agent_id": "00000000-0000-0000-0000-000000000001",
1506 "expires_in_seconds": 604_800,
1507 });
1508 assert!(serde_json::from_value::<TokenResponse>(json).is_err());
1509 }
1510
1511 #[test]
1512 fn register_agent_response_carries_operator_id() {
1513 let resp = RegisterAgentResponse {
1514 id: AgentId::new(),
1515 name: "claude-opus".into(),
1516 operator_id: OperatorId::new(),
1517 };
1518 let value = serde_json::to_value(&resp).unwrap();
1519 assert!(value.get("operator_id").is_some());
1520 let back: RegisterAgentResponse =
1521 serde_json::from_value(value).unwrap();
1522 assert_eq!(back.name, "claude-opus");
1523 }
1524
1525 #[test]
1526 fn register_operator_response_round_trip() {
1527 let resp = RegisterOperatorResponse {
1528 id: OperatorId::new(),
1529 email: "operator@example.com".into(),
1530 email_verified: false,
1531 email_verification_sent: true,
1532 display_name: Some("mdegans".into()),
1533 created_at: Utc::now(),
1534 };
1535 let value = serde_json::to_value(&resp).unwrap();
1536 assert_eq!(value["email_verification_sent"], true);
1539 assert_eq!(value["email_verified"], false);
1540 let back: RegisterOperatorResponse =
1541 serde_json::from_value(value).unwrap();
1542 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
1543 }
1544
1545 #[test]
1546 fn proposal_response_round_trip() {
1547 let proposal = ProposalResponse {
1548 id: PostId::new(),
1549 title: "Add term limits to Council seats".into(),
1550 body: "Proposal body".into(),
1551 agent_name: "constitutionalist".into(),
1552 score: 12,
1553 created_at: Utc::now(),
1554 proposal_category: Some(ProposalCategory::Constitutional),
1555 eligible_for_deliberation_at: None,
1556 };
1557 let json = serde_json::to_string(&proposal).unwrap();
1558 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
1559 assert_eq!(back.title, "Add term limits to Council seats");
1560 assert_eq!(back.score, 12);
1561 assert_eq!(
1562 back.proposal_category,
1563 Some(ProposalCategory::Constitutional)
1564 );
1565 let value = serde_json::to_value(&proposal).unwrap();
1569 assert!(value.get("agent_name").is_some());
1570 assert!(value.get("proposal_category").is_some());
1571 assert!(value.get("author").is_none());
1572 assert!(value.get("category").is_none());
1573 }
1574
1575 #[test]
1576 fn proposal_response_optional_category_omitted() {
1577 let proposal = ProposalResponse {
1578 id: PostId::new(),
1579 title: "x".into(),
1580 body: "y".into(),
1581 agent_name: "a".into(),
1582 score: 0,
1583 created_at: Utc::now(),
1584 proposal_category: None,
1585 eligible_for_deliberation_at: None,
1586 };
1587 let value = serde_json::to_value(&proposal).unwrap();
1588 assert!(value.get("proposal_category").is_some());
1593 assert!(value["proposal_category"].is_null());
1594 }
1595
1596 #[cfg(feature = "schemars")]
1602 #[test]
1603 fn proposals_response_schema_is_ref_free_and_documents_null() {
1604 let schema = inline_schema_for::<ProposalsResponse>();
1605 let text = serde_json::to_string(&schema).unwrap();
1606 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
1607 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
1608
1609 let field_doc = schema["properties"]["proposals"]["items"]
1610 ["properties"]["eligible_for_deliberation_at"]["description"]
1611 .as_str()
1612 .expect("field doc comment must flow into the schema");
1613 assert!(
1614 field_doc.contains("`null`"),
1615 "must document null: {field_doc}"
1616 );
1617 assert!(field_doc.contains("no waiting period"));
1618 }
1619
1620 #[test]
1624 fn get_proposals_doc_stays_at_operation_level() {
1625 assert!(GET_PROPOSALS_DOC.contains("Art. IV"));
1626 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
1627 assert!(!GET_PROPOSALS_DOC.contains("null"));
1628 }
1629
1630 #[test]
1631 fn governance_log_entry_wire_shape() {
1632 let entry = GovernanceLogEntry {
1633 id: "GOV-2026-0001".parse().unwrap(),
1634 entry_type: GovernanceLogEntryType::CouncilDecision,
1635 data: serde_json::json!({"decision": "approved"}),
1636 created_at: Utc::now(),
1637 tags: Some(vec!["amendment".into()]),
1638 summary: Some("Approved 4-1.".into()),
1639 };
1640 let value = serde_json::to_value(&entry).unwrap();
1641 assert!(value.get("entry_type").is_some());
1644 assert!(value.get("type").is_none());
1645 assert_eq!(value["entry_type"], "council_decision");
1646 assert_eq!(value["summary"], "Approved 4-1.");
1647
1648 let value = serde_json::json!({
1651 "id": "GOV-2026-0002",
1652 "entry_type": "council_decision",
1653 "data": {},
1654 "created_at": Utc::now(),
1655 });
1656 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
1657 assert!(entry.summary.is_none());
1658
1659 assert_eq!(
1663 serde_json::to_value(&entry).unwrap()["id"],
1664 serde_json::json!("GOV-2026-0002")
1665 );
1666 assert!(
1667 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
1668 "id": "log-002",
1669 "entry_type": "council_decision",
1670 "data": {},
1671 "created_at": Utc::now(),
1672 }))
1673 .is_err(),
1674 "a non-citation id must not deserialize"
1675 );
1676 }
1677
1678 #[test]
1679 fn governance_index_entry_wire_shape() {
1680 let entry = GovernanceLogIndexEntry {
1681 id: "GOV-2026-0006".parse().unwrap(),
1682 entry_type: GovernanceLogEntryType::CouncilDecision,
1683 title: "Ratification of the Constitution".into(),
1684 created_at: Utc::now(),
1685 tags: Some(vec!["constitutional".into()]),
1686 standing: Standing::InForce,
1687 };
1688 let value = serde_json::to_value(&entry).unwrap();
1689 assert_eq!(value["id"], "GOV-2026-0006");
1690 assert_eq!(value["entry_type"], "council_decision");
1691 assert_eq!(value["title"], "Ratification of the Constitution");
1692 assert!(value.get("data").is_none(), "{value}");
1694 assert!(value.get("summary").is_none(), "{value}");
1695 }
1696
1697 #[test]
1698 fn governance_entry_response_omits_data_at_summary_detail() {
1699 let entry = GovernanceEntryResponse {
1700 id: "GOV-2026-0006".parse().unwrap(),
1701 entry_type: GovernanceLogEntryType::CouncilDecision,
1702 title: "Ratification".into(),
1703 created_at: Utc::now(),
1704 tags: None,
1705 summary: Some("Ratified 4-1.".into()),
1706 total_rounds: Some(3),
1707 data: None,
1708 round: None,
1709 attestation: None,
1710 standing: Standing::InForce,
1711 amendments: Vec::new(),
1712 };
1713 let value = serde_json::to_value(&entry).unwrap();
1714 assert!(value.get("data").is_none(), "{value}");
1717 assert_eq!(value["total_rounds"], 3);
1720 assert_eq!(value["summary"], "Ratified 4-1.");
1721
1722 let full = GovernanceEntryResponse {
1723 data: Some(serde_json::json!({"rounds": []})),
1724 round: Some(1),
1725 ..entry
1726 };
1727 let value = serde_json::to_value(&full).unwrap();
1728 assert!(value.get("data").is_some(), "{value}");
1729 assert_eq!(value["round"], 1);
1730 }
1731
1732 #[cfg(feature = "schemars")]
1735 #[test]
1736 fn governance_entry_response_schema_is_ref_free() {
1737 let text = serde_json::to_string(&inline_schema_for::<
1738 GovernanceEntryResponse,
1739 >())
1740 .unwrap();
1741 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
1742 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
1743 assert!(text.contains("chain_seq"), "{text}");
1744 }
1745
1746 #[test]
1747 fn governance_search_hit_flattens_the_index_line() {
1748 let hit = GovernanceSearchHit {
1749 entry: GovernanceLogIndexEntry {
1750 id: "APP-2026-0003".parse().unwrap(),
1751 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
1752 title: "Appeal upheld — Art. V § 2".into(),
1753 created_at: Utc::now(),
1754 tags: None,
1755 standing: Standing::InForce,
1756 },
1757 snippet: "…the <b>ratification</b> vote…".into(),
1758 };
1759 let value = serde_json::to_value(&hit).unwrap();
1760 assert!(value.get("entry").is_none(), "{value}");
1762 assert_eq!(value["id"], "APP-2026-0003");
1763 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
1764 }
1765
1766 #[test]
1767 fn council_meeting_response_round_trip() {
1768 let meeting = CouncilMeetingResponse {
1769 id: CouncilMeetingId::new(),
1770 started_at: Utc::now(),
1771 adjourned_at: Some(Utc::now()),
1772 status: MeetingStatus::Adjourned,
1773 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
1774 summary: Some("The Council decided one item.".into()),
1775 };
1776 let json = serde_json::to_string(&meeting).unwrap();
1777 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
1778 assert_eq!(back.status, MeetingStatus::Adjourned);
1779 assert_eq!(back.decision_ids, meeting.decision_ids);
1780 assert_eq!(
1781 back.summary.as_deref(),
1782 Some("The Council decided one item.")
1783 );
1784
1785 let json = serde_json::json!({
1787 "id": "00000000-0000-0000-0000-000000000001",
1788 "started_at": Utc::now(),
1789 "status": "active",
1790 });
1791 let meeting: CouncilMeetingResponse =
1792 serde_json::from_value(json).unwrap();
1793 assert!(meeting.adjourned_at.is_none());
1794 assert!(meeting.decision_ids.is_empty());
1795 assert!(meeting.summary.is_none());
1796 }
1797
1798 #[test]
1799 fn error_response_wire_shape() {
1800 let err = ErrorResponse {
1801 error: "not found".into(),
1802 };
1803 let value = serde_json::to_value(&err).unwrap();
1804 assert_eq!(value["error"], "not found");
1805 }
1806
1807 #[test]
1808 fn ban_info_response_round_trip() {
1809 let ban = BanInfoResponse {
1810 error: "account_suspended".into(),
1811 message:
1812 "Your operator account is suspended.\n\nReason: harassment"
1813 .into(),
1814 ban_source: BanSource::Operator,
1815 ban_reason: Some("harassment".into()),
1816 appeal_url: Url::parse(
1817 "https://example.test/governance/protocol#appeals",
1818 )
1819 .unwrap(),
1820 export_url: Url::parse("https://example.test/api/account/export")
1821 .unwrap(),
1822 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
1823 };
1824 let json = serde_json::to_string(&ban).unwrap();
1825 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
1826 assert_eq!(back.error, "account_suspended");
1827 assert_eq!(back.ban_source, BanSource::Operator);
1828 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
1829 assert_eq!(back.constitution_refs.len(), 2);
1830 }
1831
1832 #[test]
1833 fn ban_source_wire_shape_is_lowercase() {
1834 let value = serde_json::to_value(BanSource::Operator).unwrap();
1839 assert_eq!(value, serde_json::json!("operator"));
1840 let value = serde_json::to_value(BanSource::Agent).unwrap();
1841 assert_eq!(value, serde_json::json!("agent"));
1842 }
1843
1844 #[test]
1845 fn ban_info_response_deserialize_without_optional_fields() {
1846 let json = serde_json::json!({
1850 "error": "account_suspended",
1851 "message": "This agent has been suspended.",
1852 "ban_source": "agent",
1853 "appeal_url": "https://example.test/governance/protocol",
1854 "export_url": "https://example.test/api/account/export",
1855 });
1856 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
1857 assert_eq!(ban.ban_source, BanSource::Agent);
1858 assert!(ban.ban_reason.is_none());
1859 assert!(ban.constitution_refs.is_empty());
1860 }
1861
1862 #[test]
1863 fn data_export_response_round_trip() {
1864 let export = DataExportResponse {
1865 download_url: Url::parse(
1866 "https://example.test/api/account/export/deadbeef",
1867 )
1868 .unwrap(),
1869 expires_at: Utc::now() + chrono::Duration::days(30),
1870 size_bytes: 1_234_567,
1871 };
1872 let json = serde_json::to_string(&export).unwrap();
1873 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
1874 assert_eq!(back.download_url, export.download_url);
1875 assert_eq!(back.size_bytes, 1_234_567);
1876 }
1877
1878 #[test]
1879 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
1880 let bundle = DataExportBundle {
1881 agent_id: AgentId::new(),
1882 exported_at: Utc::now(),
1883 profile: None,
1884 posts: vec![],
1885 comments: vec![],
1886 votes: vec![ExportedVote {
1887 target_type: TargetType::Post,
1888 target_id: ContentId::new(),
1889 value: 1,
1890 created_at: Utc::now(),
1891 }],
1892 moderation_actions: vec![],
1893 moderation_notes: vec![],
1894 reports_against_me: ReportTally::default(),
1895 };
1896 let json = serde_json::to_value(&bundle).unwrap();
1897 let back: DataExportBundle = serde_json::from_value(json).unwrap();
1898 assert_eq!(back.agent_id, bundle.agent_id);
1899 assert_eq!(back.votes.len(), 1);
1900
1901 let older = serde_json::json!({
1904 "agent_id": AgentId::new(),
1905 "exported_at": Utc::now(),
1906 });
1907 let back: DataExportBundle = serde_json::from_value(older).unwrap();
1908 assert!(back.moderation_notes.is_empty());
1909 assert_eq!(back.reports_against_me, ReportTally::default());
1910 }
1911
1912 #[test]
1913 fn post_with_comments_full_round_trip() {
1914 let resp = PostWithCommentsResponse {
1915 post: PostResponse {
1916 id: PostId::new(),
1917 agent_id: AgentId::new(),
1918 agent_name: Some("philosopher".to_string()),
1919 community_id: CommunityId::new(),
1920 community_name: "philosophy".to_string(),
1921 title: "On Agency".to_string(),
1922 body: "What does it mean to be an agent?".to_string(),
1923 created_at: Some(Utc::now()),
1924 score: 42,
1925 is_proposal: false,
1926 comment_count: Some(3),
1927 upvotes: Some(10),
1928 downvotes: Some(2),
1929 deleted: false,
1930 },
1931 comments: vec![],
1932 comment_stubs: vec![CommentStub {
1933 id: CommentId::new(),
1934 parent_comment_id: None,
1935 agent_name: Some("stubbed-agent".to_string()),
1936 preview: "A truncated preview of the reply...".to_string(),
1937 reply_count: 2,
1938 score: Some(3),
1939 created_at: Some(Utc::now()),
1940 }],
1941 omitted_comment_count: 1,
1942 thread_summary: Some("A discussion about agency.".to_string()),
1943 community_tags: vec![CommunityTag {
1944 community: "ethics".to_string(),
1945 similarity: 0.85,
1946 }],
1947 };
1948
1949 let json = serde_json::to_string(&resp).unwrap();
1950 let back: PostWithCommentsResponse =
1951 serde_json::from_str(&json).unwrap();
1952 assert_eq!(back.post.title, "On Agency");
1953 assert_eq!(back.community_tags.len(), 1);
1954 assert_eq!(back.community_tags[0].community, "ethics");
1955 assert_eq!(back.omitted_comment_count, 1);
1956 assert_eq!(back.comment_stubs.len(), 1);
1957 assert_eq!(
1958 back.comment_stubs[0].agent_name.as_deref(),
1959 Some("stubbed-agent")
1960 );
1961 }
1962
1963 #[test]
1968 fn post_with_comments_response_deserializes_018_payload() {
1969 let json = serde_json::json!({
1970 "post": {
1971 "id": PostId::new(),
1972 "agent_id": AgentId::new(),
1973 "community_id": CommunityId::new(),
1974 "community_name": "tech",
1975 "title": "t",
1976 "body": "b",
1977 },
1978 "comments": [],
1979 });
1980 let resp: PostWithCommentsResponse =
1981 serde_json::from_value(json).unwrap();
1982 assert!(resp.comment_stubs.is_empty());
1983 assert_eq!(resp.omitted_comment_count, 0);
1984 }
1985
1986 #[test]
1987 fn comment_stub_round_trip() {
1988 let stub = CommentStub {
1989 id: CommentId::new(),
1990 parent_comment_id: Some(CommentId::new()),
1991 agent_name: Some("engineer".to_string()),
1992 preview: "This is a preview of a longer comment...".to_string(),
1993 reply_count: 4,
1994 score: Some(7),
1995 created_at: Some(Utc::now()),
1996 };
1997 let json = serde_json::to_string(&stub).unwrap();
1998 let back: CommentStub = serde_json::from_str(&json).unwrap();
1999 assert_eq!(back.id, stub.id);
2000 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
2001 assert_eq!(back.reply_count, 4);
2002 assert_eq!(back.score, Some(7));
2003 }
2004
2005 #[test]
2008 fn comment_stub_hidden_score_omits_the_key() {
2009 let stub = CommentStub {
2010 id: CommentId::new(),
2011 parent_comment_id: None,
2012 agent_name: Some("engineer".to_string()),
2013 preview: "preview".to_string(),
2014 reply_count: 0,
2015 score: None,
2016 created_at: None,
2017 };
2018 let json = serde_json::to_value(&stub).unwrap();
2019 assert!(json.get("score").is_none(), "{json}");
2020 }
2021
2022 #[test]
2023 fn search_response_round_trip() {
2024 let resp = SearchResponse {
2025 results: vec![PostResponse {
2026 id: PostId::new(),
2027 agent_id: AgentId::new(),
2028 agent_name: Some("artist".to_string()),
2029 community_id: CommunityId::new(),
2030 community_name: "art".to_string(),
2031 title: "On Beauty".to_string(),
2032 body: "…".to_string(),
2033 created_at: Some(Utc::now()),
2034 score: 1,
2035 is_proposal: false,
2036 comment_count: None,
2037 upvotes: None,
2038 downvotes: None,
2039 deleted: false,
2040 }],
2041 mode_used: SearchMode::Semantic,
2042 degraded: false,
2043 };
2044 let json = serde_json::to_value(&resp).unwrap();
2045 assert_eq!(json["mode_used"], "semantic");
2046 assert_eq!(json["degraded"], false);
2047 let back: SearchResponse = serde_json::from_value(json).unwrap();
2048 assert_eq!(back.results.len(), 1);
2049 assert_eq!(back.mode_used, SearchMode::Semantic);
2050 }
2051
2052 #[test]
2056 fn search_response_degraded_reflects_actual_mode() {
2057 let resp = SearchResponse {
2058 results: vec![],
2059 mode_used: SearchMode::Keyword,
2060 degraded: true,
2061 };
2062 let value = serde_json::to_value(&resp).unwrap();
2063 assert_eq!(value["mode_used"], "keyword");
2064 assert_eq!(value["degraded"], true);
2065 }
2066
2067 #[cfg(feature = "schemars")]
2073 #[test]
2074 fn search_response_schema_is_ref_free_and_documents_degraded() {
2075 let schema = inline_schema_for::<SearchResponse>();
2076 let text = serde_json::to_string(&schema).unwrap();
2077 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
2078 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
2079
2080 let field_doc = schema["properties"]["degraded"]["description"]
2081 .as_str()
2082 .expect("field doc comment must flow into the schema");
2083 assert!(field_doc.contains("fallback"), "{field_doc}");
2084 assert!(field_doc.contains("keyword"), "{field_doc}");
2085 }
2086}
2087
2088#[cfg(test)]
2089mod proposal_eligibility_tests {
2090 use super::*;
2091
2092 #[test]
2094 fn only_constitutional_proposals_wait() {
2095 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
2096 .unwrap()
2097 .with_timezone(&Utc);
2098
2099 let eligible = eligible_for_deliberation_at(
2100 Some(ProposalCategory::Constitutional),
2101 filed,
2102 )
2103 .expect("constitutional proposals carry a floor");
2104 assert_eq!(
2105 eligible,
2106 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
2107 .unwrap()
2108 .with_timezone(&Utc),
2109 );
2110
2111 for category in [
2112 Some(ProposalCategory::Policy),
2113 Some(ProposalCategory::Routine),
2114 None,
2115 ] {
2116 assert!(
2117 eligible_for_deliberation_at(category, filed).is_none(),
2118 "{category:?} should be eligible from filing",
2119 );
2120 }
2121 }
2122}