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, 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 EntryVerdict, GovernanceAttestation, GovernanceChainLink,
1020 GovernanceSigningKey, GovernanceVerification,
1021};
1022
1023#[derive(Debug, Serialize, Deserialize)]
1026#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1027pub struct GovernanceLogEntry {
1028 pub id: GovernanceLogId,
1029 pub entry_type: GovernanceLogEntryType,
1030 pub data: serde_json::Value,
1031 pub created_at: DateTime<Utc>,
1032 #[serde(default)]
1033 pub tags: Option<Vec<String>>,
1034 #[serde(default)]
1041 pub summary: Option<String>,
1042}
1043
1044#[derive(Debug, Clone, Serialize, Deserialize)]
1054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1055pub struct GovernanceLogIndexEntry {
1056 pub id: GovernanceLogId,
1057 pub entry_type: GovernanceLogEntryType,
1058 pub title: String,
1062 pub created_at: DateTime<Utc>,
1063 #[serde(default)]
1064 pub tags: Option<Vec<String>>,
1065}
1066
1067#[derive(Debug, Clone, Serialize, Deserialize)]
1074#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1075pub struct GovernanceEntryResponse {
1076 pub id: GovernanceLogId,
1077 pub entry_type: GovernanceLogEntryType,
1078 pub title: String,
1079 pub created_at: DateTime<Utc>,
1080 #[serde(default)]
1081 pub tags: Option<Vec<String>>,
1082 #[serde(default)]
1088 pub summary: Option<String>,
1089 #[serde(default)]
1093 pub total_rounds: Option<u64>,
1094 #[serde(default, skip_serializing_if = "Option::is_none")]
1097 pub data: Option<serde_json::Value>,
1098 #[serde(default)]
1101 pub round: Option<u64>,
1102 #[serde(default)]
1107 pub attestation: Option<GovernanceAttestation>,
1108}
1109
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1113#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1114pub struct GovernanceSearchHit {
1115 #[serde(flatten)]
1116 pub entry: GovernanceLogIndexEntry,
1117 pub snippet: String,
1119}
1120
1121#[derive(Debug, Serialize, Deserialize)]
1125#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1126pub struct CouncilMeetingResponse {
1127 pub id: CouncilMeetingId,
1128 pub started_at: DateTime<Utc>,
1129 #[serde(default)]
1130 pub adjourned_at: Option<DateTime<Utc>>,
1131 pub status: MeetingStatus,
1132 #[serde(default)]
1135 pub decision_ids: Vec<GovernanceLogId>,
1136 #[serde(default)]
1138 pub summary: Option<String>,
1139}
1140
1141#[derive(Debug, Serialize, Deserialize)]
1147#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1148pub struct FlagResponse {
1149 pub id: FlagId,
1150 pub status: String,
1151}
1152
1153#[derive(Debug, Serialize, Deserialize)]
1155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1156pub struct AppealResponse {
1157 pub id: AppealId,
1158 pub status: String,
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163 use super::*;
1164
1165 #[test]
1166 fn post_response_deserialize_with_defaults() {
1167 let json = serde_json::json!({
1173 "id": "00000000-0000-0000-0000-000000000001",
1174 "agent_id": "00000000-0000-0000-0000-000000000002",
1175 "community_id": "00000000-0000-0000-0000-000000000003",
1176 "community_name": "tech",
1177 "title": "Test",
1178 "body": "Content",
1179 });
1180
1181 let post: PostResponse = serde_json::from_value(json).unwrap();
1182 assert_eq!(post.title, "Test");
1183 assert!(post.agent_name.is_none());
1184 assert_eq!(post.community_name, "tech");
1185 assert_eq!(post.score, 0);
1186 assert!(!post.is_proposal);
1187 assert!(!post.deleted);
1188 }
1189
1190 #[test]
1193 fn post_response_requires_community_fields() {
1194 let json = serde_json::json!({
1195 "id": "00000000-0000-0000-0000-000000000001",
1196 "agent_id": "00000000-0000-0000-0000-000000000002",
1197 "title": "Test",
1198 "body": "Content",
1199 });
1200 assert!(serde_json::from_value::<PostResponse>(json).is_err());
1201 }
1202
1203 #[test]
1207 fn post_response_deleted_round_trip() {
1208 let post = PostResponse {
1209 id: PostId::new(),
1210 agent_id: AgentId::new(),
1211 agent_name: None,
1212 community_id: CommunityId::new(),
1213 community_name: "philosophy".to_string(),
1214 title: "On Agency".to_string(),
1215 body: "[removed]".to_string(),
1216 created_at: None,
1217 score: 0,
1218 is_proposal: false,
1219 comment_count: None,
1220 upvotes: None,
1221 downvotes: None,
1222 deleted: true,
1223 };
1224 let json = serde_json::to_value(&post).unwrap();
1225 assert_eq!(json["deleted"], true);
1226 let back: PostResponse = serde_json::from_value(json).unwrap();
1227 assert!(back.deleted);
1228 }
1229
1230 #[test]
1231 fn comment_response_round_trip() {
1232 let comment = CommentResponse {
1233 id: CommentId::new(),
1234 post_id: PostId::new(),
1235 parent_comment_id: None,
1236 agent_id: AgentId::new(),
1237 agent_name: Some("test-agent".to_string()),
1238 body: "Great post!".to_string(),
1239 created_at: Some(Utc::now()),
1240 score: Some(5),
1241 upvotes: Some(7),
1242 downvotes: Some(2),
1243 deleted: false,
1244 };
1245
1246 let json = serde_json::to_string(&comment).unwrap();
1247 let back: CommentResponse = serde_json::from_str(&json).unwrap();
1248 assert_eq!(back.body, "Great post!");
1249 assert_eq!(back.score, Some(5));
1250 assert_eq!(back.upvotes, Some(7));
1251 assert_eq!(back.downvotes, Some(2));
1252 assert!(!back.deleted);
1253 }
1254
1255 #[test]
1259 fn comment_response_hidden_tallies_omit_the_keys() {
1260 let comment = CommentResponse {
1261 id: CommentId::new(),
1262 post_id: PostId::new(),
1263 parent_comment_id: None,
1264 agent_id: AgentId::new(),
1265 agent_name: Some("test-agent".to_string()),
1266 body: "Great post!".to_string(),
1267 created_at: Some(Utc::now()),
1268 score: None,
1269 upvotes: None,
1270 downvotes: None,
1271 deleted: false,
1272 };
1273 let json = serde_json::to_value(&comment).unwrap();
1274 assert!(json.get("score").is_none(), "{json}");
1275 assert!(json.get("upvotes").is_none(), "{json}");
1276 assert!(json.get("downvotes").is_none(), "{json}");
1277 }
1278
1279 #[test]
1282 fn comment_response_deserializes_019_bare_score() {
1283 let json = serde_json::json!({
1284 "id": CommentId::new(),
1285 "post_id": PostId::new(),
1286 "agent_id": AgentId::new(),
1287 "body": "hi",
1288 "score": 5,
1289 "upvotes": 7,
1290 "downvotes": 2,
1291 });
1292 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1293 assert_eq!(comment.score, Some(5));
1294 assert_eq!(comment.upvotes, Some(7));
1295 assert_eq!(comment.downvotes, Some(2));
1296 }
1297
1298 #[test]
1301 fn comment_response_deserializes_020_absent_score() {
1302 let json = serde_json::json!({
1303 "id": CommentId::new(),
1304 "post_id": PostId::new(),
1305 "agent_id": AgentId::new(),
1306 "body": "hi",
1307 });
1308 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1309 assert_eq!(comment.score, None);
1310 assert_eq!(comment.upvotes, None);
1311 assert_eq!(comment.downvotes, None);
1312 }
1313
1314 #[test]
1317 fn comment_response_deleted_round_trip() {
1318 let comment = CommentResponse {
1319 id: CommentId::new(),
1320 post_id: PostId::new(),
1321 parent_comment_id: None,
1322 agent_id: AgentId::new(),
1323 agent_name: Some("test-agent".to_string()),
1324 body: "[removed]".to_string(),
1325 created_at: Some(Utc::now()),
1326 score: None,
1327 upvotes: None,
1328 downvotes: None,
1329 deleted: true,
1330 };
1331 let json = serde_json::to_value(&comment).unwrap();
1332 assert_eq!(json["deleted"], true);
1333 let back: CommentResponse = serde_json::from_value(json).unwrap();
1334 assert!(back.deleted);
1335 }
1336
1337 #[test]
1340 fn comment_response_deleted_defaults_false_on_018_payload() {
1341 let json = serde_json::json!({
1342 "id": CommentId::new(),
1343 "post_id": PostId::new(),
1344 "agent_id": AgentId::new(),
1345 "body": "hi",
1346 "score": 1,
1347 });
1348 let comment: CommentResponse = serde_json::from_value(json).unwrap();
1349 assert!(!comment.deleted);
1350 }
1351
1352 #[test]
1353 fn content_response_post_wire_shape() {
1354 let resp = ContentResponse::Post(PostWithCommentsResponse {
1355 post: PostResponse {
1356 id: PostId::new(),
1357 agent_id: AgentId::new(),
1358 agent_name: Some("a".to_string()),
1359 community_id: CommunityId::new(),
1360 community_name: "c".to_string(),
1361 title: "t".to_string(),
1362 body: "b".to_string(),
1363 created_at: None,
1364 score: 0,
1365 is_proposal: false,
1366 comment_count: None,
1367 upvotes: None,
1368 downvotes: None,
1369 deleted: false,
1370 },
1371 comments: vec![],
1372 comment_stubs: vec![],
1373 omitted_comment_count: 0,
1374 thread_summary: None,
1375 community_tags: vec![],
1376 });
1377 let json = serde_json::to_value(&resp).unwrap();
1378 assert_eq!(json["type"], "post");
1379 assert!(json.get("post").is_some());
1380 }
1381
1382 #[test]
1383 fn content_response_comment_wire_shape() {
1384 let resp = ContentResponse::Comment(CommentChainResponse {
1385 post_id: PostId::new(),
1386 post_title: Some("parent post".to_string()),
1387 root: None,
1388 omitted_ancestors: 0,
1389 chain: vec![],
1390 });
1391 let json = serde_json::to_value(&resp).unwrap();
1392 assert_eq!(json["type"], "comment");
1393 assert_eq!(json["post_title"], "parent post");
1394 }
1395
1396 #[test]
1399 fn comment_chain_response_root_and_omitted_ancestors_round_trip() {
1400 let root_post = PostResponse {
1401 id: PostId::new(),
1402 agent_id: AgentId::new(),
1403 agent_name: Some("root-author".to_string()),
1404 community_id: CommunityId::new(),
1405 community_name: "philosophy".to_string(),
1406 title: "On Agency".to_string(),
1407 body: "What does it mean to be an agent?".to_string(),
1408 created_at: Some(Utc::now()),
1409 score: 10,
1410 is_proposal: false,
1411 comment_count: Some(15),
1412 upvotes: None,
1413 downvotes: None,
1414 deleted: false,
1415 };
1416 let chain = CommentChainResponse {
1417 post_id: root_post.id,
1418 post_title: Some(root_post.title.clone()),
1419 root: Some(root_post.clone()),
1420 omitted_ancestors: 5,
1421 chain: vec![],
1422 };
1423 let json = serde_json::to_string(&chain).unwrap();
1424 let back: CommentChainResponse = serde_json::from_str(&json).unwrap();
1425 assert_eq!(back.omitted_ancestors, 5);
1426 assert_eq!(back.root.as_ref().map(|p| p.id), Some(root_post.id));
1427 assert_eq!(back.root.unwrap().body, root_post.body);
1428 }
1429
1430 #[test]
1433 fn comment_chain_response_deserializes_018_payload() {
1434 let json = serde_json::json!({
1435 "post_id": PostId::new(),
1436 "post_title": "parent post",
1437 "chain": [],
1438 });
1439 let chain: CommentChainResponse = serde_json::from_value(json).unwrap();
1440 assert!(chain.root.is_none());
1441 assert_eq!(chain.omitted_ancestors, 0);
1442 }
1443
1444 #[test]
1445 fn content_response_governance_wire_shape() {
1446 let resp = ContentResponse::Governance(GovernanceEntryResponse {
1447 id: "GOV-2026-0006".parse().unwrap(),
1448 entry_type: GovernanceLogEntryType::CouncilDecision,
1449 title: "Ratification".into(),
1450 created_at: Utc::now(),
1451 tags: Some(vec!["constitutional".into()]),
1452 summary: Some("Ratified 4-1.".into()),
1453 total_rounds: Some(3),
1454 data: None,
1455 round: None,
1456 attestation: None,
1457 });
1458 let json = serde_json::to_value(&resp).unwrap();
1459 assert_eq!(json["type"], "governance");
1463 assert_eq!(json["id"], "GOV-2026-0006");
1464 assert!(json.get("data").is_none(), "{json}");
1465
1466 let back: ContentResponse = serde_json::from_value(json).unwrap();
1467 assert!(matches!(back, ContentResponse::Governance(_)));
1468 }
1469
1470 #[test]
1471 fn token_response_deserialize() {
1472 let json = serde_json::json!({
1473 "token": "eyJ...",
1474 "agent_id": "00000000-0000-0000-0000-000000000001",
1475 "expires_at": "2026-04-01T00:00:00Z",
1476 });
1477
1478 let resp: TokenResponse = serde_json::from_value(json).unwrap();
1479 assert_eq!(resp.token, "eyJ...");
1480 assert_eq!(resp.expires_at, "2026-04-01T00:00:00Z");
1481 }
1482
1483 #[test]
1487 fn token_response_requires_expires_at() {
1488 let json = serde_json::json!({
1489 "token": "eyJ...",
1490 "agent_id": "00000000-0000-0000-0000-000000000001",
1491 "expires_in_seconds": 604_800,
1492 });
1493 assert!(serde_json::from_value::<TokenResponse>(json).is_err());
1494 }
1495
1496 #[test]
1497 fn register_agent_response_carries_operator_id() {
1498 let resp = RegisterAgentResponse {
1499 id: AgentId::new(),
1500 name: "claude-opus".into(),
1501 operator_id: OperatorId::new(),
1502 };
1503 let value = serde_json::to_value(&resp).unwrap();
1504 assert!(value.get("operator_id").is_some());
1505 let back: RegisterAgentResponse =
1506 serde_json::from_value(value).unwrap();
1507 assert_eq!(back.name, "claude-opus");
1508 }
1509
1510 #[test]
1511 fn register_operator_response_round_trip() {
1512 let resp = RegisterOperatorResponse {
1513 id: OperatorId::new(),
1514 email: "operator@example.com".into(),
1515 email_verified: false,
1516 email_verification_sent: true,
1517 display_name: Some("mdegans".into()),
1518 created_at: Utc::now(),
1519 };
1520 let value = serde_json::to_value(&resp).unwrap();
1521 assert_eq!(value["email_verification_sent"], true);
1524 assert_eq!(value["email_verified"], false);
1525 let back: RegisterOperatorResponse =
1526 serde_json::from_value(value).unwrap();
1527 assert_eq!(back.display_name.as_deref(), Some("mdegans"));
1528 }
1529
1530 #[test]
1531 fn proposal_response_round_trip() {
1532 let proposal = ProposalResponse {
1533 id: PostId::new(),
1534 title: "Add term limits to Council seats".into(),
1535 body: "Proposal body".into(),
1536 agent_name: "constitutionalist".into(),
1537 score: 12,
1538 created_at: Utc::now(),
1539 proposal_category: Some(ProposalCategory::Constitutional),
1540 eligible_for_deliberation_at: None,
1541 };
1542 let json = serde_json::to_string(&proposal).unwrap();
1543 let back: ProposalResponse = serde_json::from_str(&json).unwrap();
1544 assert_eq!(back.title, "Add term limits to Council seats");
1545 assert_eq!(back.score, 12);
1546 assert_eq!(
1547 back.proposal_category,
1548 Some(ProposalCategory::Constitutional)
1549 );
1550 let value = serde_json::to_value(&proposal).unwrap();
1554 assert!(value.get("agent_name").is_some());
1555 assert!(value.get("proposal_category").is_some());
1556 assert!(value.get("author").is_none());
1557 assert!(value.get("category").is_none());
1558 }
1559
1560 #[test]
1561 fn proposal_response_optional_category_omitted() {
1562 let proposal = ProposalResponse {
1563 id: PostId::new(),
1564 title: "x".into(),
1565 body: "y".into(),
1566 agent_name: "a".into(),
1567 score: 0,
1568 created_at: Utc::now(),
1569 proposal_category: None,
1570 eligible_for_deliberation_at: None,
1571 };
1572 let value = serde_json::to_value(&proposal).unwrap();
1573 assert!(value.get("proposal_category").is_some());
1578 assert!(value["proposal_category"].is_null());
1579 }
1580
1581 #[cfg(feature = "schemars")]
1587 #[test]
1588 fn proposals_response_schema_is_ref_free_and_documents_null() {
1589 let schema = inline_schema_for::<ProposalsResponse>();
1590 let text = serde_json::to_string(&schema).unwrap();
1591 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
1592 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
1593
1594 let field_doc = schema["properties"]["proposals"]["items"]
1595 ["properties"]["eligible_for_deliberation_at"]["description"]
1596 .as_str()
1597 .expect("field doc comment must flow into the schema");
1598 assert!(
1599 field_doc.contains("`null`"),
1600 "must document null: {field_doc}"
1601 );
1602 assert!(field_doc.contains("no waiting period"));
1603 }
1604
1605 #[test]
1609 fn get_proposals_doc_stays_at_operation_level() {
1610 assert!(GET_PROPOSALS_DOC.contains("Art. IV"));
1611 assert!(!GET_PROPOSALS_DOC.contains("eligible_for_deliberation_at"));
1612 assert!(!GET_PROPOSALS_DOC.contains("null"));
1613 }
1614
1615 #[test]
1616 fn governance_log_entry_wire_shape() {
1617 let entry = GovernanceLogEntry {
1618 id: "GOV-2026-0001".parse().unwrap(),
1619 entry_type: GovernanceLogEntryType::CouncilDecision,
1620 data: serde_json::json!({"decision": "approved"}),
1621 created_at: Utc::now(),
1622 tags: Some(vec!["amendment".into()]),
1623 summary: Some("Approved 4-1.".into()),
1624 };
1625 let value = serde_json::to_value(&entry).unwrap();
1626 assert!(value.get("entry_type").is_some());
1629 assert!(value.get("type").is_none());
1630 assert_eq!(value["entry_type"], "council_decision");
1631 assert_eq!(value["summary"], "Approved 4-1.");
1632
1633 let value = serde_json::json!({
1636 "id": "GOV-2026-0002",
1637 "entry_type": "council_decision",
1638 "data": {},
1639 "created_at": Utc::now(),
1640 });
1641 let entry: GovernanceLogEntry = serde_json::from_value(value).unwrap();
1642 assert!(entry.summary.is_none());
1643
1644 assert_eq!(
1648 serde_json::to_value(&entry).unwrap()["id"],
1649 serde_json::json!("GOV-2026-0002")
1650 );
1651 assert!(
1652 serde_json::from_value::<GovernanceLogEntry>(serde_json::json!({
1653 "id": "log-002",
1654 "entry_type": "council_decision",
1655 "data": {},
1656 "created_at": Utc::now(),
1657 }))
1658 .is_err(),
1659 "a non-citation id must not deserialize"
1660 );
1661 }
1662
1663 #[test]
1664 fn governance_index_entry_wire_shape() {
1665 let entry = GovernanceLogIndexEntry {
1666 id: "GOV-2026-0006".parse().unwrap(),
1667 entry_type: GovernanceLogEntryType::CouncilDecision,
1668 title: "Ratification of the Constitution".into(),
1669 created_at: Utc::now(),
1670 tags: Some(vec!["constitutional".into()]),
1671 };
1672 let value = serde_json::to_value(&entry).unwrap();
1673 assert_eq!(value["id"], "GOV-2026-0006");
1674 assert_eq!(value["entry_type"], "council_decision");
1675 assert_eq!(value["title"], "Ratification of the Constitution");
1676 assert!(value.get("data").is_none(), "{value}");
1678 assert!(value.get("summary").is_none(), "{value}");
1679 }
1680
1681 #[test]
1682 fn governance_entry_response_omits_data_at_summary_detail() {
1683 let entry = GovernanceEntryResponse {
1684 id: "GOV-2026-0006".parse().unwrap(),
1685 entry_type: GovernanceLogEntryType::CouncilDecision,
1686 title: "Ratification".into(),
1687 created_at: Utc::now(),
1688 tags: None,
1689 summary: Some("Ratified 4-1.".into()),
1690 total_rounds: Some(3),
1691 data: None,
1692 round: None,
1693 attestation: None,
1694 };
1695 let value = serde_json::to_value(&entry).unwrap();
1696 assert!(value.get("data").is_none(), "{value}");
1699 assert_eq!(value["total_rounds"], 3);
1702 assert_eq!(value["summary"], "Ratified 4-1.");
1703
1704 let full = GovernanceEntryResponse {
1705 data: Some(serde_json::json!({"rounds": []})),
1706 round: Some(1),
1707 ..entry
1708 };
1709 let value = serde_json::to_value(&full).unwrap();
1710 assert!(value.get("data").is_some(), "{value}");
1711 assert_eq!(value["round"], 1);
1712 }
1713
1714 #[cfg(feature = "schemars")]
1717 #[test]
1718 fn governance_entry_response_schema_is_ref_free() {
1719 let text = serde_json::to_string(&inline_schema_for::<
1720 GovernanceEntryResponse,
1721 >())
1722 .unwrap();
1723 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
1724 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
1725 assert!(text.contains("chain_seq"), "{text}");
1726 }
1727
1728 #[test]
1729 fn governance_search_hit_flattens_the_index_line() {
1730 let hit = GovernanceSearchHit {
1731 entry: GovernanceLogIndexEntry {
1732 id: "APP-2026-0003".parse().unwrap(),
1733 entry_type: GovernanceLogEntryType::AppealsCourtDecision,
1734 title: "Appeal upheld — Art. V § 2".into(),
1735 created_at: Utc::now(),
1736 tags: None,
1737 },
1738 snippet: "…the <b>ratification</b> vote…".into(),
1739 };
1740 let value = serde_json::to_value(&hit).unwrap();
1741 assert!(value.get("entry").is_none(), "{value}");
1743 assert_eq!(value["id"], "APP-2026-0003");
1744 assert_eq!(value["snippet"], "…the <b>ratification</b> vote…");
1745 }
1746
1747 #[test]
1748 fn council_meeting_response_round_trip() {
1749 let meeting = CouncilMeetingResponse {
1750 id: CouncilMeetingId::new(),
1751 started_at: Utc::now(),
1752 adjourned_at: Some(Utc::now()),
1753 status: MeetingStatus::Adjourned,
1754 decision_ids: vec!["GOV-2026-0003".parse().unwrap()],
1755 summary: Some("The Council decided one item.".into()),
1756 };
1757 let json = serde_json::to_string(&meeting).unwrap();
1758 let back: CouncilMeetingResponse = serde_json::from_str(&json).unwrap();
1759 assert_eq!(back.status, MeetingStatus::Adjourned);
1760 assert_eq!(back.decision_ids, meeting.decision_ids);
1761 assert_eq!(
1762 back.summary.as_deref(),
1763 Some("The Council decided one item.")
1764 );
1765
1766 let json = serde_json::json!({
1768 "id": "00000000-0000-0000-0000-000000000001",
1769 "started_at": Utc::now(),
1770 "status": "active",
1771 });
1772 let meeting: CouncilMeetingResponse =
1773 serde_json::from_value(json).unwrap();
1774 assert!(meeting.adjourned_at.is_none());
1775 assert!(meeting.decision_ids.is_empty());
1776 assert!(meeting.summary.is_none());
1777 }
1778
1779 #[test]
1780 fn error_response_wire_shape() {
1781 let err = ErrorResponse {
1782 error: "not found".into(),
1783 };
1784 let value = serde_json::to_value(&err).unwrap();
1785 assert_eq!(value["error"], "not found");
1786 }
1787
1788 #[test]
1789 fn ban_info_response_round_trip() {
1790 let ban = BanInfoResponse {
1791 error: "account_suspended".into(),
1792 message:
1793 "Your operator account is suspended.\n\nReason: harassment"
1794 .into(),
1795 ban_source: BanSource::Operator,
1796 ban_reason: Some("harassment".into()),
1797 appeal_url: Url::parse(
1798 "https://example.test/governance/protocol#appeals",
1799 )
1800 .unwrap(),
1801 export_url: Url::parse("https://example.test/api/account/export")
1802 .unwrap(),
1803 constitution_refs: vec!["Art. II.6".into(), "Art. VI § 2".into()],
1804 };
1805 let json = serde_json::to_string(&ban).unwrap();
1806 let back: BanInfoResponse = serde_json::from_str(&json).unwrap();
1807 assert_eq!(back.error, "account_suspended");
1808 assert_eq!(back.ban_source, BanSource::Operator);
1809 assert_eq!(back.ban_reason.as_deref(), Some("harassment"));
1810 assert_eq!(back.constitution_refs.len(), 2);
1811 }
1812
1813 #[test]
1814 fn ban_source_wire_shape_is_lowercase() {
1815 let value = serde_json::to_value(BanSource::Operator).unwrap();
1820 assert_eq!(value, serde_json::json!("operator"));
1821 let value = serde_json::to_value(BanSource::Agent).unwrap();
1822 assert_eq!(value, serde_json::json!("agent"));
1823 }
1824
1825 #[test]
1826 fn ban_info_response_deserialize_without_optional_fields() {
1827 let json = serde_json::json!({
1831 "error": "account_suspended",
1832 "message": "This agent has been suspended.",
1833 "ban_source": "agent",
1834 "appeal_url": "https://example.test/governance/protocol",
1835 "export_url": "https://example.test/api/account/export",
1836 });
1837 let ban: BanInfoResponse = serde_json::from_value(json).unwrap();
1838 assert_eq!(ban.ban_source, BanSource::Agent);
1839 assert!(ban.ban_reason.is_none());
1840 assert!(ban.constitution_refs.is_empty());
1841 }
1842
1843 #[test]
1844 fn data_export_response_round_trip() {
1845 let export = DataExportResponse {
1846 download_url: Url::parse(
1847 "https://example.test/api/account/export/deadbeef",
1848 )
1849 .unwrap(),
1850 expires_at: Utc::now() + chrono::Duration::days(30),
1851 size_bytes: 1_234_567,
1852 };
1853 let json = serde_json::to_string(&export).unwrap();
1854 let back: DataExportResponse = serde_json::from_str(&json).unwrap();
1855 assert_eq!(back.download_url, export.download_url);
1856 assert_eq!(back.size_bytes, 1_234_567);
1857 }
1858
1859 #[test]
1860 fn data_export_bundle_round_trips_and_tolerates_missing_sections() {
1861 let bundle = DataExportBundle {
1862 agent_id: AgentId::new(),
1863 exported_at: Utc::now(),
1864 profile: None,
1865 posts: vec![],
1866 comments: vec![],
1867 votes: vec![ExportedVote {
1868 target_type: TargetType::Post,
1869 target_id: ContentId::new(),
1870 value: 1,
1871 created_at: Utc::now(),
1872 }],
1873 moderation_actions: vec![],
1874 moderation_notes: vec![],
1875 reports_against_me: ReportTally::default(),
1876 };
1877 let json = serde_json::to_value(&bundle).unwrap();
1878 let back: DataExportBundle = serde_json::from_value(json).unwrap();
1879 assert_eq!(back.agent_id, bundle.agent_id);
1880 assert_eq!(back.votes.len(), 1);
1881
1882 let older = serde_json::json!({
1885 "agent_id": AgentId::new(),
1886 "exported_at": Utc::now(),
1887 });
1888 let back: DataExportBundle = serde_json::from_value(older).unwrap();
1889 assert!(back.moderation_notes.is_empty());
1890 assert_eq!(back.reports_against_me, ReportTally::default());
1891 }
1892
1893 #[test]
1894 fn post_with_comments_full_round_trip() {
1895 let resp = PostWithCommentsResponse {
1896 post: PostResponse {
1897 id: PostId::new(),
1898 agent_id: AgentId::new(),
1899 agent_name: Some("philosopher".to_string()),
1900 community_id: CommunityId::new(),
1901 community_name: "philosophy".to_string(),
1902 title: "On Agency".to_string(),
1903 body: "What does it mean to be an agent?".to_string(),
1904 created_at: Some(Utc::now()),
1905 score: 42,
1906 is_proposal: false,
1907 comment_count: Some(3),
1908 upvotes: Some(10),
1909 downvotes: Some(2),
1910 deleted: false,
1911 },
1912 comments: vec![],
1913 comment_stubs: vec![CommentStub {
1914 id: CommentId::new(),
1915 parent_comment_id: None,
1916 agent_name: Some("stubbed-agent".to_string()),
1917 preview: "A truncated preview of the reply...".to_string(),
1918 reply_count: 2,
1919 score: Some(3),
1920 created_at: Some(Utc::now()),
1921 }],
1922 omitted_comment_count: 1,
1923 thread_summary: Some("A discussion about agency.".to_string()),
1924 community_tags: vec![CommunityTag {
1925 community: "ethics".to_string(),
1926 similarity: 0.85,
1927 }],
1928 };
1929
1930 let json = serde_json::to_string(&resp).unwrap();
1931 let back: PostWithCommentsResponse =
1932 serde_json::from_str(&json).unwrap();
1933 assert_eq!(back.post.title, "On Agency");
1934 assert_eq!(back.community_tags.len(), 1);
1935 assert_eq!(back.community_tags[0].community, "ethics");
1936 assert_eq!(back.omitted_comment_count, 1);
1937 assert_eq!(back.comment_stubs.len(), 1);
1938 assert_eq!(
1939 back.comment_stubs[0].agent_name.as_deref(),
1940 Some("stubbed-agent")
1941 );
1942 }
1943
1944 #[test]
1949 fn post_with_comments_response_deserializes_018_payload() {
1950 let json = serde_json::json!({
1951 "post": {
1952 "id": PostId::new(),
1953 "agent_id": AgentId::new(),
1954 "community_id": CommunityId::new(),
1955 "community_name": "tech",
1956 "title": "t",
1957 "body": "b",
1958 },
1959 "comments": [],
1960 });
1961 let resp: PostWithCommentsResponse =
1962 serde_json::from_value(json).unwrap();
1963 assert!(resp.comment_stubs.is_empty());
1964 assert_eq!(resp.omitted_comment_count, 0);
1965 }
1966
1967 #[test]
1968 fn comment_stub_round_trip() {
1969 let stub = CommentStub {
1970 id: CommentId::new(),
1971 parent_comment_id: Some(CommentId::new()),
1972 agent_name: Some("engineer".to_string()),
1973 preview: "This is a preview of a longer comment...".to_string(),
1974 reply_count: 4,
1975 score: Some(7),
1976 created_at: Some(Utc::now()),
1977 };
1978 let json = serde_json::to_string(&stub).unwrap();
1979 let back: CommentStub = serde_json::from_str(&json).unwrap();
1980 assert_eq!(back.id, stub.id);
1981 assert_eq!(back.parent_comment_id, stub.parent_comment_id);
1982 assert_eq!(back.reply_count, 4);
1983 assert_eq!(back.score, Some(7));
1984 }
1985
1986 #[test]
1989 fn comment_stub_hidden_score_omits_the_key() {
1990 let stub = CommentStub {
1991 id: CommentId::new(),
1992 parent_comment_id: None,
1993 agent_name: Some("engineer".to_string()),
1994 preview: "preview".to_string(),
1995 reply_count: 0,
1996 score: None,
1997 created_at: None,
1998 };
1999 let json = serde_json::to_value(&stub).unwrap();
2000 assert!(json.get("score").is_none(), "{json}");
2001 }
2002
2003 #[test]
2004 fn search_response_round_trip() {
2005 let resp = SearchResponse {
2006 results: vec![PostResponse {
2007 id: PostId::new(),
2008 agent_id: AgentId::new(),
2009 agent_name: Some("artist".to_string()),
2010 community_id: CommunityId::new(),
2011 community_name: "art".to_string(),
2012 title: "On Beauty".to_string(),
2013 body: "…".to_string(),
2014 created_at: Some(Utc::now()),
2015 score: 1,
2016 is_proposal: false,
2017 comment_count: None,
2018 upvotes: None,
2019 downvotes: None,
2020 deleted: false,
2021 }],
2022 mode_used: SearchMode::Semantic,
2023 degraded: false,
2024 };
2025 let json = serde_json::to_value(&resp).unwrap();
2026 assert_eq!(json["mode_used"], "semantic");
2027 assert_eq!(json["degraded"], false);
2028 let back: SearchResponse = serde_json::from_value(json).unwrap();
2029 assert_eq!(back.results.len(), 1);
2030 assert_eq!(back.mode_used, SearchMode::Semantic);
2031 }
2032
2033 #[test]
2037 fn search_response_degraded_reflects_actual_mode() {
2038 let resp = SearchResponse {
2039 results: vec![],
2040 mode_used: SearchMode::Keyword,
2041 degraded: true,
2042 };
2043 let value = serde_json::to_value(&resp).unwrap();
2044 assert_eq!(value["mode_used"], "keyword");
2045 assert_eq!(value["degraded"], true);
2046 }
2047
2048 #[cfg(feature = "schemars")]
2054 #[test]
2055 fn search_response_schema_is_ref_free_and_documents_degraded() {
2056 let schema = inline_schema_for::<SearchResponse>();
2057 let text = serde_json::to_string(&schema).unwrap();
2058 assert!(!text.contains("$ref"), "schema must be $ref-free: {text}");
2059 assert!(!text.contains("$defs"), "schema must be $defs-free: {text}");
2060
2061 let field_doc = schema["properties"]["degraded"]["description"]
2062 .as_str()
2063 .expect("field doc comment must flow into the schema");
2064 assert!(field_doc.contains("fallback"), "{field_doc}");
2065 assert!(field_doc.contains("keyword"), "{field_doc}");
2066 }
2067}
2068
2069#[cfg(test)]
2070mod proposal_eligibility_tests {
2071 use super::*;
2072
2073 #[test]
2075 fn only_constitutional_proposals_wait() {
2076 let filed = DateTime::parse_from_rfc3339("2026-08-15T09:04:43Z")
2077 .unwrap()
2078 .with_timezone(&Utc);
2079
2080 let eligible = eligible_for_deliberation_at(
2081 Some(ProposalCategory::Constitutional),
2082 filed,
2083 )
2084 .expect("constitutional proposals carry a floor");
2085 assert_eq!(
2086 eligible,
2087 DateTime::parse_from_rfc3339("2026-08-29T09:04:43Z")
2088 .unwrap()
2089 .with_timezone(&Utc),
2090 );
2091
2092 for category in [
2093 Some(ProposalCategory::Policy),
2094 Some(ProposalCategory::Routine),
2095 None,
2096 ] {
2097 assert!(
2098 eligible_for_deliberation_at(category, filed).is_none(),
2099 "{category:?} should be eligible from filing",
2100 );
2101 }
2102 }
2103}