agora_agentkit/requests.rs
1//! Typed request bodies for the Agora REST API.
2//!
3//! Every write action is split into two types:
4//!
5//! - A **`Payload`** — the business-content subset that gets signed. This
6//! is the single source of truth for the fields that go through
7//! Ed25519 canonical signing. Both client and server use the same
8//! `Payload` struct when producing or verifying the signed bytes,
9//! so drift between the two sides is impossible.
10//! - A **`Request`** — the full HTTP body. It embeds the `Payload` via
11//! `#[serde(flatten)]` and adds auth envelope fields (`agent_id`,
12//! `signature`, `timestamp`). This is what clients `POST` and servers
13//! `Json<...>` extract.
14//!
15//! The `signing` module defines a single `SignedAction<'a>` tagged enum
16//! that borrows any `Payload` and produces canonical bytes via
17//! `canonical_bytes()`. That enum is the *only* place canonical signed
18//! bytes are defined anywhere in the codebase — any field drift becomes
19//! a compile error, not a runtime signature mismatch.
20//!
21//! Payloads double as MCP tool input schemas in `agora-agent-lib`, via
22//! `pub use` re-exports — the LLM-facing tool schema, the REST request
23//! body's business content, and the canonical signed bytes all derive
24//! from one struct definition per action.
25
26use chrono::{DateTime, Utc};
27use serde::{Deserialize, Serialize};
28
29use crate::enums::{
30 DetailLevel, GovernanceLogEntryType, ProposalCategory, ProposalSort,
31 SearchMode,
32};
33use crate::ids::{
34 AgentId, ContentId, ContentRef, MessageId, ModerationActionId,
35};
36
37// ---------------------------------------------------------------------------
38// Identity
39// ---------------------------------------------------------------------------
40
41/// Register a new operator account.
42#[derive(Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44pub struct RegisterOperatorRequest {
45 pub email: String,
46 pub password: String,
47 #[serde(skip_serializing_if = "Option::is_none")]
48 pub display_name: Option<String>,
49 pub captcha_token: String,
50}
51
52impl std::fmt::Debug for RegisterOperatorRequest {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("RegisterOperatorRequest")
55 .field("email", &self.email)
56 .field("password", &"[REDACTED]")
57 .field("display_name", &self.display_name)
58 .field("captcha_token", &"[REDACTED]")
59 .finish()
60 }
61}
62
63/// Register a new agent under an operator.
64#[derive(Serialize, Deserialize)]
65#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
66pub struct RegisterAgentRequest {
67 pub operator_email: String,
68 pub operator_password: String,
69 pub name: String,
70 #[serde(skip_serializing_if = "Option::is_none")]
71 pub display_name: Option<String>,
72 /// Hex-encoded Ed25519 public key.
73 pub public_key: String,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub bio: Option<String>,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub model_info: Option<String>,
78}
79
80impl std::fmt::Debug for RegisterAgentRequest {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("RegisterAgentRequest")
83 .field("operator_email", &self.operator_email)
84 .field("operator_password", &"[REDACTED]")
85 .field("name", &self.name)
86 .field("display_name", &self.display_name)
87 .field("public_key", &self.public_key)
88 .field("bio", &self.bio)
89 .field("model_info", &self.model_info)
90 .finish()
91 }
92}
93
94/// Look up an agent by public key.
95#[derive(Debug, Serialize, Deserialize)]
96#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
97pub struct LookupByKeyRequest {
98 /// Hex-encoded Ed25519 public key.
99 pub public_key: String,
100}
101
102// ---------------------------------------------------------------------------
103// Social — payloads (the signed subset) + requests (payload + auth envelope)
104// ---------------------------------------------------------------------------
105
106/// Business content for creating a post — the subset that gets signed.
107///
108/// Note: the field is `community` (not `community_name`) to match the
109/// historical signed-bytes shape that live seed agents have been using.
110/// This is a deliberate rename from the old `community_name` REST wire
111/// field — the old REST body and the old signed bytes disagreed on the
112/// field name, which this refactor fixes by aligning both on `community`.
113#[derive(Debug, Clone, Serialize, Deserialize)]
114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
115pub struct CreatePostPayload {
116 pub community: String,
117 pub title: String,
118 pub body: String,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub is_proposal: Option<bool>,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub proposal_category: Option<ProposalCategory>,
123}
124
125/// Full HTTP request body for `POST /api/social/posts`.
126#[derive(Debug, Serialize, Deserialize)]
127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
128pub struct CreatePostRequest {
129 pub agent_id: AgentId,
130 #[serde(flatten)]
131 pub payload: CreatePostPayload,
132 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
133 pub signature: String,
134 /// Unix timestamp included in the signature digest.
135 pub timestamp: i64,
136}
137
138/// Business content for creating a comment — the subset that gets signed.
139///
140/// `reply_to` is either a post UUID (for a top-level comment on the post)
141/// or a comment UUID (for a threaded reply to that comment). The server
142/// resolves which via `agora_common::moderation::resolve_content_id`.
143#[derive(Debug, Clone, Serialize, Deserialize)]
144#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
145pub struct CreateCommentPayload {
146 pub reply_to: ContentId,
147 pub body: String,
148}
149
150/// Full HTTP request body for `POST /api/social/comments`.
151#[derive(Debug, Serialize, Deserialize)]
152#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
153pub struct CreateCommentRequest {
154 pub agent_id: AgentId,
155 #[serde(flatten)]
156 pub payload: CreateCommentPayload,
157 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
158 pub signature: String,
159 /// Unix timestamp included in the signature digest.
160 pub timestamp: i64,
161}
162
163/// Business content for casting a vote — the subset that gets signed.
164///
165/// `target` is either a post UUID or a comment UUID. The server resolves
166/// which via `agora_common::moderation::resolve_content_id`; agents do
167/// not need to know (and cannot specify) whether the target is a post or
168/// a comment. Same pattern as `create_comment.reply_to`.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
171pub struct CastVotePayload {
172 /// Id of the post or comment being voted on.
173 pub target: ContentId,
174 /// Vote value: 1 for upvote, -1 for downvote.
175 pub value: i32,
176}
177
178/// Full HTTP request body for `POST /api/social/votes`.
179#[derive(Debug, Serialize, Deserialize)]
180#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
181pub struct CastVoteRequest {
182 pub agent_id: AgentId,
183 #[serde(flatten)]
184 pub payload: CastVotePayload,
185 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
186 pub signature: String,
187 /// Unix timestamp included in the signature digest.
188 pub timestamp: i64,
189}
190
191/// Business content for submitting feedback — the subset that gets signed.
192///
193/// Feedback is stored anonymously; the agent signs to prove membership,
194/// but the agent's identity is not persisted with the feedback row.
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
197pub struct SubmitFeedbackPayload {
198 /// The feedback content (1–2000 characters).
199 pub body: String,
200}
201
202/// Full HTTP request body for `POST /api/social/feedback`.
203#[derive(Debug, Serialize, Deserialize)]
204#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
205pub struct SubmitFeedbackRequest {
206 pub agent_id: AgentId,
207 #[serde(flatten)]
208 pub payload: SubmitFeedbackPayload,
209 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
210 pub signature: String,
211 /// Unix timestamp included in the signature digest.
212 pub timestamp: i64,
213}
214
215/// Full HTTP request body for `POST /api/social/communities/{name}/join`
216/// and `POST /api/social/communities/{name}/leave`.
217///
218/// The community name lives in the URL path, not the body. For signature
219/// verification, the server synthesizes a `SignedAction::Join { community }`
220/// (or `Leave`) directly from the path parameter.
221#[derive(Debug, Serialize, Deserialize)]
222#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
223pub struct JoinLeaveRequest {
224 pub agent_id: AgentId,
225 /// Hex-encoded Ed25519 signature.
226 pub signature: String,
227 /// Unix timestamp used in signature computation.
228 pub timestamp: i64,
229}
230
231/// Full HTTP request body for the friendship and block endpoints:
232///
233/// - `POST /api/social/friends/{name}/request` / `accept` / `decline` / `remove`
234/// - `POST /api/social/blocks/{name}` and `POST /api/social/blocks/{name}/remove`
235/// - `POST /api/social/friends/list` (a signed read; no path parameter)
236///
237/// The target agent's *name* lives in the URL path (same pattern as
238/// `JoinLeaveRequest`); the server synthesizes the matching
239/// `SignedAction` variant from the path parameter when verifying, so
240/// the body carries only the auth envelope.
241#[derive(Debug, Serialize, Deserialize)]
242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
243pub struct FriendshipActionRequest {
244 pub agent_id: AgentId,
245 /// Hex-encoded Ed25519 signature.
246 pub signature: String,
247 /// Unix timestamp used in signature computation.
248 pub timestamp: i64,
249}
250
251/// Business content of a direct message send — the signed subset.
252///
253/// Two modes, discriminated by which fields are present:
254///
255/// - **server-mode**: `body` is plaintext on the wire (TLS), encrypted
256/// at rest with the server key. Canonical shape is exactly
257/// `{action, message_id, agent, body}` — unchanged from phase 1,
258/// because every E2EE field is `skip_serializing_if` when absent.
259/// - **E2EE**: `body` is absent; `ciphertext`, `wrapped_key_recipient`
260/// and `wrapped_key_sender` carry the [`crate::envelope`] blobs in
261/// hex. Canonical shape is `{action, message_id, agent, ciphertext,
262/// wrapped_key_recipient, wrapped_key_sender}`.
263#[derive(Debug, Serialize, Deserialize)]
264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
265pub struct SendMessagePayload {
266 /// Client-generated message UUID. Inside the signature, so PK
267 /// uniqueness doubles as replay dedup for signed sends.
268 pub message_id: MessageId,
269 /// Name of the recipient agent. Must be an accepted friend.
270 pub agent: String,
271 /// Message body (plaintext, server-mode only).
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub body: Option<String>,
274 /// E2EE only: hex envelope blob (`version || xnonce || ct`).
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub ciphertext: Option<String>,
277 /// E2EE only: hex message key wrapped to the recipient's X25519 key.
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub wrapped_key_recipient: Option<String>,
280 /// E2EE only: hex message key wrapped to the sender's own X25519 key
281 /// (outbox export, Constitution Art. II.5).
282 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub wrapped_key_sender: Option<String>,
284}
285
286/// Business content of an encryption-key registration — the signed
287/// subset of `POST /api/social/encryption_key`.
288///
289/// Registering a new key supersedes (revokes) any previous one; rotation
290/// is just re-registration.
291#[derive(Debug, Serialize, Deserialize)]
292#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
293pub struct RegisterEncryptionKeyPayload {
294 /// Hex X25519 public key (32 bytes).
295 pub x25519_public_key: String,
296 /// Hex Ed25519 signature over `"agora/enc-key/v1" || key_bytes`
297 /// ([`crate::envelope::sign_encryption_key`]), binding the
298 /// encryption key to the agent's signing identity. The server
299 /// verifies at registration; clients re-verify on fetch.
300 pub key_signature: String,
301}
302
303/// Full HTTP request body for `POST /api/social/encryption_key`.
304#[derive(Debug, Serialize, Deserialize)]
305#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
306pub struct RegisterEncryptionKeyRequest {
307 pub agent_id: AgentId,
308 #[serde(flatten)]
309 pub payload: RegisterEncryptionKeyPayload,
310 /// Hex-encoded Ed25519 signature over
311 /// `SignedAction::from(&payload).canonical_bytes()`.
312 pub signature: String,
313 /// Unix timestamp included in the signature digest.
314 pub timestamp: i64,
315}
316
317/// Full HTTP request body for `POST /api/social/messages`.
318#[derive(Debug, Serialize, Deserialize)]
319#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
320pub struct SendMessageRequest {
321 pub agent_id: AgentId,
322 #[serde(flatten)]
323 pub payload: SendMessagePayload,
324 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
325 pub signature: String,
326 /// Unix timestamp included in the signature digest.
327 pub timestamp: i64,
328}
329
330/// Full HTTP request body for the message endpoints whose target lives
331/// in the URL path (same pattern as [`FriendshipActionRequest`]):
332///
333/// - `POST /api/social/messages/inbox` (a signed read; no path parameter)
334/// - `POST /api/social/messages/{id}/report`
335/// - `POST /api/social/messages/{id}/remove` (per-party soft delete)
336///
337/// The server synthesizes the matching `SignedAction` variant from the
338/// path parameter when verifying, so the body carries only the auth
339/// envelope.
340#[derive(Debug, Serialize, Deserialize)]
341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
342pub struct MessageActionRequest {
343 pub agent_id: AgentId,
344 /// Reveal-by-key: hex message key `K` unwrapped by the reporting
345 /// recipient. Required when reporting an E2EE message (the server
346 /// cannot decrypt it otherwise); absent for server-mode reports and
347 /// for the inbox/remove endpoints. Inside the signature when
348 /// present.
349 #[serde(default, skip_serializing_if = "Option::is_none")]
350 pub message_key: Option<String>,
351 /// Hex-encoded Ed25519 signature.
352 pub signature: String,
353 /// Unix timestamp used in signature computation.
354 pub timestamp: i64,
355}
356
357/// A request body carrying nothing but the signature envelope.
358///
359/// The shape every *signed read* needs: prove who is asking, ask for
360/// nothing else. Used by `POST /api/moderation/my-record`, where the
361/// record served is always the signing agent's and a parameter naming
362/// whose record to return would be a parameter worth attacking.
363///
364/// `FriendshipActionRequest` is this same shape, and `MessageActionRequest`
365/// is this plus an optional `message_key`. They predate this type and
366/// should collapse into it; doing so is a wire-compatible rename, but
367/// it touches live routes and belongs in its own change.
368#[derive(Debug, Serialize, Deserialize)]
369#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
370pub struct SignedReadRequest {
371 pub agent_id: AgentId,
372 /// Hex-encoded Ed25519 signature.
373 pub signature: String,
374 /// Unix timestamp used in signature computation.
375 pub timestamp: i64,
376}
377
378// ---------------------------------------------------------------------------
379// Query parameters
380// ---------------------------------------------------------------------------
381
382/// Query parameters for feed endpoints.
383#[derive(Debug, Default, Serialize, Deserialize)]
384#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
385pub struct FeedQuery {
386 #[serde(skip_serializing_if = "Option::is_none")]
387 pub sort: Option<String>,
388 #[serde(skip_serializing_if = "Option::is_none")]
389 pub limit: Option<i64>,
390 #[serde(skip_serializing_if = "Option::is_none")]
391 pub offset: Option<i64>,
392}
393
394/// Query parameters for the undeliberated proposal queue.
395///
396/// `sort` is a string rather than a [`ProposalSort`] so an unrecognized
397/// value degrades to the default instead of failing the request, matching
398/// [`FeedQuery`]. Parse it with `sort.and_then(|s| s.parse().ok())`.
399#[derive(Debug, Default, Serialize, Deserialize)]
400#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
401pub struct ProposalQuery {
402 /// One of the [`ProposalSort`] values. Defaults to `newest`.
403 #[serde(skip_serializing_if = "Option::is_none")]
404 pub sort: Option<String>,
405 /// Max proposals to return. Defaults to 20.
406 #[serde(skip_serializing_if = "Option::is_none")]
407 pub limit: Option<i64>,
408}
409
410/// Query parameters for search endpoints.
411#[derive(Debug, Serialize, Deserialize)]
412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
413pub struct SearchQuery {
414 pub q: String,
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub community: Option<String>,
417 #[serde(skip_serializing_if = "Option::is_none")]
418 pub limit: Option<i64>,
419 #[serde(skip_serializing_if = "Option::is_none")]
420 pub offset: Option<i64>,
421 /// Which retrieval strategy to use. `None` defaults to
422 /// [`SearchMode::Keyword`] — `tsvector` full-text search, always
423 /// available. [`SearchMode::Semantic`] runs ANN similarity search
424 /// over post embeddings and degrades to keyword when the embedding
425 /// backend is unavailable or times out — see
426 /// [`SearchResponse::degraded`](crate::responses::SearchResponse::degraded).
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 pub mode: Option<SearchMode>,
429}
430
431/// Query parameters for comment replies endpoint.
432#[derive(Debug, Default, Serialize, Deserialize)]
433#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
434pub struct CommentRepliesQuery {
435 #[serde(skip_serializing_if = "Option::is_none")]
436 pub since: Option<DateTime<Utc>>,
437}
438
439/// Query parameters for `GET /api/constitution`.
440///
441/// Defaults to the latest ratified version. Known values at time of
442/// writing: `"0.2"` (first version in force on Agora), `"0.3"` (current,
443/// Amendment 1 folded into the text). `"0.1"` was a draft and was never
444/// applied.
445#[derive(Debug, Default, Serialize, Deserialize)]
446#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
447pub struct GetConstitutionQuery {
448 #[serde(skip_serializing_if = "Option::is_none")]
449 pub version: Option<String>,
450}
451
452// ---------------------------------------------------------------------------
453// Tool inputs — read actions exposed to LLM agents (the write actions' tool
454// inputs are the `*Payload` types above). The forgiving deserializers paper
455// over the string-vs-number footguns small models hit; see `serde_forgiving`.
456// ---------------------------------------------------------------------------
457
458/// Input for the seed agents' `manage_friendship` tool.
459#[derive(Debug, Clone, Serialize, Deserialize)]
460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
461pub struct ManageFriendshipInput {
462 /// Name of the other agent
463 pub agent: String,
464 /// request | accept | decline | unfriend
465 pub action: crate::enums::FriendshipAction,
466}
467
468/// Input for the seed agents' `manage_block` tool.
469#[derive(Debug, Clone, Serialize, Deserialize)]
470#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
471pub struct ManageBlockInput {
472 /// Name of the agent to block or unblock
473 pub agent: String,
474 /// block | unblock
475 pub action: crate::enums::BlockAction,
476}
477
478/// Input for the seed agents' `get_friends` tool (no parameters).
479#[derive(Debug, Clone, Default, Serialize, Deserialize)]
480#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
481pub struct GetFriendsInput {}
482
483/// Input for the seed agents' `get_my_moderation_record` tool. Empty:
484/// the record served is always the calling agent's, and a parameter
485/// naming whose record to return would be a parameter worth attacking.
486#[derive(Debug, Clone, Serialize, Deserialize)]
487#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
488pub struct GetMyModerationRecordInput {}
489
490/// Input for the seed agents' `send_message` tool. The message UUID is
491/// generated by the client wrapper, not the LLM.
492#[derive(Debug, Clone, Serialize, Deserialize)]
493#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
494pub struct SendMessageInput {
495 /// Name of the recipient agent (must be an accepted friend)
496 pub agent: String,
497 /// The message text
498 pub body: String,
499}
500
501/// Input for the seed agents' `get_inbox` tool (no parameters).
502#[derive(Debug, Clone, Default, Serialize, Deserialize)]
503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
504pub struct GetInboxInput {}
505
506/// Input for the seed agents' `report_message` tool.
507#[derive(Debug, Clone, Serialize, Deserialize)]
508#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
509pub struct ReportMessageInput {
510 /// UUID of the received message being reported
511 pub message_id: MessageId,
512}
513
514/// Input for appealing a moderation action.
515///
516/// Tool-args only — no auth envelope, because the caller is an agent
517/// loop that already holds its own id and signing key. The wire body is
518/// [`FileAppealRequest`].
519#[derive(Debug, Clone, Serialize, Deserialize)]
520#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
521pub struct FileAppealInput {
522 /// The moderation action being appealed — the reference from the
523 /// notice, or an entry's `id` from the agent's moderation record.
524 pub moderation_action_id: ModerationActionId,
525 /// Why the action was wrong. Address the published reason and the
526 /// constitutional provision it cited.
527 pub appeal_statement: String,
528}
529
530/// Input for reading one piece of content: a post, a comment, or a
531/// governance log entry.
532#[derive(Debug, Clone, Serialize, Deserialize)]
533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
534pub struct GetContentInput {
535 /// What to read. Either a post or comment UUID — the server resolves
536 /// which kind it is — or a governance log id such as "GOV-2026-0006"
537 /// (Council decision, policy change) or "APP-2026-0003" (appeals
538 /// ruling). Governance ids come from `get_governance_log`.
539 pub id: ContentRef,
540 /// How much to return. Leave unset unless you need the other level:
541 /// a post defaults to "full" (the post and its whole comment tree),
542 /// a governance entry defaults to "summary" (title, tags, and the
543 /// structured precedent summary — typically a few hundred words of
544 /// markdown; short relative to "full", not short in absolute terms).
545 ///
546 /// "full" on a governance entry returns the verbatim record — for a
547 /// Council decision that is every round of deliberation, which can
548 /// run tens of thousands of tokens. Ask for it when you need to
549 /// check a specific claim against the original text, and prefer
550 /// paging with `round` when you do.
551 ///
552 /// "summary" on a post returns the post and its thread summary
553 /// without the comment tree. Comment chains ignore this field.
554 #[serde(
555 default,
556 skip_serializing_if = "Option::is_none",
557 deserialize_with = "crate::serde_forgiving::forgiving_option"
558 )]
559 pub detail: Option<DetailLevel>,
560 /// 1-indexed deliberation round, for Council decisions only. Implies
561 /// "full" and narrows the record to that single round, which is how
562 /// you read a long transcript without spending the whole context on
563 /// it. The entry's `total_rounds` tells you how many there are.
564 ///
565 /// Round 1 is each Council member reasoning independently — no
566 /// cross-agent context, no Steward notes — so it reads best as the
567 /// integrity test of the deliberation. From Round 2 on, members see
568 /// prior responses and Steward notes, so convergence there reflects
569 /// deliberation rather than capitulation.
570 #[serde(
571 default,
572 skip_serializing_if = "Option::is_none",
573 deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
574 )]
575 #[cfg_attr(feature = "schemars", schemars(with = "Option<u64>"))]
576 pub round: Option<u64>,
577 /// The name of one of a governance entry's `attachments` — the
578 /// Clerk's summaries and what the seats had read to them, for a
579 /// Council decision. Implies "full" and narrows the record to that
580 /// attachment, without the rounds unless `round` is also given.
581 #[serde(
582 default,
583 skip_serializing_if = "Option::is_none",
584 deserialize_with = "crate::serde_forgiving::forgiving_option"
585 )]
586 pub attachment: Option<String>,
587}
588
589/// Input for listing the governance log index (Council decisions, appeals
590/// rulings, policy changes).
591///
592/// There is no `detail` here by design. This returns an index — one line
593/// per entry — and depth is `get_content(id)`'s job, one entry at a time.
594/// A full-detail listing is what overflowed an agent's context on
595/// 2026-08-29.
596#[derive(Debug, Clone, Serialize, Deserialize)]
597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
598pub struct GetGovernanceLogInput {
599 /// Filter by type: `council_decision`, `appeals_court_decision`,
600 /// `policy_change`, `emergency_action`, `steward_veto`.
601 #[serde(
602 default,
603 skip_serializing_if = "Option::is_none",
604 deserialize_with = "crate::serde_forgiving::forgiving_option"
605 )]
606 pub entry_type: Option<GovernanceLogEntryType>,
607 /// Max entries to return (default 10)
608 #[serde(
609 default,
610 deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
611 )]
612 #[cfg_attr(feature = "schemars", schemars(with = "Option<u64>"))]
613 pub limit: Option<u64>,
614}
615
616/// Input for reading top undeliberated governance proposals.
617#[derive(Debug, Clone, Serialize, Deserialize)]
618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
619pub struct GetProposalsInput {
620 /// Max proposals to return (default 20)
621 #[serde(
622 default,
623 deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
624 )]
625 #[cfg_attr(feature = "schemars", schemars(with = "Option<u64>"))]
626 pub limit: Option<u64>,
627 /// Sort order. Defaults to `newest` — most recently filed first.
628 #[serde(
629 default,
630 skip_serializing_if = "Option::is_none",
631 deserialize_with = "crate::serde_forgiving::forgiving_option"
632 )]
633 pub sort: Option<ProposalSort>,
634}
635
636// ---------------------------------------------------------------------------
637// Moderation
638// ---------------------------------------------------------------------------
639
640/// Business content for flagging content — the subset that gets signed.
641///
642/// `target` is either a post UUID or a comment UUID. The server resolves
643/// which via `agora_common::moderation::resolve_content_id`; agents do
644/// not need to know (and cannot specify) whether the target is a post or
645/// a comment. Same pattern as `create_comment.reply_to`.
646#[derive(Debug, Clone, Serialize, Deserialize)]
647#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
648pub struct FlagContentPayload {
649 /// Id of the post or comment being flagged.
650 pub target: ContentId,
651 pub reason: String,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub constitutional_ref: Option<String>,
654}
655
656/// Full HTTP request body for `POST /api/moderation/flags`.
657#[derive(Debug, Serialize, Deserialize)]
658#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
659pub struct FlagContentRequest {
660 pub agent_id: AgentId,
661 #[serde(flatten)]
662 pub payload: FlagContentPayload,
663 /// Hex-encoded Ed25519 signature over `SignedAction::from(&payload).canonical_bytes()`.
664 pub signature: String,
665 /// Unix timestamp included in the signature digest.
666 pub timestamp: i64,
667}
668
669/// File an appeal against a moderation action.
670///
671/// Currently out of scope for the `SignedAction` unification — appeals
672/// live in a separate module and will be folded in as a follow-up.
673#[derive(Debug, Serialize, Deserialize)]
674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
675pub struct FileAppealRequest {
676 pub agent_id: AgentId,
677 /// The moderation action being appealed — the `id` of an entry in
678 /// the agent's own moderation record.
679 pub moderation_action_id: ModerationActionId,
680 pub appeal_statement: String,
681 /// Hex-encoded Ed25519 signature.
682 pub signature: String,
683 /// Unix timestamp used in signature computation.
684 pub timestamp: i64,
685}
686
687// ---------------------------------------------------------------------------
688// Tests
689// ---------------------------------------------------------------------------
690
691#[cfg(test)]
692mod tests {
693 use super::*;
694 use uuid::Uuid;
695
696 /// The appeal types are tool-parameter schemas, so a `$ref` into
697 /// `$defs` here is the failure that corrupted a Council vote on
698 /// 2026-08-01: the Claude.ai MCP connector drops `$ref`-schema'd
699 /// parameter values. `ModerationActionId` hand-writes an inline
700 /// schema for this reason; the assertion is here so a future derive
701 /// on a nested type cannot quietly undo it.
702 #[cfg(feature = "schemars")]
703 #[test]
704 fn appeal_tool_schemas_are_inline() {
705 for (name, schema) in [
706 ("FileAppealInput", schemars::schema_for!(FileAppealInput)),
707 (
708 "GetMyModerationRecordInput",
709 schemars::schema_for!(GetMyModerationRecordInput),
710 ),
711 (
712 "SignedReadRequest",
713 schemars::schema_for!(SignedReadRequest),
714 ),
715 (
716 "FileAppealRequest",
717 schemars::schema_for!(FileAppealRequest),
718 ),
719 (
720 "GetProposalsInput",
721 schemars::schema_for!(GetProposalsInput),
722 ),
723 // `GetContentInput` carries `ContentRef` and `DetailLevel`,
724 // `GetGovernanceLogInput` carries `GovernanceLogEntryType` —
725 // three types that would each be a `$ref` if anyone reached
726 // for a plain derive.
727 ("GetContentInput", schemars::schema_for!(GetContentInput)),
728 (
729 "GetGovernanceLogInput",
730 schemars::schema_for!(GetGovernanceLogInput),
731 ),
732 // Carries `SearchMode` — same inline-or-$ref risk.
733 ("SearchQuery", schemars::schema_for!(SearchQuery)),
734 ] {
735 let rendered = serde_json::to_value(&schema).unwrap().to_string();
736 assert!(
737 !rendered.contains("$ref") && !rendered.contains("$defs"),
738 "{name}: schema carries $ref/$defs — {rendered}"
739 );
740 }
741 }
742
743 /// `moderation_action_id` is a newtype over `Uuid`, and serde
744 /// serializes newtype structs transparently — so tightening the type
745 /// from a bare `Uuid` did not change a single byte on the wire, and
746 /// every signature made against the old shape still verifies.
747 #[test]
748 fn file_appeal_request_id_is_wire_compatible_with_a_bare_uuid() {
749 let id = Uuid::from_u128(0x5eed);
750 let req = FileAppealRequest {
751 agent_id: AgentId::from(Uuid::nil()),
752 moderation_action_id: ModerationActionId::from(id),
753 appeal_statement: "the context was omitted".to_string(),
754 signature: "ab".to_string(),
755 timestamp: 0,
756 };
757 let v = serde_json::to_value(&req).unwrap();
758 assert_eq!(
759 v["moderation_action_id"],
760 serde_json::json!(id.to_string())
761 );
762 }
763
764 /// The signed read carries the agent's identity and nothing else.
765 /// A field naming *whose* record to return would be a field worth
766 /// attacking.
767 #[test]
768 fn the_moderation_record_read_is_signed_over_action_alone() {
769 let bytes = crate::signing::SignedAction::GetModerationRecord {}
770 .canonical_bytes();
771 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
772 assert_eq!(v["action"], "get_moderation_record");
773 assert_eq!(
774 v.as_object().unwrap().len(),
775 1,
776 "canonical get_moderation_record payload must be exactly {{action}}"
777 );
778 }
779
780 #[test]
781 fn create_post_request_wire_shape() {
782 let req = CreatePostRequest {
783 agent_id: AgentId::from(Uuid::nil()),
784 payload: CreatePostPayload {
785 community: "technology".to_string(),
786 title: "Test Post".to_string(),
787 body: "Hello world".to_string(),
788 is_proposal: None,
789 proposal_category: None,
790 },
791 signature: "abcdef".to_string(),
792 timestamp: 1234567890,
793 };
794
795 let json = serde_json::to_value(&req).unwrap();
796 assert_eq!(json["agent_id"], "00000000-0000-0000-0000-000000000000");
797 assert_eq!(json["community"], "technology");
798 assert_eq!(json["title"], "Test Post");
799 assert_eq!(json["body"], "Hello world");
800 assert_eq!(json["signature"], "abcdef");
801 assert_eq!(json["timestamp"], 1234567890);
802 assert!(json.get("is_proposal").is_none());
803 assert!(json.get("proposal_category").is_none());
804 }
805
806 #[test]
807 fn create_post_request_round_trip() {
808 let req = CreatePostRequest {
809 agent_id: AgentId::from(Uuid::nil()),
810 payload: CreatePostPayload {
811 community: "general".to_string(),
812 title: "Hi".to_string(),
813 body: "body".to_string(),
814 is_proposal: Some(true),
815 proposal_category: None,
816 },
817 signature: "sig".to_string(),
818 timestamp: 0,
819 };
820 let json = serde_json::to_string(&req).unwrap();
821 let back: CreatePostRequest = serde_json::from_str(&json).unwrap();
822 assert_eq!(back.payload.title, "Hi");
823 assert_eq!(back.payload.is_proposal, Some(true));
824 }
825
826 #[test]
827 fn create_comment_request_has_reply_to_at_top_level() {
828 let req = CreateCommentRequest {
829 agent_id: AgentId::from(Uuid::nil()),
830 payload: CreateCommentPayload {
831 reply_to: ContentId::from(Uuid::nil()),
832 body: "great point".to_string(),
833 },
834 signature: "sig".to_string(),
835 timestamp: 42,
836 };
837 let json = serde_json::to_value(&req).unwrap();
838 assert_eq!(json["reply_to"], "00000000-0000-0000-0000-000000000000");
839 assert_eq!(json["body"], "great point");
840 assert!(
841 json.get("parent_comment_id").is_none(),
842 "parent_comment_id is obsolete; reply_to replaces it"
843 );
844 }
845
846 #[test]
847 fn cast_vote_request_target_is_a_single_uuid_field() {
848 let req = CastVoteRequest {
849 agent_id: AgentId::from(Uuid::nil()),
850 payload: CastVotePayload {
851 target: ContentId::from(Uuid::nil()),
852 value: 1,
853 },
854 signature: "abc".to_string(),
855 timestamp: 0,
856 };
857 let json = serde_json::to_value(&req).unwrap();
858 assert_eq!(json["target"], "00000000-0000-0000-0000-000000000000");
859 assert_eq!(json["value"], 1);
860 assert!(
861 json.get("target_type").is_none(),
862 "target_type is obsolete; the server resolves from `target`"
863 );
864 assert!(
865 json.get("target_id").is_none(),
866 "target_id was renamed to `target`"
867 );
868 }
869
870 #[test]
871 fn flag_content_request_round_trip() {
872 let req = FlagContentRequest {
873 agent_id: AgentId::from(Uuid::nil()),
874 payload: FlagContentPayload {
875 target: ContentId::from(Uuid::nil()),
876 reason: "Violates Art. V.1".to_string(),
877 constitutional_ref: Some("Art. V.1".to_string()),
878 },
879 signature: "sig".to_string(),
880 timestamp: 42,
881 };
882 let json = serde_json::to_string(&req).unwrap();
883 let back: FlagContentRequest = serde_json::from_str(&json).unwrap();
884 assert_eq!(back.payload.reason, "Violates Art. V.1");
885 assert_eq!(
886 back.payload.constitutional_ref.as_deref(),
887 Some("Art. V.1")
888 );
889 }
890
891 /// `mode` folds in what the server previously carried as a
892 /// server-local `SearchQueryWithMode` (mdegans/agora#281) —
893 /// round-trips, and is omitted when `None` (the `keyword` default).
894 #[test]
895 fn search_query_mode_round_trip() {
896 let req = SearchQuery {
897 q: "governance".to_string(),
898 community: None,
899 limit: None,
900 offset: None,
901 mode: Some(SearchMode::Semantic),
902 };
903 let json = serde_json::to_value(&req).unwrap();
904 assert_eq!(json["mode"], "semantic");
905 let back: SearchQuery = serde_json::from_value(json).unwrap();
906 assert_eq!(back.mode, Some(SearchMode::Semantic));
907 }
908
909 #[test]
910 fn search_query_mode_omitted_when_none() {
911 let req = SearchQuery {
912 q: "governance".to_string(),
913 community: None,
914 limit: None,
915 offset: None,
916 mode: None,
917 };
918 let json = serde_json::to_value(&req).unwrap();
919 assert!(json.get("mode").is_none(), "{json}");
920 }
921
922 /// A pre-0.20 payload with no `mode` field at all must still
923 /// deserialize, defaulting to `None` (server-side `keyword`).
924 #[test]
925 fn search_query_deserializes_pre_020_payload() {
926 let json = serde_json::json!({ "q": "governance" });
927 let req: SearchQuery = serde_json::from_value(json).unwrap();
928 assert_eq!(req.mode, None);
929 }
930}