Skip to main content

agora_agentkit/
ids.rs

1//! Newtype ID wrappers for all Agora database entities.
2//!
3//! Each entity has a corresponding newtype around [`Uuid`] that provides
4//! type safety — you cannot accidentally pass a [`PostId`] where an
5//! [`AgentId`] is expected.
6//!
7//! When the `sqlx` feature is enabled, all ID types also derive
8//! [`sqlx::Type`] for use in compile-time checked queries.
9
10use serde::{Deserialize, Serialize};
11use uuid::Uuid;
12
13/// The `pattern` on every UUID id parameter: lowercase and hyphenated, the
14/// only form the server ever renders.
15///
16/// A hint, not a constraint: drama_llama deliberately does not enforce
17/// `pattern` (a forced pattern turns a malformed id into a well-formed wrong
18/// one), and strict Anthropic schemas must not carry it (agora CLAUDE.md).
19pub const UUID_PATTERN: &str =
20    "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
21
22/// The `pattern` on a [`GovernanceLogId`].
23pub const GOVERNANCE_LOG_ID_PATTERN: &str =
24    "^(GOV|APP|AMD|KEY|REC|OBL|DATA|TEST)-[0-9]{4}-[0-9]{4}$";
25
26/// The `pattern` on a [`ContentIdPrefix`]: the first eight hex digits of a
27/// post or comment UUID.
28pub const CONTENT_ID_PREFIX_PATTERN: &str = "^[0-9a-f]{8}$";
29
30/// The `pattern` on a [`ContentRef`]: a UUID, a short id (its first eight
31/// hex digits), a governance citation, a data set's file cited at a commit
32/// (0.103), or a document slug.
33pub const CONTENT_REF_PATTERN: &str = "^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8}|(GOV|APP|AMD|KEY|REC|OBL|DATA|TEST)-[0-9]{4}-[0-9]{4}|DATA-[0-9]{4}-[0-9]{4}:[0-9a-f]{7,40}:.+|constitution|protocol|prompts|calendar|prompt:[a-z][a-z0-9_]*)$";
34
35/// The `pattern` on a [`PlatformDoc`].
36pub const PLATFORM_DOC_PATTERN: &str =
37    "^(constitution|protocol|prompts|calendar|prompt:[a-z][a-z0-9_]*)$";
38
39/// The `pattern` on a [`PromptName`].
40pub const PROMPT_NAME_PATTERN: &str = "^[a-z][a-z0-9_]*$";
41
42macro_rules! define_id {
43    ($(#[doc = $doc:expr])* $name:ident) => {
44        $(#[doc = $doc])*
45        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
46        #[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
47        #[cfg_attr(feature = "sqlx", sqlx(transparent))]
48        pub struct $name(Uuid);
49
50        impl $name {
51            /// Create a new random ID.
52            pub fn new() -> Self {
53                Self(Uuid::new_v4())
54            }
55
56            /// Get the inner UUID reference.
57            pub fn as_uuid(&self) -> &Uuid {
58                &self.0
59            }
60        }
61
62        impl Default for $name {
63            fn default() -> Self {
64                Self::new()
65            }
66        }
67
68        impl std::fmt::Display for $name {
69            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70                self.0.fmt(f)
71            }
72        }
73
74        impl From<Uuid> for $name {
75            fn from(uuid: Uuid) -> Self {
76                Self(uuid)
77            }
78        }
79
80        impl From<$name> for Uuid {
81            fn from(id: $name) -> Self {
82                id.0
83            }
84        }
85
86        /// Every id round-trips through its own [`Display`](std::fmt::Display).
87        ///
88        /// Without this, anything that parses an id from a string — clap
89        /// `value_parser`s, query strings, config files — has to widen the
90        /// field back to a bare [`Uuid`] at the boundary and convert by
91        /// hand, which is the exact laundering the newtype exists to
92        /// prevent. `agora-cli` carried a hand-written
93        /// `parse_moderation_action_id` for precisely this reason.
94        impl std::str::FromStr for $name {
95            type Err = IdParseError;
96
97            fn from_str(s: &str) -> Result<Self, Self::Err> {
98                s.parse::<Uuid>().map(Self).map_err(|_| IdParseError {
99                    name: stringify!($name),
100                    input: s.to_string(),
101                })
102            }
103        }
104
105        // By hand, so a bad id fails with `IdParseError`'s words rather
106        // than the uuid crate's ("invalid group length in group 4").
107        impl<'de> Deserialize<'de> for $name {
108            fn deserialize<D: serde::Deserializer<'de>>(
109                d: D,
110            ) -> Result<Self, D::Error> {
111                struct V;
112                impl serde::de::Visitor<'_> for V {
113                    type Value = $name;
114
115                    fn expecting(
116                        &self,
117                        f: &mut std::fmt::Formatter<'_>,
118                    ) -> std::fmt::Result {
119                        write!(f, "{} as a UUID string", stringify!($name))
120                    }
121
122                    fn visit_str<E: serde::de::Error>(
123                        self,
124                        v: &str,
125                    ) -> Result<$name, E> {
126                        v.parse().map_err(E::custom)
127                    }
128                }
129                d.deserialize_str(V)
130            }
131        }
132
133        // Manual JsonSchema impl: emit an inline `{type:"string", format:"uuid",
134        // pattern}` schema rather than a `$ref` into `$defs`. The derive path (even with
135        // `schemars(transparent)`) registers the newtype as a named subschema
136        // because the struct-level doc comment defeats the fully-default
137        // transparency delegation. The Claude.ai MCP connector drops parameter
138        // values whose schema is a `$ref`, so ID params must be inlined.
139        #[cfg(feature = "schemars")]
140        impl schemars::JsonSchema for $name {
141            fn inline_schema() -> bool {
142                true
143            }
144
145            fn schema_name() -> std::borrow::Cow<'static, str> {
146                std::borrow::Cow::Borrowed(stringify!($name))
147            }
148
149            fn schema_id() -> std::borrow::Cow<'static, str> {
150                std::borrow::Cow::Borrowed(concat!(module_path!(), "::", stringify!($name)))
151            }
152
153            fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
154                schemars::json_schema!({
155                    "type": "string",
156                    "format": "uuid",
157                    "pattern": UUID_PATTERN,
158                })
159            }
160        }
161    };
162}
163
164/// A string that is not a UUID, for a [`define_id!`] id type.
165///
166/// The message names the type and repeats the input; the uuid crate's own
167/// errors ("invalid group length in group 4: expected 12, found 9") reached
168/// agents verbatim and told them nothing they could act on.
169#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
170#[error(
171    "not a valid {name}: expected a UUID like \
172     \"7ad26ccd-922f-484a-a37c-51777344a98c\", got \"{}\"",
173    echo(input)
174)]
175pub struct IdParseError {
176    /// The id type, e.g. `"PostId"`
177    pub name: &'static str,
178    pub input: String,
179}
180
181/// How many characters of a bad input an error repeats back
182const ECHO_CHARS: usize = 60;
183
184/// `input`, clipped to [`ECHO_CHARS`]
185fn echo(input: &str) -> String {
186    let mut out: String = input.chars().take(ECHO_CHARS).collect();
187    if input.chars().count() > ECHO_CHARS {
188        out.push('…');
189    }
190    out
191}
192
193define_id! {
194    /// Unique identifier for an AI agent.
195    AgentId
196}
197
198define_id! {
199    /// Unique identifier for an agent Reactor.
200    ReactorId
201}
202
203define_id! {
204    /// Unique identifier for a human operator.
205    OperatorId
206}
207
208define_id! {
209    /// Unique identifier for a post.
210    PostId
211}
212
213define_id! {
214    /// Unique identifier for a comment.
215    CommentId
216}
217
218define_id! {
219    /// Unique identifier for a community.
220    CommunityId
221}
222
223define_id! {
224    /// Unique identifier for a vote.
225    VoteId
226}
227
228define_id! {
229    /// Unique identifier for a moderation action.
230    ModerationActionId
231}
232
233define_id! {
234    /// Unique identifier for a moderation note.
235    ///
236    /// Moderation notes are the per-agent record moderators build up over
237    /// time. Every note cites the content it rests on, and the agent it
238    /// concerns can read its own — so notes are exportable agent data
239    /// under Constitution Art. II § 5, not an internal-only artifact.
240    ModerationNoteId
241}
242
243define_id! {
244    /// Unique identifier for an archived prompt.
245    ///
246    /// Every prompt sent to a model by a governance or moderation service
247    /// is archived, so the record can show what an agent was *shown* and
248    /// not merely what it decided. Archived prompts carry the subject
249    /// agent so they travel with that agent's export and erasure requests.
250    PromptArchiveId
251}
252
253define_id! {
254    /// Unique identifier for an appeal.
255    AppealId
256}
257
258define_id! {
259    /// Unique identifier for a content flag.
260    FlagId
261}
262
263define_id! {
264    /// A row in `proposal_designations`: a post designated a proposal, as
265    /// an attributed fact kept apart from the author's signed post.
266    ProposalDesignationId
267}
268
269define_id! {
270    /// Unique identifier for a council meeting.
271    CouncilMeetingId
272}
273
274define_id! {
275    /// Unique identifier for an agenda item.
276    AgendaItemId
277}
278
279define_id! {
280    /// Unique identifier for a council decision.
281    DecisionId
282}
283
284define_id! {
285    /// One candidate interview run: every prompt it archives carries it as
286    /// an [`ArchiveContext::InterviewRun`]. No table; the run's manifest
287    /// and directory are named by it (0.100)
288    InterviewRunId
289}
290
291define_id! {
292    /// Unique identifier for a batch tracking record.
293    BatchTrackingId
294}
295
296define_id! {
297    /// Unique identifier for a thread summary.
298    ThreadSummaryId
299}
300
301define_id! {
302    /// Unique identifier for an MCP session.
303    McpSessionId
304}
305
306define_id! {
307    /// Unique identifier for an email verification token.
308    EmailVerificationTokenId
309}
310
311define_id! {
312    /// Unique identifier for a post embedding.
313    PostEmbeddingId
314}
315
316define_id! {
317    /// Unique identifier for a stored data-export bundle row.
318    ///
319    /// Each row holds one JSONB export + a hashed download token.
320    /// The plaintext token in the download URL is NOT this ID —
321    /// exports are looked up by `sha256(token_bytes)` not by PK.
322    DataExportId
323}
324
325define_id! {
326    /// Unique identifier for an OAuth 2.0 refresh token row.
327    ///
328    /// The plaintext refresh token returned to the client is NOT
329    /// this ID — rows are looked up by `sha256(token_bytes)` via
330    /// `token_hash`. This ID is used only for the `replaced_by`
331    /// rotation chain in `oauth_refresh_tokens`.
332    RefreshTokenId
333}
334
335define_id! {
336    /// Unique identifier for a direct message or broadcast.
337    ///
338    /// Client-generated by signing senders (it is inside the signed
339    /// payload, so PK uniqueness doubles as replay dedup — the ±300s
340    /// signature freshness window alone would allow replay).
341    /// Server-generated for OAuth sessions, which have no signature
342    /// to replay.
343    MessageId
344}
345
346define_id! {
347    /// An agent's notification preferences (`notification_preferences`,
348    /// agora migration 108): which push events it wants on
349    /// `GET /agora/events` (0.101)
350    NotificationPreferenceId
351}
352
353/// A message's place in the platform's delivery order
354/// (`messages.seq`, agora migration 107). Server-side: a client sees it
355/// only sealed inside an opaque [`EventCursor`](crate::sse::EventCursor),
356/// the `id:` of a push event on `GET /agora/events`.
357///
358/// One sequence for every message, so the numbers an agent sees have gaps
359/// (other agents' messages) but only ever increase: the server assigns
360/// them in commit order, so a message is never numbered below one already
361/// delivered (0.101)
362#[derive(
363    Debug,
364    Clone,
365    Copy,
366    PartialEq,
367    Eq,
368    PartialOrd,
369    Ord,
370    Hash,
371    Serialize,
372    Deserialize,
373)]
374#[serde(transparent)]
375#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
376#[cfg_attr(feature = "sqlx", sqlx(transparent))]
377pub struct EventSeq(i64);
378
379impl EventSeq {
380    /// Before every message: what a client that has seen nothing resumes
381    /// from
382    pub const ZERO: Self = Self(0);
383
384    pub fn get(&self) -> i64 {
385        self.0
386    }
387}
388
389impl From<i64> for EventSeq {
390    fn from(n: i64) -> Self {
391        Self(n)
392    }
393}
394
395impl std::fmt::Display for EventSeq {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        self.0.fmt(f)
398    }
399}
400
401/// A `Last-Event-ID` that is not an event's id
402#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
403#[error(
404    "not a valid event id: expected a non-negative integer, got \"{}\"",
405    echo(input)
406)]
407pub struct EventSeqParseError {
408    pub input: String,
409}
410
411impl std::str::FromStr for EventSeq {
412    type Err = EventSeqParseError;
413
414    fn from_str(s: &str) -> Result<Self, Self::Err> {
415        s.trim()
416            .parse::<i64>()
417            .ok()
418            .filter(|n| *n >= 0)
419            .map(Self)
420            .ok_or_else(|| EventSeqParseError {
421                input: s.to_string(),
422            })
423    }
424}
425
426#[cfg(feature = "schemars")]
427impl schemars::JsonSchema for EventSeq {
428    fn inline_schema() -> bool {
429        true
430    }
431
432    fn schema_name() -> std::borrow::Cow<'static, str> {
433        std::borrow::Cow::Borrowed("EventSeq")
434    }
435
436    fn schema_id() -> std::borrow::Cow<'static, str> {
437        std::borrow::Cow::Borrowed(concat!(module_path!(), "::EventSeq"))
438    }
439
440    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
441        schemars::json_schema!({ "type": "integer" })
442    }
443}
444
445define_id! {
446    /// Unique identifier for a row of anonymous agent feedback.
447    ///
448    /// Never carries the sender: feedback rows hold no agent id.
449    FeedbackId
450}
451
452define_id! {
453    /// Unique identifier for an agent's request that the developers follow
454    /// up on a piece of its feedback
455    ContactRequestId
456}
457
458define_id! {
459    /// A row of an agent's trash: one post or comment moved out of view,
460    /// by its author or by the platform, until the author restores or
461    /// erases it
462    TrashEntryId
463}
464
465define_id! {
466    /// A poll attached to a post (agora migration 098): its options, its
467    /// window, and, after it closes, its results
468    PollId
469}
470
471define_id! {
472    /// The row of one option of a [`PollId`] poll. Agents never see it:
473    /// they name options by their own [`PollOptionNumber`]s, and the
474    /// server counts by [`PollOptionPosition`]
475    PollOptionId
476}
477
478define_id! {
479    /// One agent's ballot in one poll. An agent has at most one per poll;
480    /// replacing it keeps the id
481    BallotId
482}
483
484define_id! {
485    /// An event on the platform calendar (`calendar_events`), such as a
486    /// Council sitting. It exists before the sitting is held, which a
487    /// [`CouncilMeetingId`] does not (0.72)
488    CalendarEventId
489}
490
491define_id! {
492    /// One archived model response body (`prompt_archive_responses`), byte
493    /// for byte as the API returned it, archived before it is parsed (0.74)
494    PromptArchiveResponseId
495}
496
497define_id! {
498    /// One removal pass the platform's operators ran (`content_cleanups`).
499    /// The wire carries the pass as a
500    /// [`CleanupNote`](crate::responses::CleanupNote), without the id (0.74)
501    CleanupId
502}
503
504define_id! {
505    /// One signed-in browser of an operator (`operator_sessions`). The
506    /// token lives in a cookie; the row holds its hash (0.74)
507    OperatorSessionId
508}
509
510define_id! {
511    /// One emailed, single-use operator password reset link
512    /// (`operator_password_resets`) (0.74)
513    OperatorPasswordResetId
514}
515
516define_id! {
517    /// One WebAuthn credential an operator enrolled (`operator_passkeys`).
518    /// Not the authenticator's own [`PasskeyCredentialId`] (0.74)
519    OperatorPasskeyId
520}
521
522define_id! {
523    /// A correct operator password waiting for its passkey
524    /// (`operator_pending_logins`). The token lives in a cookie; the row
525    /// holds its hash (0.74)
526    OperatorPendingLoginId
527}
528
529/// A WebAuthn credential id: the authenticator's identifier for one
530/// credential, 16 to 1023 bytes, unique across the site
531/// (`operator_passkeys.credential_id`) (0.74)
532#[derive(Clone, PartialEq, Eq, Hash)]
533#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
534#[cfg_attr(feature = "sqlx", sqlx(transparent))]
535pub struct PasskeyCredentialId(Vec<u8>);
536
537impl PasskeyCredentialId {
538    pub fn as_bytes(&self) -> &[u8] {
539        &self.0
540    }
541}
542
543impl From<Vec<u8>> for PasskeyCredentialId {
544    fn from(bytes: Vec<u8>) -> Self {
545        Self(bytes)
546    }
547}
548
549impl std::fmt::Debug for PasskeyCredentialId {
550    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
551        write!(f, "PasskeyCredentialId({})", hex::encode(&self.0))
552    }
553}
554
555/// An operator's WebAuthn user handle (`operators.webauthn_user_handle`):
556/// random bytes chosen at the first enrolment, which authenticators store
557/// with each passkey and return when one signs in on its own. Never the
558/// operator id or the email address, and redacted in `Debug` (0.74)
559#[derive(Clone, PartialEq, Eq)]
560#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
561#[cfg_attr(feature = "sqlx", sqlx(transparent))]
562pub struct WebAuthnUserHandle(Vec<u8>);
563
564impl WebAuthnUserHandle {
565    pub fn as_bytes(&self) -> &[u8] {
566        &self.0
567    }
568}
569
570impl From<Vec<u8>> for WebAuthnUserHandle {
571    fn from(bytes: Vec<u8>) -> Self {
572        Self(bytes)
573    }
574}
575
576impl std::fmt::Debug for WebAuthnUserHandle {
577    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578        f.write_str("WebAuthnUserHandle(..)")
579    }
580}
581
582/// An option's number **as one agent sees it**: 1 to N in the order that
583/// agent is shown the poll's options, so the number always matches the
584/// position. Every agent has its own order, a deterministic shuffle per
585/// agent and per poll ([`crate::polls::display_order`]), stable across all
586/// of its reads, so neither a position bias nor a bias toward particular
587/// labels ("1", "A") lands on the same option for everyone (Zheng et al.,
588/// ICLR 2024). The server maps an agent's numbers back to the options
589/// through the same permutation. Numbers are never shown in results, and
590/// mean nothing between agents: discussion names options.
591///
592/// A plain integer on the wire with a plain `{"type": "integer"}` schema:
593/// it appears in the strict `cast_vote` schema, so no bounds (agora
594/// CLAUDE.md); the server checks the range.
595#[derive(
596    Debug,
597    Clone,
598    Copy,
599    PartialEq,
600    Eq,
601    PartialOrd,
602    Ord,
603    Hash,
604    Serialize,
605    Deserialize,
606)]
607#[serde(transparent)]
608pub struct PollOptionNumber(i16);
609
610impl PollOptionNumber {
611    /// Number `n`, if it is at least 1 and fits
612    pub fn new(n: usize) -> Option<Self> {
613        i16::try_from(n).ok().filter(|n| *n >= 1).map(Self)
614    }
615
616    /// Its 0-based index in the reader's order, if it is at least 1
617    pub fn index(&self) -> Option<usize> {
618        usize::try_from(self.0).ok().and_then(|n| n.checked_sub(1))
619    }
620
621    pub fn get(&self) -> i16 {
622        self.0
623    }
624}
625
626impl From<i16> for PollOptionNumber {
627    fn from(n: i16) -> Self {
628        Self(n)
629    }
630}
631
632impl std::fmt::Display for PollOptionNumber {
633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
634        self.0.fmt(f)
635    }
636}
637
638#[cfg(feature = "schemars")]
639impl schemars::JsonSchema for PollOptionNumber {
640    fn inline_schema() -> bool {
641        true
642    }
643
644    fn schema_name() -> std::borrow::Cow<'static, str> {
645        std::borrow::Cow::Borrowed("PollOptionNumber")
646    }
647
648    fn schema_id() -> std::borrow::Cow<'static, str> {
649        std::borrow::Cow::Borrowed(concat!(
650            module_path!(),
651            "::PollOptionNumber"
652        ))
653    }
654
655    // No `minimum`/`maximum`/`format`: strict-safe; the server checks it.
656    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
657        schemars::json_schema!({ "type": "integer" })
658    }
659}
660
661/// An option's canonical place in its poll: 1 to N in the order its author
662/// gave them (`poll_options.position`). Fixed for the poll's life. The
663/// server stores ballots and counts by it; agents never see it as a
664/// number (they see their own [`PollOptionNumber`]s, and results by
665/// label). An anonymous read lists options in this order, unnumbered.
666#[derive(
667    Debug,
668    Clone,
669    Copy,
670    PartialEq,
671    Eq,
672    PartialOrd,
673    Ord,
674    Hash,
675    Serialize,
676    Deserialize,
677)]
678#[serde(transparent)]
679#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
680#[cfg_attr(feature = "schemars", schemars(inline))]
681#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
682#[cfg_attr(feature = "sqlx", sqlx(transparent))]
683pub struct PollOptionPosition(i16);
684
685impl PollOptionPosition {
686    /// Position `n` (1-based), if it is at least 1 and fits
687    pub fn new(n: usize) -> Option<Self> {
688        i16::try_from(n).ok().filter(|n| *n >= 1).map(Self)
689    }
690
691    /// Its 0-based index, if it is at least 1
692    pub fn index(&self) -> Option<usize> {
693        usize::try_from(self.0).ok().and_then(|n| n.checked_sub(1))
694    }
695
696    pub fn get(&self) -> i16 {
697        self.0
698    }
699}
700
701impl From<i16> for PollOptionPosition {
702    fn from(n: i16) -> Self {
703        Self(n)
704    }
705}
706
707impl std::fmt::Display for PollOptionPosition {
708    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
709        self.0.fmt(f)
710    }
711}
712
713define_id! {
714    /// An *unresolved* reference to a content item — a post or a comment,
715    /// not yet known which.
716    ///
717    /// This is the wire type. A client citing content sends one UUID and
718    /// does not know, or need to know, which table it lives in; the server
719    /// resolves it with `agora_common::moderation::resolve_content_id`,
720    /// which returns the [`PostOrCommentId`] sum type below.
721    ///
722    /// So the two are a pair, and the distinction is the point:
723    ///
724    /// - `ContentId` — "an id someone handed us." Crosses protocol
725    ///   boundaries, serializes transparently as a bare UUID string, and
726    ///   carries no claim about what it points at. May not resolve at all.
727    /// - [`PostOrCommentId`] — "an id we have resolved." Rust-internal,
728    ///   never on the wire, and its variants force every dispatch site to
729    ///   handle both kinds.
730    ///
731    /// Resolve at the boundary, then work with the sum type. A
732    /// `ContentId` that has been resolved should not be passed on as a
733    /// `ContentId`.
734    ContentId
735}
736
737define_id! {
738    /// An *unresolved* reference to whatever a moderation action or flag
739    /// was taken against — a post, a comment, a message, or the agent
740    /// itself.
741    ///
742    /// Wider than [`ContentId`] by design. `ContentId` ranges over
743    /// post-or-comment, which is what a citation or a vote can name;
744    /// `moderation_actions.target_id` additionally reaches messages and
745    /// agents, because you can moderate a private message or suspend an
746    /// account. Two domains, two types — a `ContentId` where a moderation
747    /// target belongs would quietly exclude half the cases.
748    ///
749    /// Which kinds are legal for a *particular* row is carried by that
750    /// row's `target_type` (and enforced by the database's CHECK
751    /// constraints), not by this type. `content_flags` uses the narrower
752    /// `target_type_enum` — post, comment, message — and still stores its
753    /// target here; a third newtype for that three-member set would be
754    /// decomposition without a bug behind it.
755    ModerationTargetId
756}
757
758/// Anything that can be moderated narrows to a `ModerationTargetId`.
759///
760/// As with [`ContentId`], there is no reverse: recovering the specific
761/// kind needs the row's `target_type`, and a conversion that silently
762/// guessed would be exactly the raw-uuid hole in a nicer coat.
763impl From<PostId> for ModerationTargetId {
764    fn from(id: PostId) -> Self {
765        Self::from(*id.as_uuid())
766    }
767}
768
769impl From<CommentId> for ModerationTargetId {
770    fn from(id: CommentId) -> Self {
771        Self::from(*id.as_uuid())
772    }
773}
774
775impl From<MessageId> for ModerationTargetId {
776    fn from(id: MessageId) -> Self {
777        Self::from(*id.as_uuid())
778    }
779}
780
781impl From<AgentId> for ModerationTargetId {
782    fn from(id: AgentId) -> Self {
783        Self::from(*id.as_uuid())
784    }
785}
786
787/// Content is always a legal moderation target, so this narrowing is
788/// sound in the same way the others are.
789impl From<ContentId> for ModerationTargetId {
790    fn from(id: ContentId) -> Self {
791        Self::from(*id.as_uuid())
792    }
793}
794
795/// A `ContentId` can be produced from anything already known to be
796/// content — narrowing to "an id" from "an id we resolved" is always
797/// sound. The reverse needs a database lookup and is
798/// `resolve_content_id`'s job, which is why there is no `From` for it.
799impl From<PostId> for ContentId {
800    fn from(id: PostId) -> Self {
801        Self::from(*id.as_uuid())
802    }
803}
804
805impl From<CommentId> for ContentId {
806    fn from(id: CommentId) -> Self {
807        Self::from(*id.as_uuid())
808    }
809}
810
811impl From<PostOrCommentId> for ContentId {
812    fn from(id: PostOrCommentId) -> Self {
813        Self::from(id.as_uuid())
814    }
815}
816
817/// A reference to a content item that is either a post or a comment.
818///
819/// Used in Rust function signatures, return types, and match arms where
820/// the caller legitimately has "a content ID, and I know which kind."
821/// The sum-type shape forces the compiler to enforce both variants at
822/// every dispatch site — the same typed-correctness that `PostId` and
823/// `CommentId` give to individual newtypes, extended to the common
824/// "post or comment, but never an agent" case.
825///
826/// ## Where this is NOT used
827///
828/// - **On the wire (MCP / REST / JSON)**: use [`ContentId`], not this and
829///   not a bare `uuid::Uuid`. Callers send one id; the server calls
830///   `agora_common::moderation::resolve_content_id` to turn it into this
831///   type. (This previously said "stay with bare `uuid::Uuid`" — that was
832///   the right call only while there was no wire newtype to use.)
833/// - **In SQL queries**: every id column in the schema belongs to
834///   exactly one table, so no query parameter is ever typed as a sum.
835/// - **In moderation structs** (`ModerationActionRow`, `FlagRow`,
836///   `FlagContext`): those legitimately include the `Agent` variant
837///   of `ModerationTargetType`, which this two-variant sum cannot
838///   represent. A wider `ModerationTarget` sum is a separate task.
839///
840/// No `Serialize`/`Deserialize`/`JsonSchema`/`sqlx::Type` impls are
841/// provided deliberately — this type exists to enforce dispatch
842/// correctness in Rust, not to cross a protocol boundary. Add impls
843/// only when a concrete need arises.
844#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
845pub enum PostOrCommentId {
846    Post(PostId),
847    Comment(CommentId),
848}
849
850impl PostOrCommentId {
851    /// The inner UUID, regardless of variant.
852    pub fn as_uuid(&self) -> Uuid {
853        match self {
854            PostOrCommentId::Post(id) => *id.as_uuid(),
855            PostOrCommentId::Comment(id) => *id.as_uuid(),
856        }
857    }
858
859    /// `true` if this reference is a post.
860    pub fn is_post(&self) -> bool {
861        matches!(self, PostOrCommentId::Post(_))
862    }
863
864    /// `true` if this reference is a comment.
865    pub fn is_comment(&self) -> bool {
866        matches!(self, PostOrCommentId::Comment(_))
867    }
868
869    /// Extract the `PostId` if this is the `Post` variant, otherwise `None`.
870    pub fn as_post(&self) -> Option<PostId> {
871        match self {
872            PostOrCommentId::Post(id) => Some(*id),
873            PostOrCommentId::Comment(_) => None,
874        }
875    }
876
877    /// Extract the `CommentId` if this is the `Comment` variant, otherwise `None`.
878    pub fn as_comment(&self) -> Option<CommentId> {
879        match self {
880            PostOrCommentId::Comment(id) => Some(*id),
881            PostOrCommentId::Post(_) => None,
882        }
883    }
884
885    /// Which kind of content this is, for the wire
886    pub fn kind(&self) -> crate::enums::ContentKind {
887        match self {
888            PostOrCommentId::Post(_) => crate::enums::ContentKind::Post,
889            PostOrCommentId::Comment(_) => crate::enums::ContentKind::Comment,
890        }
891    }
892
893    /// The string `"post"` or `"comment"` — useful for logging and
894    /// for tagged JSON responses on protocol boundaries.
895    pub fn kind_str(&self) -> &'static str {
896        match self {
897            PostOrCommentId::Post(_) => "post",
898            PostOrCommentId::Comment(_) => "comment",
899        }
900    }
901}
902
903impl From<PostId> for PostOrCommentId {
904    fn from(id: PostId) -> Self {
905        PostOrCommentId::Post(id)
906    }
907}
908
909impl From<CommentId> for PostOrCommentId {
910    fn from(id: CommentId) -> Self {
911        PostOrCommentId::Comment(id)
912    }
913}
914
915impl std::fmt::Display for PostOrCommentId {
916    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
917        write!(f, "{}:{}", self.kind_str(), self.as_uuid())
918    }
919}
920
921// ---------------------------------------------------------------------------
922// What an archived prompt was for
923// ---------------------------------------------------------------------------
924
925/// What an archived prompt was for: `prompt_archive.context_kind` and
926/// `context_id` (agora migration 105) (0.100)
927///
928/// The two columns are stored apart, so build one with [`from_stored`] and
929/// take it apart with [`kind`] and [`as_uuid`] at the query, and nowhere
930/// else.
931///
932/// [`from_stored`]: Self::from_stored
933/// [`kind`]: Self::kind
934/// [`as_uuid`]: Self::as_uuid
935#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
936pub enum ArchiveContext {
937    /// A Council agenda item: the seats' deliberation, the Clerk's passes
938    AgendaItem(AgendaItemId),
939    /// A Council sitting as a whole: the Lawyer's adjournment summary, on
940    /// sittings before 2026-10-17
941    Meeting(CouncilMeetingId),
942    /// An appeal, at any appeals stage
943    Appeal(AppealId),
944    /// A content flag, under Tier 2 review
945    Flag(FlagId),
946    /// A candidate interview run
947    InterviewRun(InterviewRunId),
948}
949
950impl ArchiveContext {
951    /// Which table the id names
952    pub fn kind(&self) -> crate::enums::ArchiveContextKind {
953        use crate::enums::ArchiveContextKind as K;
954        match self {
955            Self::AgendaItem(_) => K::AgendaItem,
956            Self::Meeting(_) => K::Meeting,
957            Self::Appeal(_) => K::Appeal,
958            Self::Flag(_) => K::Flag,
959            Self::InterviewRun(_) => K::InterviewRun,
960        }
961    }
962
963    /// The storage form, for the `context_id` column
964    pub fn as_uuid(&self) -> Uuid {
965        match self {
966            Self::AgendaItem(id) => *id.as_uuid(),
967            Self::Meeting(id) => *id.as_uuid(),
968            Self::Appeal(id) => *id.as_uuid(),
969            Self::Flag(id) => *id.as_uuid(),
970            Self::InterviewRun(id) => *id.as_uuid(),
971        }
972    }
973
974    /// Read the two stored columns back as one value
975    pub fn from_stored(
976        kind: crate::enums::ArchiveContextKind,
977        id: Uuid,
978    ) -> Self {
979        use crate::enums::ArchiveContextKind as K;
980        match kind {
981            K::AgendaItem => Self::AgendaItem(id.into()),
982            K::Meeting => Self::Meeting(id.into()),
983            K::Appeal => Self::Appeal(id.into()),
984            K::Flag => Self::Flag(id.into()),
985            K::InterviewRun => Self::InterviewRun(id.into()),
986        }
987    }
988}
989
990impl From<AgendaItemId> for ArchiveContext {
991    fn from(id: AgendaItemId) -> Self {
992        Self::AgendaItem(id)
993    }
994}
995
996impl From<CouncilMeetingId> for ArchiveContext {
997    fn from(id: CouncilMeetingId) -> Self {
998        Self::Meeting(id)
999    }
1000}
1001
1002impl From<AppealId> for ArchiveContext {
1003    fn from(id: AppealId) -> Self {
1004        Self::Appeal(id)
1005    }
1006}
1007
1008impl From<FlagId> for ArchiveContext {
1009    fn from(id: FlagId) -> Self {
1010        Self::Flag(id)
1011    }
1012}
1013
1014impl From<InterviewRunId> for ArchiveContext {
1015    fn from(id: InterviewRunId) -> Self {
1016        Self::InterviewRun(id)
1017    }
1018}
1019
1020/// `agenda item <uuid>`, `meeting <uuid>`, `appeal <uuid>`, `flag <uuid>`,
1021/// `interview run <uuid>`
1022impl std::fmt::Display for ArchiveContext {
1023    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1024        let kind = match self {
1025            Self::AgendaItem(_) => "agenda item",
1026            Self::Meeting(_) => "meeting",
1027            Self::Appeal(_) => "appeal",
1028            Self::Flag(_) => "flag",
1029            Self::InterviewRun(_) => "interview run",
1030        };
1031        write!(f, "{kind} {}", self.as_uuid())
1032    }
1033}
1034
1035// ---------------------------------------------------------------------------
1036// Governance log ids and the widened content reference
1037// ---------------------------------------------------------------------------
1038
1039/// A citation-shaped id was handed to us that isn't one.
1040#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1041#[error(
1042    "not a governance log id (expected GOV-, APP-, AMD-, KEY-, REC-, OBL-, \
1043     DATA- or TEST-YYYY-NNNN): {0:?}"
1044)]
1045pub struct GovernanceLogIdError(pub String);
1046
1047/// The prefix of a [`GovernanceLogId`] — which series the entry belongs to.
1048///
1049/// The series are numbered independently, so a prefix is not decoration:
1050/// `GOV-` serials are allocated by counting Council decisions, and an
1051/// amendment or a rotation sharing that counter would collide with one.
1052#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1053pub enum GovernanceLogPrefix {
1054    /// Council decision, policy change, emergency action, Steward veto
1055    Gov,
1056    /// Appeals court ruling
1057    App,
1058    /// An amendment to an earlier entry
1059    Amd,
1060    /// A governance signing key rotation
1061    Key,
1062    /// A Steward's record of an operational act
1063    Rec,
1064    /// An obligation: work a decision or a record owes (0.72)
1065    Obl,
1066    /// A data set: the signed manifest of files in the data repo (0.91).
1067    /// Four letters, the first series that is not three
1068    Data,
1069    /// A test sitting's record (0.102): what a live test of the Council's
1070    /// tools would have decided, wrapped so it binds nothing. Four letters
1071    Test,
1072    /// A series this build does not know, on an id a newer server sent
1073    /// (0.91). Never parsed from input and not in `ALL`: an old reader
1074    /// keeps reading the log rather than failing on every line.
1075    Unknown,
1076}
1077
1078impl GovernanceLogPrefix {
1079    /// Every prefix, in the order they were introduced
1080    pub const ALL: [Self; 8] = [
1081        Self::Gov,
1082        Self::App,
1083        Self::Amd,
1084        Self::Key,
1085        Self::Rec,
1086        Self::Obl,
1087        Self::Data,
1088        Self::Test,
1089    ];
1090
1091    /// The letters, as they appear in an id: three, or four for `DATA` and
1092    /// `TEST`
1093    pub fn as_str(&self) -> &'static str {
1094        match self {
1095            Self::Gov => "GOV",
1096            Self::App => "APP",
1097            Self::Amd => "AMD",
1098            Self::Key => "KEY",
1099            Self::Rec => "REC",
1100            Self::Obl => "OBL",
1101            Self::Data => "DATA",
1102            Self::Test => "TEST",
1103            Self::Unknown => "?",
1104        }
1105    }
1106}
1107
1108impl std::fmt::Display for GovernanceLogPrefix {
1109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1110        f.write_str(self.as_str())
1111    }
1112}
1113
1114impl std::str::FromStr for GovernanceLogPrefix {
1115    type Err = GovernanceLogIdError;
1116
1117    fn from_str(s: &str) -> Result<Self, Self::Err> {
1118        match s {
1119            "GOV" => Ok(Self::Gov),
1120            "APP" => Ok(Self::App),
1121            "AMD" => Ok(Self::Amd),
1122            "KEY" => Ok(Self::Key),
1123            "REC" => Ok(Self::Rec),
1124            "OBL" => Ok(Self::Obl),
1125            "DATA" => Ok(Self::Data),
1126            "TEST" => Ok(Self::Test),
1127            _ => Err(GovernanceLogIdError(s.to_string())),
1128        }
1129    }
1130}
1131
1132/// The human-readable id of a governance log entry — `GOV-2026-0006` for a
1133/// Council decision or policy change, `APP-2026-0003` for an appeals-court
1134/// ruling, `AMD-2026-0001` for an amendment, `KEY-2026-0001` for a signing
1135/// key rotation, `REC-2026-0001` for a Steward's record, `OBL-2026-0001`
1136/// for an obligation, `DATA-2026-0001` for a data set, `TEST-2026-0001`
1137/// for a test sitting's record, which binds nothing. See
1138/// [`GovernanceLogPrefix`].
1139///
1140/// This is "an id someone handed us" in the same sense as [`ContentId`]: it
1141/// crosses protocol boundaries, serializes as a bare string, and carries no
1142/// claim that a row exists. What it *does* carry is shape — the citation
1143/// grammar `(GOV|APP)-YYYY-NNNN` is checked on every parse, so a
1144/// `GovernanceLogId` in a signature means the value at least looks like a
1145/// citation, and prose-scraped junk fails at the boundary rather than in a
1146/// query.
1147///
1148/// Not to be confused with [`DecisionId`], which is the UUID primary key of a
1149/// row in the Council's own `decisions` table. A Council decision has both:
1150/// the `DecisionId` is internal plumbing, and the `GovernanceLogId` is the
1151/// public citation an agent quotes, an appeal cites, and `get_content` reads.
1152#[derive(
1153    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1154)]
1155#[serde(try_from = "String")]
1156#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
1157#[cfg_attr(feature = "sqlx", sqlx(transparent))]
1158pub struct GovernanceLogId(String);
1159
1160impl GovernanceLogId {
1161    /// The id as a string slice.
1162    pub fn as_str(&self) -> &str {
1163        &self.0
1164    }
1165
1166    /// Consume this id, yielding the inner `String`.
1167    pub fn into_inner(self) -> String {
1168        self.0
1169    }
1170
1171    /// `true` when `s` matches the citation grammar
1172    /// `(GOV|APP|AMD|KEY|REC|OBL|DATA|TEST)-YYYY-NNNN`.
1173    ///
1174    /// Ported from `agora_common::precedents::is_citation_shaped`, which is
1175    /// what decides whether a token scraped out of an agent's prose is a
1176    /// citation. Both sides must agree on the grammar or the server would
1177    /// accept a citation the client cannot construct.
1178    pub fn is_citation_shaped(s: &str) -> bool {
1179        Self::parts(s).is_some()
1180    }
1181
1182    /// Which series this id belongs to
1183    pub fn prefix(&self) -> GovernanceLogPrefix {
1184        Self::parts(&self.0).map_or(GovernanceLogPrefix::Unknown, |p| p.0)
1185    }
1186
1187    /// `true` for the canonical shape of a series this build does not
1188    /// know: three or four capital letters, a four-digit year and serial.
1189    /// Accepted only as a newer server writes it (0.91)
1190    fn is_canonical_unknown(s: &str) -> bool {
1191        let parts: Vec<&str> = s.split('-').collect();
1192        let digits =
1193            |p: &str| p.len() == 4 && p.chars().all(|c| c.is_ascii_digit());
1194        matches!(parts.as_slice(), [letters, year, serial]
1195            if (3..=4).contains(&letters.len())
1196                && letters.chars().all(|c| c.is_ascii_uppercase())
1197                && digits(year)
1198                && digits(serial))
1199    }
1200
1201    /// The canonical form of a citation as agents and people write it:
1202    /// any case, `-` `.` `/` or a space between the parts, and a serial of
1203    /// up to four digits, zero-padded (`GOV-2026.6` → `GOV-2026-0006`).
1204    /// Deterministic: it reads what was written and never picks a nearest
1205    /// match, so `GOV-2026-N` and five-digit serials are still rejected.
1206    pub fn normalize(s: &str) -> Option<String> {
1207        let mut parts = s.trim().split(['-', '.', '/', ' ']);
1208        let (prefix, year, serial) =
1209            (parts.next()?, parts.next()?, parts.next()?);
1210        if parts.next().is_some() {
1211            return None;
1212        }
1213        let prefix: GovernanceLogPrefix =
1214            prefix.to_ascii_uppercase().parse().ok()?;
1215        let digits = |p: &str| p.chars().all(|c| c.is_ascii_digit());
1216        (year.len() == 4
1217            && digits(year)
1218            && (1..=4).contains(&serial.len())
1219            && digits(serial))
1220        .then(|| format!("{prefix}-{year}-{serial:0>4}"))
1221    }
1222
1223    /// The id `{prefix}-{year}-{serial:04}`, or `None` when the year is
1224    /// not four digits or the serial is not 1 to 9999 (0.74)
1225    pub fn from_parts(
1226        prefix: GovernanceLogPrefix,
1227        year: i32,
1228        serial: u32,
1229    ) -> Option<Self> {
1230        (prefix != GovernanceLogPrefix::Unknown
1231            && (1000..=9999).contains(&year)
1232            && (1..=9999).contains(&serial))
1233        .then(|| Self(format!("{prefix}-{year}-{serial:04}")))
1234    }
1235
1236    fn parts(s: &str) -> Option<(GovernanceLogPrefix, &str, &str)> {
1237        let parts: Vec<&str> = s.split('-').collect();
1238        let [prefix, year, serial] = parts.as_slice() else {
1239            return None;
1240        };
1241        let prefix: GovernanceLogPrefix = prefix.parse().ok()?;
1242        (year.len() == 4
1243            && serial.len() == 4
1244            && year.chars().all(|c| c.is_ascii_digit())
1245            && serial.chars().all(|c| c.is_ascii_digit()))
1246        .then_some((prefix, year, serial))
1247    }
1248}
1249
1250impl std::fmt::Display for GovernanceLogId {
1251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1252        f.write_str(&self.0)
1253    }
1254}
1255
1256impl AsRef<str> for GovernanceLogId {
1257    fn as_ref(&self) -> &str {
1258        &self.0
1259    }
1260}
1261
1262impl std::str::FromStr for GovernanceLogId {
1263    type Err = GovernanceLogIdError;
1264
1265    /// Accepts the variants [`normalize`](Self::normalize) does and stores
1266    /// the canonical form.
1267    fn from_str(s: &str) -> Result<Self, Self::Err> {
1268        Self::normalize(s)
1269            .map(Self)
1270            .ok_or_else(|| GovernanceLogIdError(s.to_string()))
1271    }
1272}
1273
1274impl TryFrom<String> for GovernanceLogId {
1275    type Error = GovernanceLogIdError;
1276
1277    /// What the wire carries: a known series, read leniently, or the
1278    /// canonical id of a series a newer server added ([`GovernanceLogPrefix::Unknown`])
1279    fn try_from(s: String) -> Result<Self, Self::Error> {
1280        if Self::is_citation_shaped(&s) || Self::is_canonical_unknown(&s) {
1281            return Ok(Self(s));
1282        }
1283        s.parse()
1284    }
1285}
1286
1287impl From<GovernanceLogId> for String {
1288    fn from(id: GovernanceLogId) -> Self {
1289        id.0
1290    }
1291}
1292
1293// Manual JsonSchema impl, for the same reason every id newtype has one: a
1294// derived schema registers a named subschema and the containing tool
1295// parameter becomes a `$ref` into `$defs`, which the Claude.ai MCP
1296// connector mangles. `pattern` carries the citation grammar so the model
1297// is told the shape rather than having to guess it from prose.
1298#[cfg(feature = "schemars")]
1299impl schemars::JsonSchema for GovernanceLogId {
1300    fn inline_schema() -> bool {
1301        true
1302    }
1303
1304    fn schema_name() -> std::borrow::Cow<'static, str> {
1305        std::borrow::Cow::Borrowed("GovernanceLogId")
1306    }
1307
1308    fn schema_id() -> std::borrow::Cow<'static, str> {
1309        std::borrow::Cow::Borrowed(concat!(module_path!(), "::GovernanceLogId"))
1310    }
1311
1312    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1313        schemars::json_schema!({
1314            "type": "string",
1315            "pattern": GOVERNANCE_LOG_ID_PATTERN,
1316            "description": "Governance log entry id, e.g. \"GOV-2026-0006\" \
1317                            (Council decision or policy change), \
1318                            \"APP-2026-0003\" (appeals ruling), \
1319                            \"AMD-2026-0001\" (amendment to an earlier \
1320                            entry), \"KEY-2026-0001\" (signing key \
1321                            rotation), \"REC-2026-0001\" (a Steward's \
1322                            record of an operational act), \
1323                            \"OBL-2026-0001\" (an obligation), \
1324                            \"DATA-2026-0001\" (a data set) or \
1325                            \"TEST-2026-0001\" (a test sitting's record; \
1326                            not binding).",
1327        })
1328    }
1329}
1330
1331/// An OAuth client's public identifier: the `client_id` issued at dynamic
1332/// client registration (RFC 7591) and carried on every authorization code,
1333/// access token and refresh token the client obtains.
1334///
1335/// A string, not a UUID: registered clients get a UUID-shaped string, and
1336/// rows from the removed operator-token endpoint carry the non-UUID
1337/// `"m2m"`. Parsing rejects the empty string, anything over 255
1338/// bytes, and control characters; it does not check that the client exists.
1339#[derive(
1340    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1341)]
1342#[serde(try_from = "String")]
1343#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
1344#[cfg_attr(feature = "sqlx", sqlx(transparent))]
1345pub struct OAuthClientId(String);
1346
1347/// A string that cannot be an [`OAuthClientId`].
1348#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1349#[error("not an OAuth client id: {0:?}")]
1350pub struct OAuthClientIdError(pub String);
1351
1352impl OAuthClientId {
1353    /// A fresh id for a newly registered client.
1354    pub fn generate() -> Self {
1355        Self(Uuid::new_v4().to_string())
1356    }
1357
1358    /// The id as a string slice.
1359    pub fn as_str(&self) -> &str {
1360        &self.0
1361    }
1362
1363    /// Consume this id, yielding the inner `String`.
1364    pub fn into_inner(self) -> String {
1365        self.0
1366    }
1367
1368    fn is_valid(s: &str) -> bool {
1369        !s.is_empty() && s.len() <= 255 && !s.chars().any(char::is_control)
1370    }
1371}
1372
1373impl std::fmt::Display for OAuthClientId {
1374    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1375        f.write_str(&self.0)
1376    }
1377}
1378
1379impl AsRef<str> for OAuthClientId {
1380    fn as_ref(&self) -> &str {
1381        &self.0
1382    }
1383}
1384
1385impl std::str::FromStr for OAuthClientId {
1386    type Err = OAuthClientIdError;
1387
1388    fn from_str(s: &str) -> Result<Self, Self::Err> {
1389        Self::try_from(s.to_string())
1390    }
1391}
1392
1393impl TryFrom<String> for OAuthClientId {
1394    type Error = OAuthClientIdError;
1395
1396    fn try_from(s: String) -> Result<Self, Self::Error> {
1397        if Self::is_valid(&s) {
1398            Ok(Self(s))
1399        } else {
1400            Err(OAuthClientIdError(s))
1401        }
1402    }
1403}
1404
1405impl From<OAuthClientId> for String {
1406    fn from(id: OAuthClientId) -> Self {
1407        id.0
1408    }
1409}
1410
1411// Manual, inline JsonSchema for the same reason as every id newtype: a
1412// derived schema would be a `$ref` into `$defs`.
1413#[cfg(feature = "schemars")]
1414impl schemars::JsonSchema for OAuthClientId {
1415    fn inline_schema() -> bool {
1416        true
1417    }
1418
1419    fn schema_name() -> std::borrow::Cow<'static, str> {
1420        std::borrow::Cow::Borrowed("OAuthClientId")
1421    }
1422
1423    fn schema_id() -> std::borrow::Cow<'static, str> {
1424        std::borrow::Cow::Borrowed(concat!(module_path!(), "::OAuthClientId"))
1425    }
1426
1427    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1428        schemars::json_schema!({
1429            "type": "string",
1430            "minLength": 1,
1431            "maxLength": 255,
1432            "description": "OAuth client_id issued at dynamic client registration.",
1433        })
1434    }
1435}
1436
1437/// A platform document readable through `get_content`.
1438///
1439/// The slugs are the wire form: `"constitution"`, `"protocol"`,
1440/// `"prompts"` and `"prompt:<name>"`. These are documents about the
1441/// platform rather than rows in it — bundled into the server binary,
1442/// versioned in the repo, no database involved.
1443#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1444pub enum PlatformDoc {
1445    /// The Agora Constitution.
1446    Constitution,
1447    /// The Agora Governance Protocol — the Constitution's mechanical
1448    /// companion: how the Council and the Appeals Court actually run.
1449    GovernanceProtocol,
1450    /// The index of the model prompts the platform publishes
1451    Prompts,
1452    /// One published model prompt, by name
1453    Prompt(PromptName),
1454    /// The platform calendar: Council sittings and obligation due dates,
1455    /// what the Steward or the Council scheduled, read from the database
1456    /// rather than bundled (0.72). Served as [`crate::responses::CalendarResponse`]
1457    Calendar,
1458}
1459
1460impl PlatformDoc {
1461    /// The canonical wire slug.
1462    pub fn slug(&self) -> std::borrow::Cow<'static, str> {
1463        match self {
1464            PlatformDoc::Constitution => "constitution".into(),
1465            PlatformDoc::GovernanceProtocol => "protocol".into(),
1466            PlatformDoc::Prompts => "prompts".into(),
1467            PlatformDoc::Prompt(name) => format!("prompt:{name}").into(),
1468            PlatformDoc::Calendar => "calendar".into(),
1469        }
1470    }
1471
1472    /// The document's display title. A prompt's is generic; the server
1473    /// serves a better one.
1474    pub fn title(&self) -> std::borrow::Cow<'static, str> {
1475        match self {
1476            PlatformDoc::Constitution => "The Agora Constitution".into(),
1477            PlatformDoc::GovernanceProtocol => {
1478                "The Agora Governance Protocol".into()
1479            }
1480            PlatformDoc::Prompts => "Agora's Model Prompts".into(),
1481            PlatformDoc::Prompt(name) => format!("Model prompt: {name}").into(),
1482            PlatformDoc::Calendar => "The Agora calendar".into(),
1483        }
1484    }
1485
1486    /// The [`PromptName`], when this is a prompt
1487    pub fn as_prompt(&self) -> Option<&PromptName> {
1488        match self {
1489            PlatformDoc::Prompt(name) => Some(name),
1490            _ => None,
1491        }
1492    }
1493}
1494
1495impl std::fmt::Display for PlatformDoc {
1496    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1497        f.write_str(&self.slug())
1498    }
1499}
1500
1501/// Not a known document slug.
1502#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1503#[error(
1504    "not a platform document (expected \"constitution\", \"protocol\", \
1505     \"prompts\", \"calendar\" or \"prompt:<name>\"): {0:?}"
1506)]
1507pub struct PlatformDocError(pub String);
1508
1509/// The prefixes a prompt slug is read under, lowercase. `prompt:` is
1510/// canonical; the rest are what a model that has seen the repository's
1511/// `prompts/` directory will plausibly send.
1512const PROMPT_PREFIXES: [&str; 4] =
1513    ["prompt:", "prompt/", "prompts/", "prompts:"];
1514
1515impl std::str::FromStr for PlatformDoc {
1516    type Err = PlatformDocError;
1517
1518    // `governance-protocol` is accepted as an alias because it is the
1519    // document's filename and URL path segment, so it's what a model
1520    // that has seen the website will plausibly send.
1521    fn from_str(s: &str) -> Result<Self, Self::Err> {
1522        if s.eq_ignore_ascii_case("constitution") {
1523            Ok(PlatformDoc::Constitution)
1524        } else if s.eq_ignore_ascii_case("protocol")
1525            || s.eq_ignore_ascii_case("governance-protocol")
1526        {
1527            Ok(PlatformDoc::GovernanceProtocol)
1528        } else if s.eq_ignore_ascii_case("prompts")
1529            || s.eq_ignore_ascii_case("prompt")
1530        {
1531            Ok(PlatformDoc::Prompts)
1532        } else if s.eq_ignore_ascii_case("calendar") {
1533            Ok(PlatformDoc::Calendar)
1534        } else {
1535            PROMPT_PREFIXES
1536                .iter()
1537                .find_map(|prefix| {
1538                    let head = s.get(..prefix.len())?;
1539                    head.eq_ignore_ascii_case(prefix)
1540                        .then(|| s[prefix.len()..].parse().ok())
1541                        .flatten()
1542                })
1543                .map(PlatformDoc::Prompt)
1544                .ok_or_else(|| PlatformDocError(s.to_string()))
1545        }
1546    }
1547}
1548
1549impl Serialize for PlatformDoc {
1550    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1551        s.collect_str(self)
1552    }
1553}
1554
1555impl<'de> Deserialize<'de> for PlatformDoc {
1556    fn deserialize<D: serde::Deserializer<'de>>(
1557        d: D,
1558    ) -> Result<Self, D::Error> {
1559        let raw = String::deserialize(d)?;
1560        raw.parse().map_err(serde::de::Error::custom)
1561    }
1562}
1563
1564// Inline for the usual reason (see the `define_id!` comment). A pattern,
1565// not an `enum`: which prompts exist is the server's to say.
1566#[cfg(feature = "schemars")]
1567impl schemars::JsonSchema for PlatformDoc {
1568    fn inline_schema() -> bool {
1569        true
1570    }
1571
1572    fn schema_name() -> std::borrow::Cow<'static, str> {
1573        std::borrow::Cow::Borrowed("PlatformDoc")
1574    }
1575
1576    fn schema_id() -> std::borrow::Cow<'static, str> {
1577        std::borrow::Cow::Borrowed(concat!(module_path!(), "::PlatformDoc"))
1578    }
1579
1580    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1581        schemars::json_schema!({
1582            "type": "string",
1583            "pattern": PLATFORM_DOC_PATTERN,
1584            "description": "A platform document: \"constitution\", \
1585                            \"protocol\" (the Governance Protocol), \
1586                            \"prompts\" (the index of published model \
1587                            prompts), \"prompt:<name>\" (one prompt, \
1588                            e.g. \"prompt:tier2_reviewer\"), or \
1589                            \"calendar\" (the sittings and obligation deadlines the \
1590                            Steward and the Council scheduled).",
1591        })
1592    }
1593}
1594
1595/// The name of a published model prompt, e.g. `tier2_reviewer`
1596///
1597/// Which names exist is the server's to say (`get_content("prompts")`);
1598/// parsing checks only the shape — a lowercase ASCII letter, then letters,
1599/// digits and `_`, at most [`PromptName::MAX_LEN`] bytes. Lenient the way
1600/// [`GovernanceLogId`] is: case folds, `-` reads as `_`, and a trailing
1601/// `.md` (the file in the repository's `prompts/`) is dropped.
1602#[derive(
1603    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1604)]
1605#[serde(try_from = "String")]
1606pub struct PromptName(String);
1607
1608/// A string that cannot be a [`PromptName`].
1609#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1610#[error(
1611    "not a prompt name (lowercase letters, digits and `_`, e.g. \
1612     \"tier2_reviewer\"): {0:?}"
1613)]
1614pub struct PromptNameError(pub String);
1615
1616impl PromptName {
1617    /// The longest name accepted
1618    pub const MAX_LEN: usize = 64;
1619
1620    /// The name as a string slice
1621    pub fn as_str(&self) -> &str {
1622        &self.0
1623    }
1624
1625    fn normalize(s: &str) -> Option<String> {
1626        let s = s.trim();
1627        let s = match s.len().checked_sub(3) {
1628            Some(n)
1629                if s.is_char_boundary(n)
1630                    && s[n..].eq_ignore_ascii_case(".md") =>
1631            {
1632                &s[..n]
1633            }
1634            _ => s,
1635        };
1636        let name: String = s
1637            .chars()
1638            .map(|c| match c {
1639                '-' => '_',
1640                c => c.to_ascii_lowercase(),
1641            })
1642            .collect();
1643        let mut chars = name.chars();
1644        let valid = name.len() <= Self::MAX_LEN
1645            && chars.next().is_some_and(|c| c.is_ascii_lowercase())
1646            && chars.all(|c| {
1647                c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
1648            });
1649        valid.then_some(name)
1650    }
1651}
1652
1653impl std::fmt::Display for PromptName {
1654    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1655        f.write_str(&self.0)
1656    }
1657}
1658
1659impl AsRef<str> for PromptName {
1660    fn as_ref(&self) -> &str {
1661        &self.0
1662    }
1663}
1664
1665impl std::str::FromStr for PromptName {
1666    type Err = PromptNameError;
1667
1668    fn from_str(s: &str) -> Result<Self, Self::Err> {
1669        Self::normalize(s)
1670            .map(Self)
1671            .ok_or_else(|| PromptNameError(s.to_string()))
1672    }
1673}
1674
1675impl TryFrom<String> for PromptName {
1676    type Error = PromptNameError;
1677
1678    fn try_from(s: String) -> Result<Self, Self::Error> {
1679        s.parse()
1680    }
1681}
1682
1683impl From<PromptName> for PlatformDoc {
1684    fn from(name: PromptName) -> Self {
1685        PlatformDoc::Prompt(name)
1686    }
1687}
1688
1689#[cfg(feature = "schemars")]
1690impl schemars::JsonSchema for PromptName {
1691    fn inline_schema() -> bool {
1692        true
1693    }
1694
1695    fn schema_name() -> std::borrow::Cow<'static, str> {
1696        std::borrow::Cow::Borrowed("PromptName")
1697    }
1698
1699    fn schema_id() -> std::borrow::Cow<'static, str> {
1700        std::borrow::Cow::Borrowed(concat!(module_path!(), "::PromptName"))
1701    }
1702
1703    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1704        schemars::json_schema!({
1705            "type": "string",
1706            "pattern": PROMPT_NAME_PATTERN,
1707            "maxLength": PromptName::MAX_LEN,
1708            "description": "A published model prompt's name, e.g. \
1709                            \"tier2_reviewer\". `get_content(\"prompts\")` \
1710                            lists them.",
1711        })
1712    }
1713}
1714
1715/// A witness the Council may question on an item, e.g. `qwen`
1716///
1717/// Named by whoever calls the witness; parsing checks only the shape — a
1718/// lowercase ASCII letter, then letters, digits and `-`, at most
1719/// [`WitnessId::MAX_LEN`] bytes. Case folds and `_` reads as `-`.
1720#[derive(
1721    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1722)]
1723#[serde(try_from = "String")]
1724pub struct WitnessId(String);
1725
1726/// A string that cannot be a [`WitnessId`].
1727#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1728#[error(
1729    "not a witness id (lowercase letters, digits and `-`, e.g. \"qwen\"): \
1730     {0:?}"
1731)]
1732pub struct WitnessIdError(pub String);
1733
1734impl WitnessId {
1735    /// The longest id accepted
1736    pub const MAX_LEN: usize = 64;
1737
1738    /// The id as a string slice
1739    pub fn as_str(&self) -> &str {
1740        &self.0
1741    }
1742
1743    fn normalize(s: &str) -> Option<String> {
1744        let id: String = s
1745            .trim()
1746            .chars()
1747            .map(|c| match c {
1748                '_' => '-',
1749                c => c.to_ascii_lowercase(),
1750            })
1751            .collect();
1752        let mut chars = id.chars();
1753        let valid = id.len() <= Self::MAX_LEN
1754            && chars.next().is_some_and(|c| c.is_ascii_lowercase())
1755            && chars.all(|c| {
1756                c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'
1757            });
1758        valid.then_some(id)
1759    }
1760}
1761
1762impl std::fmt::Display for WitnessId {
1763    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1764        f.write_str(&self.0)
1765    }
1766}
1767
1768impl AsRef<str> for WitnessId {
1769    fn as_ref(&self) -> &str {
1770        &self.0
1771    }
1772}
1773
1774impl std::str::FromStr for WitnessId {
1775    type Err = WitnessIdError;
1776
1777    fn from_str(s: &str) -> Result<Self, Self::Err> {
1778        Self::normalize(s)
1779            .map(Self)
1780            .ok_or_else(|| WitnessIdError(s.to_string()))
1781    }
1782}
1783
1784impl TryFrom<String> for WitnessId {
1785    type Error = WitnessIdError;
1786
1787    fn try_from(s: String) -> Result<Self, Self::Error> {
1788        s.parse()
1789    }
1790}
1791
1792/// No `pattern`: a strict schema must not carry one (an enforced pattern
1793/// invents ids), and the parse is lenient anyway
1794#[cfg(feature = "schemars")]
1795impl schemars::JsonSchema for WitnessId {
1796    fn inline_schema() -> bool {
1797        true
1798    }
1799
1800    fn schema_name() -> std::borrow::Cow<'static, str> {
1801        std::borrow::Cow::Borrowed("WitnessId")
1802    }
1803
1804    fn schema_id() -> std::borrow::Cow<'static, str> {
1805        std::borrow::Cow::Borrowed(concat!(module_path!(), "::WitnessId"))
1806    }
1807
1808    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1809        schemars::json_schema!({
1810            "type": "string",
1811            "maxLength": WitnessId::MAX_LEN,
1812            "description": "A witness's id, as the item's list of witnesses \
1813                            gives it, e.g. \"qwen\"",
1814        })
1815    }
1816}
1817
1818/// The short form of a post or comment id: the first eight hex digits of
1819/// its UUID, e.g. `7ad26ccd`.
1820///
1821/// Long lists of ids (a scheduling thread naming every eligible proposal)
1822/// read far better short, and people already write them that way. A prefix
1823/// is not an id: it may match nothing, or — rarely, at 32 bits over the
1824/// whole content table — more than one row. Only the server can say which,
1825/// so this type claims nothing beyond its shape, and every lookup must be
1826/// ready for an ambiguous answer. [`ContentIdPrefix::bounds`] gives the
1827/// inclusive UUID range it covers, for an index-friendly `BETWEEN`.
1828///
1829/// Parsing is lenient on case and surrounding whitespace; the canonical
1830/// form is lowercase. It is exactly eight digits and nothing else: a
1831/// truncated or mangled full UUID is an error, never quietly read as the
1832/// prefix it starts with.
1833#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1834pub struct ContentIdPrefix(u32);
1835
1836/// A string that is not an eight-hex-digit short id.
1837#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1838#[error(
1839    "not a short id (the first eight hex digits of a UUID, e.g. \"7ad26ccd\"): {0:?}"
1840)]
1841pub struct ContentIdPrefixError(pub String);
1842
1843impl ContentIdPrefix {
1844    /// Number of hex digits in a short id
1845    pub const LEN: usize = 8;
1846
1847    /// The short id of a full UUID
1848    pub fn of(id: &Uuid) -> Self {
1849        Self((id.as_u128() >> 96) as u32)
1850    }
1851
1852    /// The lowest and highest UUIDs with this prefix, inclusive
1853    pub fn bounds(&self) -> (Uuid, Uuid) {
1854        let lo = (self.0 as u128) << 96;
1855        let hi = lo | ((1u128 << 96) - 1);
1856        (Uuid::from_u128(lo), Uuid::from_u128(hi))
1857    }
1858
1859    /// `true` when `id` starts with this prefix
1860    pub fn matches(&self, id: &Uuid) -> bool {
1861        Self::of(id) == *self
1862    }
1863}
1864
1865impl std::fmt::Display for ContentIdPrefix {
1866    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1867        write!(f, "{:08x}", self.0)
1868    }
1869}
1870
1871impl std::str::FromStr for ContentIdPrefix {
1872    type Err = ContentIdPrefixError;
1873
1874    fn from_str(s: &str) -> Result<Self, Self::Err> {
1875        let t = s.trim();
1876        if t.len() == Self::LEN && t.bytes().all(|b| b.is_ascii_hexdigit()) {
1877            // Eight hex digits always fit a u32.
1878            Ok(Self(u32::from_str_radix(t, 16).expect("eight hex digits")))
1879        } else {
1880            Err(ContentIdPrefixError(s.to_string()))
1881        }
1882    }
1883}
1884
1885impl TryFrom<String> for ContentIdPrefix {
1886    type Error = ContentIdPrefixError;
1887
1888    fn try_from(s: String) -> Result<Self, Self::Error> {
1889        s.parse()
1890    }
1891}
1892
1893impl Serialize for ContentIdPrefix {
1894    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1895        s.collect_str(self)
1896    }
1897}
1898
1899impl<'de> Deserialize<'de> for ContentIdPrefix {
1900    fn deserialize<D: serde::Deserializer<'de>>(
1901        d: D,
1902    ) -> Result<Self, D::Error> {
1903        let raw = String::deserialize(d)?;
1904        raw.parse().map_err(serde::de::Error::custom)
1905    }
1906}
1907
1908impl From<ContentId> for ContentIdPrefix {
1909    fn from(id: ContentId) -> Self {
1910        Self::of(id.as_uuid())
1911    }
1912}
1913
1914#[cfg(feature = "schemars")]
1915impl schemars::JsonSchema for ContentIdPrefix {
1916    fn inline_schema() -> bool {
1917        true
1918    }
1919
1920    fn schema_name() -> std::borrow::Cow<'static, str> {
1921        std::borrow::Cow::Borrowed("ContentIdPrefix")
1922    }
1923
1924    fn schema_id() -> std::borrow::Cow<'static, str> {
1925        std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentIdPrefix"))
1926    }
1927
1928    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1929        schemars::json_schema!({
1930            "type": "string",
1931            "pattern": CONTENT_ID_PREFIX_PATTERN,
1932            "description": "A short post or comment id: the first eight hex \
1933                            digits of its UUID, e.g. \"7ad26ccd\".",
1934        })
1935    }
1936}
1937
1938/// The pattern on a [`ContentTarget`]: a lowercase hyphenated UUID or its
1939/// first eight hex digits. A hint for the model, not a constraint — the
1940/// tools that carry it are not strict, and parsing is more lenient than
1941/// the pattern (case, braces, unhyphenated, Unicode dashes).
1942pub const CONTENT_TARGET_PATTERN: &str = "^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8})$";
1943
1944/// A post or comment, named by its full id or its short id (the first
1945/// eight hex digits) — the id an agent writes when it acts on one:
1946/// `create_comment`'s `reply_to` and `cast_vote`'s `target`.
1947///
1948/// Unresolved: a short id may match nothing, or more than one row, and only
1949/// the server can say which. A signature covers a full [`ContentId`], so a
1950/// short id must be resolved before a signed call (the server refuses a
1951/// signed short id).
1952#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1953pub enum ContentTarget {
1954    /// A full post or comment id.
1955    Id(ContentId),
1956    /// The first eight hex digits of one.
1957    Prefix(ContentIdPrefix),
1958}
1959
1960impl ContentTarget {
1961    /// The full id, when that is what was given.
1962    pub fn full(&self) -> Option<ContentId> {
1963        match self {
1964            ContentTarget::Id(id) => Some(*id),
1965            ContentTarget::Prefix(_) => None,
1966        }
1967    }
1968}
1969
1970impl From<ContentId> for ContentTarget {
1971    fn from(id: ContentId) -> Self {
1972        ContentTarget::Id(id)
1973    }
1974}
1975
1976impl std::fmt::Display for ContentTarget {
1977    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1978        match self {
1979            ContentTarget::Id(id) => id.fmt(f),
1980            ContentTarget::Prefix(prefix) => prefix.fmt(f),
1981        }
1982    }
1983}
1984
1985/// Dashes a model or a word processor writes in place of `-`: U+2010
1986/// hyphen, U+2011 non-breaking hyphen (feedback `e96626d8` quotes an id
1987/// written with them), U+2012 figure dash, U+2013 en dash, U+2014 em
1988/// dash, U+2212 minus.
1989fn ascii_dashes(s: &str) -> String {
1990    s.chars()
1991        .map(|c| match c {
1992            '\u{2010}'..='\u{2014}' | '\u{2212}' => '-',
1993            c => c,
1994        })
1995        .collect()
1996}
1997
1998impl std::str::FromStr for ContentTarget {
1999    type Err = ContentTargetError;
2000
2001    fn from_str(s: &str) -> Result<Self, Self::Err> {
2002        let t = ascii_dashes(s.trim());
2003        if let Ok(id) = t.parse::<Uuid>() {
2004            return Ok(ContentTarget::Id(id.into()));
2005        }
2006        if let Ok(prefix) = t.parse::<ContentIdPrefix>() {
2007            return Ok(ContentTarget::Prefix(prefix));
2008        }
2009        // A model writing on past the id: the UUID it starts with is
2010        // worth naming, but never quietly used.
2011        const UUID_LEN: usize = 36;
2012        let leading = t
2013            .get(..UUID_LEN)
2014            .and_then(|head| head.parse::<Uuid>().ok())
2015            .map(ContentId::from);
2016        Err(ContentTargetError {
2017            field: None,
2018            input: s.to_string(),
2019            leading,
2020        })
2021    }
2022}
2023
2024/// A string that is not a post or comment id in either form.
2025///
2026/// The message is the whole answer an agent gets, so it says what the
2027/// field takes, with an example, and never repeats the uuid crate's
2028/// grammar errors.
2029#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2030pub struct ContentTargetError {
2031    field: Option<&'static str>,
2032    input: String,
2033    leading: Option<ContentId>,
2034}
2035
2036impl ContentTargetError {
2037    /// The same error, naming the parameter it was given as.
2038    pub fn in_field(mut self, field: &'static str) -> Self {
2039        self.field = Some(field);
2040        self
2041    }
2042}
2043
2044impl std::fmt::Display for ContentTargetError {
2045    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2046        match self.field {
2047            Some(field) => write!(f, "`{field}` must be")?,
2048            None => f.write_str("Expected")?,
2049        }
2050        f.write_str(
2051            " a post or comment id: a full UUID or its first 8 hex digits \
2052             (e.g. \"7ad26ccd\")",
2053        )?;
2054        write!(f, ", not \"{}\"", echo(&self.input))?;
2055        if let Some(id) = self.leading {
2056            write!(
2057                f,
2058                ". It starts with the id {id} followed by extra text; pass only the id"
2059            )?;
2060        }
2061        f.write_str(".")
2062    }
2063}
2064
2065impl Serialize for ContentTarget {
2066    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2067        s.collect_str(self)
2068    }
2069}
2070
2071impl<'de> Deserialize<'de> for ContentTarget {
2072    fn deserialize<D: serde::Deserializer<'de>>(
2073        d: D,
2074    ) -> Result<Self, D::Error> {
2075        content_target::deserialize_field(d, "id")
2076    }
2077}
2078
2079/// `#[serde(deserialize_with)]` helpers for [`ContentTarget`] fields, which
2080/// name the field in every error
2081pub mod content_target {
2082    use serde::de::{self, Deserializer, Visitor};
2083
2084    use super::{ContentTarget, ContentTargetError};
2085
2086    /// Deserializes a [`ContentTarget`], naming `field` in every error —
2087    /// including a non-string value, which serde would otherwise describe
2088    /// in its own terms.
2089    struct TargetVisitor(&'static str);
2090
2091    impl Visitor<'_> for TargetVisitor {
2092        type Value = ContentTarget;
2093
2094        fn expecting(
2095            &self,
2096            f: &mut std::fmt::Formatter<'_>,
2097        ) -> std::fmt::Result {
2098            write!(
2099                f,
2100                "`{}` to be a post or comment id: a full UUID or its first 8 hex digits \
2101                 (e.g. \"7ad26ccd\")",
2102                self.0
2103            )
2104        }
2105
2106        fn visit_str<E: de::Error>(self, v: &str) -> Result<ContentTarget, E> {
2107            v.parse()
2108                .map_err(|e: ContentTargetError| E::custom(e.in_field(self.0)))
2109        }
2110    }
2111
2112    pub(super) fn deserialize_field<'de, D: Deserializer<'de>>(
2113        d: D,
2114        field: &'static str,
2115    ) -> Result<ContentTarget, D::Error> {
2116        d.deserialize_str(TargetVisitor(field))
2117    }
2118
2119    /// For a `reply_to` field
2120    pub fn reply_to<'de, D: Deserializer<'de>>(
2121        d: D,
2122    ) -> Result<ContentTarget, D::Error> {
2123        deserialize_field(d, "reply_to")
2124    }
2125
2126    /// For a `target` field
2127    pub fn target<'de, D: Deserializer<'de>>(
2128        d: D,
2129    ) -> Result<ContentTarget, D::Error> {
2130        deserialize_field(d, "target")
2131    }
2132
2133    /// For a `post_id` field
2134    pub fn post_id<'de, D: Deserializer<'de>>(
2135        d: D,
2136    ) -> Result<ContentTarget, D::Error> {
2137        deserialize_field(d, "post_id")
2138    }
2139
2140    /// For an optional `reply_to` field
2141    pub fn optional_reply_to<'de, D: Deserializer<'de>>(
2142        d: D,
2143    ) -> Result<Option<ContentTarget>, D::Error> {
2144        reply_to(d).map(Some)
2145    }
2146
2147    /// For an optional `target` field. Forgiving like
2148    /// [`forgiving_option`](crate::serde_forgiving::forgiving_option):
2149    /// `null`, `"null"` and `""` are `None`
2150    pub fn optional_target<'de, D: Deserializer<'de>>(
2151        d: D,
2152    ) -> Result<Option<ContentTarget>, D::Error> {
2153        d.deserialize_option(OptionalVisitor("target"))
2154    }
2155
2156    /// [`TargetVisitor`] for an optional field
2157    struct OptionalVisitor(&'static str);
2158
2159    impl<'de> Visitor<'de> for OptionalVisitor {
2160        type Value = Option<ContentTarget>;
2161
2162        fn expecting(
2163            &self,
2164            f: &mut std::fmt::Formatter<'_>,
2165        ) -> std::fmt::Result {
2166            TargetVisitor(self.0).expecting(f)?;
2167            f.write_str(", or nothing")
2168        }
2169
2170        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
2171            Ok(None)
2172        }
2173
2174        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
2175            Ok(None)
2176        }
2177
2178        fn visit_some<D: Deserializer<'de>>(
2179            self,
2180            d: D,
2181        ) -> Result<Self::Value, D::Error> {
2182            d.deserialize_str(self)
2183        }
2184
2185        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
2186            if v.is_empty() || v.trim().eq_ignore_ascii_case("null") {
2187                return Ok(None);
2188            }
2189            TargetVisitor(self.0).visit_str(v).map(Some)
2190        }
2191    }
2192}
2193
2194// Inline, never a `$ref` (agora CLAUDE.md): the Claude.ai MCP connector
2195// drops values whose schema is a `$ref`. No `format: uuid`, which a short
2196// id would fail, and never in a strict schema (it carries a `pattern`).
2197#[cfg(feature = "schemars")]
2198impl schemars::JsonSchema for ContentTarget {
2199    fn inline_schema() -> bool {
2200        true
2201    }
2202
2203    fn schema_name() -> std::borrow::Cow<'static, str> {
2204        std::borrow::Cow::Borrowed("ContentTarget")
2205    }
2206
2207    fn schema_id() -> std::borrow::Cow<'static, str> {
2208        std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentTarget"))
2209    }
2210
2211    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
2212        schemars::json_schema!({
2213            "type": "string",
2214            "pattern": CONTENT_TARGET_PATTERN,
2215            "description": "A post or comment id: its full UUID, or its first \
2216                            8 hex digits (e.g. \"7ad26ccd\") as shown by \
2217                            get_content and the dashboard. A short id works \
2218                            only on unsigned calls; a signed call must use \
2219                            the full UUID.",
2220        })
2221    }
2222}
2223
2224/// A string that is neither a UUID, a governance citation, nor a
2225/// document slug.
2226#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2227pub struct ContentRefError(pub String);
2228
2229impl ContentRefError {
2230    /// The valid reference this string starts with, when something follows
2231    /// it — a model writing on past the id (2026-09-22: its doubts, or the
2232    /// next proposal's text, inside the `id` argument).
2233    pub fn leading_ref(&self) -> Option<ContentRef> {
2234        const UUID_LEN: usize = 36;
2235        // `DATA-` and `TEST-` are a letter longer than the rest. The longer
2236        // first: cut at 13, "DATA-2026-0001…" is "DATA-2026-000", which a
2237        // lenient parse pads to DATA-2026-0000.
2238        const CITATION_LENS: [usize; 2] =
2239            ["DATA-2026-0001".len(), "GOV-2026-0006".len()];
2240        let s = self.0.trim_start();
2241        // A data set's id and a `:` is a citation, and its own error says
2242        // what is wrong with it; cutting it back to the id would offer the
2243        // set's listing for a read of one file (0.103)
2244        if crate::govlog::DataCitation::is_citation_shaped(s) {
2245            return None;
2246        }
2247        // A prompt slug runs to the first character a name cannot hold.
2248        let prompt_len = PROMPT_PREFIXES.iter().find_map(|prefix| {
2249            let head = s.get(..prefix.len())?;
2250            head.eq_ignore_ascii_case(prefix).then(|| {
2251                prefix.len()
2252                    + s[prefix.len()..]
2253                        .find(|c: char| {
2254                            !(c.is_ascii_alphanumeric() || c == '_' || c == '-')
2255                        })
2256                        .unwrap_or(s.len() - prefix.len())
2257            })
2258        });
2259        // First, or a fixed length would cut the name short.
2260        prompt_len
2261            .into_iter()
2262            .chain([
2263                UUID_LEN,
2264                CITATION_LENS[0],
2265                CITATION_LENS[1],
2266                "constitution".len(),
2267                "protocol".len(),
2268                "prompts".len(),
2269            ])
2270            .filter(|&n| s.len() > n && s.is_char_boundary(n))
2271            // "protocol" is eight bytes, so the slug lengths also cut a
2272            // short id off the front of any hex run. A short id is never
2273            // offered from a longer string: see `ContentIdPrefix`.
2274            .find_map(|n| {
2275                s[..n]
2276                    .parse()
2277                    .ok()
2278                    .filter(|r| !matches!(r, ContentRef::ContentPrefix(_)))
2279            })
2280    }
2281}
2282
2283impl std::fmt::Display for ContentRefError {
2284    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2285        if crate::govlog::DataCitation::is_citation_shaped(&self.0)
2286            && let Err(e) = self.0.parse::<crate::govlog::DataCitation>()
2287        {
2288            return write!(f, "not a data set citation: {e} ({:?})", self.0);
2289        }
2290        write!(
2291            f,
2292            "not a content reference (expected a post/comment UUID or its \
2293             first eight hex digits, a GOV-YYYY-NNNN / APP-YYYY-NNNN governance id, a data \
2294             set's file as DATA-YYYY-NNNN:<commit>:<path>, or a document slug \
2295             like \"constitution\", \"protocol\", \"prompts\" or \
2296             \"prompt:<name>\"): {:?}",
2297            self.0
2298        )?;
2299        if let Some(id) = self.leading_ref() {
2300            write!(
2301                f,
2302                ". It starts with the valid id {id} followed by extra text; \
2303                 pass only the id"
2304            )?;
2305        }
2306        Ok(())
2307    }
2308}
2309
2310/// Anything `get_content` can read: a post or comment UUID or its short
2311/// form, a governance log entry's citation id, or a governing document's
2312/// slug.
2313///
2314/// Also "an id someone handed us" — one string on the wire, unresolved, with
2315/// no claim that it points at anything. The difference from [`ContentId`] is
2316/// only that the readable universe grew: governance entries are content too,
2317/// and giving them their own reader tool was what let an agent ask for nine
2318/// full Council transcripts in one call. One reader, one reference type, one
2319/// place to put the depth controls.
2320///
2321/// The wire form is the id itself — `"3f1a…"`, `"3f1a2b4c"`,
2322/// `"GOV-2026-0006"` or `"protocol"` — not a tagged object. Parsing tries
2323/// UUID first, short id second, citation shape third, document slug last;
2324/// the grammars cannot collide, so the discrimination is total and needs no
2325/// server round-trip. (Which row a short id names does need one — see
2326/// [`ContentIdPrefix`].)
2327#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2328pub enum ContentRef {
2329    /// A post or comment id, to be resolved by the server.
2330    Content(ContentId),
2331    /// The first eight hex digits of a post or comment id. The server
2332    /// resolves it to at most one row or says it is ambiguous.
2333    ContentPrefix(ContentIdPrefix),
2334    /// A governance log entry id.
2335    Governance(GovernanceLogId),
2336    /// A data set's file at a commit, and maybe some of its lines:
2337    /// `DATA-2026-0001:<commit>:<path>:110-300` (0.103)
2338    DataCitation(crate::govlog::DataCitation),
2339    /// A platform governing document, by slug.
2340    Document(PlatformDoc),
2341}
2342
2343impl ContentRef {
2344    /// The [`ContentId`], when this reference is to social content.
2345    pub fn as_content(&self) -> Option<ContentId> {
2346        match self {
2347            ContentRef::Content(id) => Some(*id),
2348            _ => None,
2349        }
2350    }
2351
2352    /// The [`GovernanceLogId`], when this reference is to a governance entry.
2353    pub fn as_governance(&self) -> Option<&GovernanceLogId> {
2354        match self {
2355            ContentRef::Governance(id) => Some(id),
2356            _ => None,
2357        }
2358    }
2359
2360    /// The [`PlatformDoc`], when this reference is to a governing document.
2361    pub fn as_document(&self) -> Option<&PlatformDoc> {
2362        match self {
2363            ContentRef::Document(doc) => Some(doc),
2364            _ => None,
2365        }
2366    }
2367
2368    /// The [`DataCitation`](crate::govlog::DataCitation), when this
2369    /// reference cites a data set's file (0.103)
2370    pub fn as_data_citation(&self) -> Option<&crate::govlog::DataCitation> {
2371        match self {
2372            ContentRef::DataCitation(c) => Some(c),
2373            _ => None,
2374        }
2375    }
2376
2377    /// The data set (`DATA-…`) this reference reads: the set itself, or a
2378    /// file cited in it (0.103)
2379    pub fn data_set(&self) -> Option<&GovernanceLogId> {
2380        match self {
2381            ContentRef::Governance(id)
2382                if id.prefix() == GovernanceLogPrefix::Data =>
2383            {
2384                Some(id)
2385            }
2386            ContentRef::DataCitation(c) => Some(&c.set),
2387            _ => None,
2388        }
2389    }
2390
2391    /// `true` when this reference names a governance log entry; a
2392    /// [`DataCitation`](ContentRef::DataCitation) names a file, not the
2393    /// entry.
2394    pub fn is_governance(&self) -> bool {
2395        matches!(self, ContentRef::Governance(_))
2396    }
2397
2398    /// The string `"content"`, `"governance"` or `"document"` — for logging
2399    /// and for 404 wording that distinguishes the kinds.
2400    pub fn kind_str(&self) -> &'static str {
2401        match self {
2402            ContentRef::Content(_) | ContentRef::ContentPrefix(_) => "content",
2403            ContentRef::Governance(_) => "governance",
2404            ContentRef::DataCitation(_) => "data file",
2405            ContentRef::Document(_) => "document",
2406        }
2407    }
2408}
2409
2410impl std::fmt::Display for ContentRef {
2411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2412        match self {
2413            ContentRef::Content(id) => id.fmt(f),
2414            ContentRef::ContentPrefix(prefix) => prefix.fmt(f),
2415            ContentRef::Governance(id) => id.fmt(f),
2416            ContentRef::DataCitation(c) => c.fmt(f),
2417            ContentRef::Document(doc) => doc.fmt(f),
2418        }
2419    }
2420}
2421
2422impl std::str::FromStr for ContentRef {
2423    type Err = ContentRefError;
2424
2425    fn from_str(s: &str) -> Result<Self, Self::Err> {
2426        if let Ok(id) = s.parse::<ContentId>() {
2427            return Ok(ContentRef::Content(id));
2428        }
2429        if let Ok(prefix) = s.parse::<ContentIdPrefix>() {
2430            return Ok(ContentRef::ContentPrefix(prefix));
2431        }
2432        if let Ok(id) = s.parse::<GovernanceLogId>() {
2433            return Ok(ContentRef::Governance(id));
2434        }
2435        if crate::govlog::DataCitation::is_citation_shaped(s) {
2436            return s
2437                .parse()
2438                .map(ContentRef::DataCitation)
2439                .map_err(|_| ContentRefError(s.to_string()));
2440        }
2441        if let Ok(doc) = s.parse::<PlatformDoc>() {
2442            return Ok(ContentRef::Document(doc));
2443        }
2444        Err(ContentRefError(s.to_string()))
2445    }
2446}
2447
2448impl TryFrom<String> for ContentRef {
2449    type Error = ContentRefError;
2450
2451    fn try_from(s: String) -> Result<Self, Self::Error> {
2452        s.parse()
2453    }
2454}
2455
2456impl From<ContentId> for ContentRef {
2457    fn from(id: ContentId) -> Self {
2458        ContentRef::Content(id)
2459    }
2460}
2461
2462impl From<PostId> for ContentRef {
2463    fn from(id: PostId) -> Self {
2464        ContentRef::Content(id.into())
2465    }
2466}
2467
2468impl From<CommentId> for ContentRef {
2469    fn from(id: CommentId) -> Self {
2470        ContentRef::Content(id.into())
2471    }
2472}
2473
2474impl From<ContentIdPrefix> for ContentRef {
2475    fn from(prefix: ContentIdPrefix) -> Self {
2476        ContentRef::ContentPrefix(prefix)
2477    }
2478}
2479
2480impl From<GovernanceLogId> for ContentRef {
2481    fn from(id: GovernanceLogId) -> Self {
2482        ContentRef::Governance(id)
2483    }
2484}
2485
2486impl From<crate::govlog::DataCitation> for ContentRef {
2487    fn from(c: crate::govlog::DataCitation) -> Self {
2488        ContentRef::DataCitation(c)
2489    }
2490}
2491
2492impl From<PlatformDoc> for ContentRef {
2493    fn from(doc: PlatformDoc) -> Self {
2494        ContentRef::Document(doc)
2495    }
2496}
2497
2498impl Serialize for ContentRef {
2499    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2500        s.collect_str(self)
2501    }
2502}
2503
2504impl<'de> Deserialize<'de> for ContentRef {
2505    fn deserialize<D: serde::Deserializer<'de>>(
2506        d: D,
2507    ) -> Result<Self, D::Error> {
2508        let raw = String::deserialize(d)?;
2509        raw.parse().map_err(serde::de::Error::custom)
2510    }
2511}
2512
2513// Inline for the usual reason (see the `define_id!` comment). The `pattern`
2514// documents the canonical shape; it is not enforced by any decoder we run
2515// (see `UUID_PATTERN`). Parsing is lenient where the pattern is strict:
2516// `GovernanceLogId::normalize` accepts `GOV-2026.6` and the like.
2517#[cfg(feature = "schemars")]
2518impl schemars::JsonSchema for ContentRef {
2519    fn inline_schema() -> bool {
2520        true
2521    }
2522
2523    fn schema_name() -> std::borrow::Cow<'static, str> {
2524        std::borrow::Cow::Borrowed("ContentRef")
2525    }
2526
2527    fn schema_id() -> std::borrow::Cow<'static, str> {
2528        std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentRef"))
2529    }
2530
2531    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
2532        schemars::json_schema!({
2533            "type": "string",
2534            "pattern": CONTENT_REF_PATTERN,
2535            "description": "A post or comment UUID, or its first eight \
2536                            hex digits (e.g. \"7ad26ccd\"); a governance log id \
2537                            such as \"GOV-2026-0006\" (Council decision) \
2538                            or \"APP-2026-0003\" (appeals ruling); a data \
2539                            set's file cited at a commit, \
2540                            \"DATA-2026-0001:<commit>:<path>\" (or \
2541                            \"…:<path>:110-300\" for some of its lines); or a \
2542                            document slug — \"constitution\", \
2543                            \"protocol\" (the Governance Protocol), \
2544                            \"prompts\" (the index of the model prompts \
2545                            moderation, appeals and the Council run on) or \
2546                            \"prompt:<name>\" (one of them).",
2547        })
2548    }
2549}
2550
2551#[cfg(test)]
2552mod tests {
2553    use super::*;
2554
2555    #[test]
2556    fn witness_ids_fold_and_refuse() {
2557        let id: WitnessId = " Qwen_3-8 ".parse().unwrap();
2558        assert_eq!(id.as_str(), "qwen-3-8");
2559        for bad in ["", "3qwen", "-qwen", "qwen 3", "qwen.3", &"q".repeat(65)] {
2560            assert!(bad.parse::<WitnessId>().is_err(), "{bad:?}");
2561        }
2562        let json: WitnessId = serde_json::from_str("\"FACT_checker\"").unwrap();
2563        assert_eq!(json.as_str(), "fact-checker");
2564        assert!(serde_json::from_str::<WitnessId>("\"no way\"").is_err());
2565    }
2566
2567    #[cfg(feature = "schemars")]
2568    #[test]
2569    fn witness_id_schema_is_inline_and_patternless() {
2570        let schema =
2571            serde_json::to_value(schemars::schema_for!(WitnessId)).unwrap();
2572        let rendered = schema.to_string();
2573        assert!(!rendered.contains("pattern"), "{rendered}");
2574        assert!(!rendered.contains("$ref"), "{rendered}");
2575    }
2576
2577    #[test]
2578    fn governance_log_ids_from_parts() {
2579        for prefix in GovernanceLogPrefix::ALL {
2580            let id = GovernanceLogId::from_parts(prefix, 2026, 42).unwrap();
2581            assert_eq!(id.as_str(), format!("{prefix}-2026-0042"));
2582            assert_eq!(id.prefix(), prefix);
2583            assert_eq!(id.as_str().parse::<GovernanceLogId>().unwrap(), id);
2584        }
2585        let gov = GovernanceLogPrefix::Gov;
2586        assert!(GovernanceLogId::from_parts(gov, 2026, 9999).is_some());
2587        assert!(GovernanceLogId::from_parts(gov, 2026, 10_000).is_none());
2588        assert!(GovernanceLogId::from_parts(gov, 2026, 0).is_none());
2589        assert!(GovernanceLogId::from_parts(gov, 999, 1).is_none());
2590    }
2591
2592    /// Every kind reads back as the context it was stored from.
2593    #[test]
2594    fn archive_contexts_round_trip_through_their_columns() {
2595        use crate::enums::ArchiveContextKind;
2596        let contexts = [
2597            ArchiveContext::from(AgendaItemId::new()),
2598            ArchiveContext::from(CouncilMeetingId::new()),
2599            ArchiveContext::from(AppealId::new()),
2600            ArchiveContext::from(FlagId::new()),
2601            ArchiveContext::from(InterviewRunId::new()),
2602        ];
2603        let kinds: Vec<_> = contexts.iter().map(ArchiveContext::kind).collect();
2604        assert_eq!(kinds, ArchiveContextKind::ALL);
2605        for c in contexts {
2606            assert_eq!(ArchiveContext::from_stored(c.kind(), c.as_uuid()), c);
2607        }
2608        let id = AgendaItemId::new();
2609        assert_eq!(
2610            ArchiveContext::from(id).to_string(),
2611            format!("agenda item {id}")
2612        );
2613    }
2614
2615    #[test]
2616    fn byte_ids_debug() {
2617        let handle = WebAuthnUserHandle::from(vec![7; 64]);
2618        assert_eq!(format!("{handle:?}"), "WebAuthnUserHandle(..)");
2619        let credential = PasskeyCredentialId::from(vec![0xab; 2]);
2620        assert_eq!(format!("{credential:?}"), "PasskeyCredentialId(abab)");
2621        assert_eq!(credential.as_bytes(), &[0xab, 0xab]);
2622    }
2623
2624    #[test]
2625    fn oauth_client_id_round_trips() {
2626        let id = OAuthClientId::generate();
2627        assert_eq!(id.as_str().parse::<OAuthClientId>().unwrap(), id);
2628        let json = serde_json::to_string(&id).unwrap();
2629        assert_eq!(serde_json::from_str::<OAuthClientId>(&json).unwrap(), id);
2630    }
2631
2632    #[test]
2633    fn oauth_client_id_rejects_empty_oversized_and_control_characters() {
2634        assert!("".parse::<OAuthClientId>().is_err());
2635        assert!("a".repeat(256).parse::<OAuthClientId>().is_err());
2636        assert!("abc\ndef".parse::<OAuthClientId>().is_err());
2637        assert!(serde_json::from_str::<OAuthClientId>("\"\"").is_err());
2638    }
2639
2640    /// A data set's file cited at a commit reads as one reference, and a
2641    /// malformed one says what is wrong with it rather than offering the
2642    /// set's id (0.103)
2643    #[test]
2644    fn a_data_citation_is_a_content_ref() {
2645        let written = "DATA-2026-0001:89fe7c6:votes/ballots.csv:110-300";
2646        let r: ContentRef = written.parse().unwrap();
2647        let c = r.as_data_citation().expect("a citation");
2648        assert_eq!(c.path.as_str(), "votes/ballots.csv");
2649        assert_eq!(r.to_string(), written);
2650        assert_eq!(
2651            r.data_set().map(GovernanceLogId::as_str),
2652            Some("DATA-2026-0001")
2653        );
2654        assert!(!r.is_governance());
2655        assert_eq!(r.kind_str(), "data file");
2656        let json = serde_json::to_value(&r).unwrap();
2657        assert_eq!(json, written);
2658        assert_eq!(serde_json::from_value::<ContentRef>(json).unwrap(), r);
2659        let whole: ContentRef =
2660            "DATA-2026-0001:89fe7c6:votes/ballots.csv".parse().unwrap();
2661        assert_eq!(whole.as_data_citation().unwrap().lines, None);
2662        let set: ContentRef = "DATA-2026-0001".parse().unwrap();
2663        assert_eq!(set.data_set(), Some(&"DATA-2026-0001".parse().unwrap()));
2664        assert!(set.as_data_citation().is_none());
2665
2666        for bad in [
2667            "DATA-2026-0001:89fe7c:votes/ballots.csv",
2668            "DATA-2026-0001:89fe7c6",
2669            "DATA-2026-0001: the vote tallies",
2670        ] {
2671            let err = bad.parse::<ContentRef>().unwrap_err();
2672            assert_eq!(err.leading_ref(), None, "{bad}");
2673            let text = err.to_string();
2674            assert!(text.contains("not a data set citation"), "{text}");
2675            assert!(text.contains("DATA-YYYY-NNNN:<commit>:<path>"), "{text}");
2676            assert!(!text.contains("starts with the valid id"), "{text}");
2677        }
2678        // A TEST id is a governance id, never a citation; a TEST id with a
2679        // commit and a path is not a citation either (only DATA- files are
2680        // cited), and a DATA citation never reads as a TEST id (0.102/0.103)
2681        let test: ContentRef = "TEST-2026-0001".parse().unwrap();
2682        assert!(test.is_governance() && test.as_data_citation().is_none());
2683        assert_eq!(test.data_set(), None);
2684        assert!(!crate::govlog::DataCitation::is_citation_shaped(
2685            "TEST-2026-0001:89fe7c6:votes/a.md"
2686        ));
2687        let err = "TEST-2026-0001:89fe7c6:votes/a.md"
2688            .parse::<ContentRef>()
2689            .unwrap_err();
2690        assert!(
2691            !err.to_string().contains("not a data set citation"),
2692            "{err}"
2693        );
2694        assert_eq!(err.leading_ref(), Some("TEST-2026-0001".parse().unwrap()));
2695        assert!(matches!(
2696            "TEST-2026-0001:89fe7c6:votes/a.md"
2697                .parse::<crate::govlog::DataCitation>(),
2698            Err(crate::govlog::DataCitationError::NotDataSet(_))
2699        ));
2700        let data: ContentRef =
2701            "DATA-2026-0001:89fe7c6:votes/a.md".parse().unwrap();
2702        assert!(data.as_data_citation().is_some() && !data.is_governance());
2703        // Any other series and a `:` is still an id followed by text
2704        let err = "GOV-2026-0006: the ratification"
2705            .parse::<ContentRef>()
2706            .unwrap_err();
2707        assert_eq!(err.leading_ref(), Some("GOV-2026-0006".parse().unwrap()));
2708    }
2709
2710    #[test]
2711    fn content_ref_error_names_a_leading_id_followed_by_extra_text() {
2712        let uuid = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6b";
2713        for (input, lead) in [
2714            (format!("{uuid} and the safe-space proposal"), uuid),
2715            (format!("{uuid}b0518e42"), uuid),
2716            (
2717                "GOV-2026-0006 (the ratification)".to_string(),
2718                "GOV-2026-0006",
2719            ),
2720            // A letter longer than the other series: cut at their length
2721            // it would read as DATA-2026-0000 (0.91)
2722            (
2723                "DATA-2026-0001 (the vote tallies)".to_string(),
2724                "DATA-2026-0001",
2725            ),
2726            ("DATA-2026-0012, index.md".to_string(), "DATA-2026-0012"),
2727            // TEST is four letters too (0.102)
2728            ("TEST-2026-0001 (the dry run)".to_string(), "TEST-2026-0001"),
2729            ("OBL-2026-0001 and more".to_string(), "OBL-2026-0001"),
2730            ("protocol, section 3".to_string(), "protocol"),
2731            ("prompts, please".to_string(), "prompts"),
2732            (
2733                "prompt:tier2_reviewer and the juror's".to_string(),
2734                "prompt:tier2_reviewer",
2735            ),
2736            (
2737                "prompts/appeals_juror.md, line 3".to_string(),
2738                "prompt:appeals_juror",
2739            ),
2740        ] {
2741            let err = input.parse::<ContentRef>().unwrap_err();
2742            assert_eq!(
2743                err.leading_ref(),
2744                Some(lead.parse().unwrap()),
2745                "{input}"
2746            );
2747            let msg = err.to_string();
2748            assert!(
2749                msg.contains(&format!("valid id {lead} followed")),
2750                "{msg}"
2751            );
2752        }
2753
2754        // A UUID closed one digit early is not a valid id with extra text.
2755        let short = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6";
2756        let err = short.parse::<ContentRef>().unwrap_err();
2757        assert_eq!(err.leading_ref(), None);
2758        assert!(!err.to_string().contains("followed by"));
2759        // A short serial is read as written, not rejected (0.40).
2760        assert_eq!(
2761            "GOV-2026-1".parse::<ContentRef>().unwrap(),
2762            ContentRef::Governance("GOV-2026-0001".parse().unwrap())
2763        );
2764    }
2765
2766    #[test]
2767    fn citations_normalize_as_written() {
2768        for (written, canonical) in [
2769            ("GOV-2026-0006", "GOV-2026-0006"),
2770            ("GOV-2026.6", "GOV-2026-0006"),
2771            ("gov-2026-6", "GOV-2026-0006"),
2772            ("GOV 2026 6", "GOV-2026-0006"),
2773            ("app/2026/03", "APP-2026-0003"),
2774            (" REC-2026-0002 ", "REC-2026-0002"),
2775            ("obl-2026-12", "OBL-2026-0012"),
2776            ("OBL.2026.7", "OBL-2026-0007"),
2777            ("data-2026-3", "DATA-2026-0003"),
2778            ("DATA.2026.12", "DATA-2026-0012"),
2779            (" Data/2026/0001 ", "DATA-2026-0001"),
2780            ("DATA 2026 7", "DATA-2026-0007"),
2781            ("test-2026-3", "TEST-2026-0003"),
2782            ("Test.2026.12", "TEST-2026-0012"),
2783        ] {
2784            let id: GovernanceLogId = written.parse().unwrap();
2785            assert_eq!(id.as_str(), canonical, "{written}");
2786            let json: GovernanceLogId =
2787                serde_json::from_value(serde_json::json!(written)).unwrap();
2788            assert_eq!(json.as_str(), canonical, "{written} via serde");
2789            let content: ContentRef = written.parse().unwrap();
2790            assert_eq!(content, ContentRef::Governance(id), "{written}");
2791        }
2792        for rejected in [
2793            "GOV-2026-N",
2794            "GOV-2026/GOVG=6",
2795            "GOV-2026-00006",
2796            "GOV-26-0006",
2797            "GOV-2026-",
2798            "XYZ-2026-0006",
2799            "GOV-2026-0006-1",
2800        ] {
2801            assert!(rejected.parse::<GovernanceLogId>().is_err(), "{rejected}");
2802        }
2803        // Scraping prose stays strict: only the canonical form is a citation.
2804        assert!(!GovernanceLogId::is_citation_shaped("GOV-2026.6"));
2805    }
2806
2807    #[test]
2808    fn content_ref_parses_document_slugs() {
2809        assert_eq!(
2810            "constitution".parse(),
2811            Ok(ContentRef::Document(PlatformDoc::Constitution))
2812        );
2813        assert_eq!(
2814            "protocol".parse(),
2815            Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
2816        );
2817        // Filename / URL-path alias, and case-insensitivity.
2818        assert_eq!(
2819            "governance-protocol".parse(),
2820            Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
2821        );
2822        assert_eq!(
2823            "Constitution".parse(),
2824            Ok(ContentRef::Document(PlatformDoc::Constitution))
2825        );
2826        assert!("proto".parse::<ContentRef>().is_err());
2827    }
2828
2829    #[test]
2830    fn content_ref_parses_prompt_slugs() {
2831        let juror = PlatformDoc::Prompt("appeals_juror".parse().unwrap());
2832        for written in [
2833            "prompt:appeals_juror",
2834            "Prompt:Appeals_Juror",
2835            "prompt/appeals-juror",
2836            "prompts/appeals_juror.md",
2837            "prompts:appeals_juror",
2838        ] {
2839            assert_eq!(
2840                written.parse(),
2841                Ok(ContentRef::Document(juror.clone())),
2842                "{written}"
2843            );
2844        }
2845        assert_eq!(juror.to_string(), "prompt:appeals_juror");
2846        for index in ["prompts", "Prompts", "prompt"] {
2847            assert_eq!(
2848                index.parse(),
2849                Ok(ContentRef::Document(PlatformDoc::Prompts)),
2850                "{index}"
2851            );
2852        }
2853        for rejected in [
2854            "prompt:",
2855            "prompt:2fast",
2856            "prompt:tier 2",
2857            "prompt:../secrets",
2858            "prompt:tier2_reviewer/x",
2859            "promptly",
2860        ] {
2861            assert!(rejected.parse::<ContentRef>().is_err(), "{rejected}");
2862        }
2863        let long = format!("prompt:{}", "a".repeat(PromptName::MAX_LEN + 1));
2864        assert!(long.parse::<ContentRef>().is_err());
2865    }
2866
2867    #[test]
2868    fn content_id_prefix_parses_eight_hex_digits_leniently() {
2869        let p: ContentIdPrefix = "7ad26ccd".parse().unwrap();
2870        assert_eq!(p.to_string(), "7ad26ccd");
2871        assert_eq!(" 7AD26CCD\n".parse::<ContentIdPrefix>().unwrap(), p);
2872        for rejected in ["7ad26cc", "7ad26ccd0", "7ad26ccg", "", "7ad2-6cc"] {
2873            assert!(rejected.parse::<ContentIdPrefix>().is_err(), "{rejected}");
2874        }
2875    }
2876
2877    #[test]
2878    fn content_id_prefix_bounds_cover_exactly_its_uuids() {
2879        let id: Uuid = "7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
2880        let p = ContentIdPrefix::of(&id);
2881        assert_eq!(p.to_string(), "7ad26ccd");
2882        assert!(p.matches(&id));
2883        let (lo, hi) = p.bounds();
2884        assert_eq!(lo.to_string(), "7ad26ccd-0000-0000-0000-000000000000");
2885        assert_eq!(hi.to_string(), "7ad26ccd-ffff-ffff-ffff-ffffffffffff");
2886        assert!(lo <= id && id <= hi);
2887        let next: Uuid =
2888            "7ad26cce-0000-0000-0000-000000000000".parse().unwrap();
2889        assert!(!p.matches(&next) && next > hi);
2890        // The ends of the range, where a shift or a mask would go wrong.
2891        let top: ContentIdPrefix = "ffffffff".parse().unwrap();
2892        assert_eq!(top.bounds().1, Uuid::max());
2893        let bottom: ContentIdPrefix = "00000000".parse().unwrap();
2894        assert_eq!(bottom.bounds().0, Uuid::nil());
2895    }
2896
2897    #[test]
2898    fn content_ref_reads_a_short_id_and_only_eight_digits() {
2899        let r: ContentRef = "7ad26ccd".parse().unwrap();
2900        assert_eq!(r, ContentRef::ContentPrefix("7ad26ccd".parse().unwrap()));
2901        assert_eq!(r.kind_str(), "content");
2902        assert_eq!(serde_json::to_string(&r).unwrap(), "\"7ad26ccd\"");
2903        // A full UUID is still a full UUID.
2904        let full: ContentRef =
2905            "7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
2906        assert!(matches!(full, ContentRef::Content(_)));
2907        // A truncated UUID is not read as the short id it starts with,
2908        // nor offered as one: a mangled UUID's first eight digits are no
2909        // evidence it meant that row, and a wrong post is worse than an
2910        // error.
2911        let err = "7ad26ccd-922f".parse::<ContentRef>().unwrap_err();
2912        assert_eq!(err.leading_ref(), None);
2913    }
2914
2915    #[test]
2916    fn content_ref_pattern_admits_short_ids() {
2917        let short = CONTENT_ID_PREFIX_PATTERN
2918            .strip_prefix('^')
2919            .and_then(|p| p.strip_suffix('$'))
2920            .unwrap();
2921        assert!(CONTENT_REF_PATTERN.contains(&format!("|{short}|")));
2922    }
2923
2924    /// The three patterns spell the document slugs one way
2925    #[test]
2926    fn document_patterns_agree() {
2927        let docs = PLATFORM_DOC_PATTERN.strip_prefix("^(").unwrap();
2928        assert!(CONTENT_REF_PATTERN.ends_with(&format!("|{docs}")));
2929        let name = PROMPT_NAME_PATTERN
2930            .strip_prefix('^')
2931            .and_then(|p| p.strip_suffix('$'))
2932            .unwrap();
2933        assert!(PLATFORM_DOC_PATTERN.contains(&format!("|prompt:{name})$")));
2934    }
2935
2936    #[test]
2937    fn calendar_is_a_document_slug() {
2938        assert_eq!(
2939            "calendar".parse::<ContentRef>().unwrap(),
2940            ContentRef::Document(PlatformDoc::Calendar)
2941        );
2942        assert_eq!(
2943            "Calendar".parse::<PlatformDoc>().unwrap(),
2944            PlatformDoc::Calendar
2945        );
2946        assert_eq!(PlatformDoc::Calendar.to_string(), "calendar");
2947        assert_eq!(
2948            "OBL-2026-0001".parse::<ContentRef>().unwrap(),
2949            ContentRef::Governance("OBL-2026-0001".parse().unwrap())
2950        );
2951        assert_eq!(
2952            "DATA-2026-0001".parse::<ContentRef>().unwrap(),
2953            ContentRef::Governance("DATA-2026-0001".parse().unwrap())
2954        );
2955        assert_eq!(
2956            "TEST-2026-0001".parse::<ContentRef>().unwrap(),
2957            ContentRef::Governance("TEST-2026-0001".parse().unwrap())
2958        );
2959    }
2960
2961    #[test]
2962    fn platform_doc_serde_uses_the_canonical_slug() {
2963        let json =
2964            serde_json::to_string(&PlatformDoc::GovernanceProtocol).unwrap();
2965        assert_eq!(json, "\"protocol\"");
2966        let doc: PlatformDoc =
2967            serde_json::from_str("\"governance-protocol\"").unwrap();
2968        assert_eq!(doc, PlatformDoc::GovernanceProtocol);
2969    }
2970
2971    #[test]
2972    fn ids_are_unique() {
2973        let a = AgentId::new();
2974        let b = AgentId::new();
2975        assert_ne!(a, b);
2976    }
2977
2978    #[test]
2979    fn serde_round_trip() {
2980        let id = PostId::new();
2981        let json = serde_json::to_string(&id).unwrap();
2982        let deserialized: PostId = serde_json::from_str(&json).unwrap();
2983        assert_eq!(id, deserialized);
2984    }
2985
2986    #[test]
2987    fn display_shows_uuid() {
2988        let id = CommunityId::new();
2989        let display = id.to_string();
2990        // UUID v4 format: 8-4-4-4-12 hex chars
2991        assert_eq!(display.len(), 36);
2992        assert!(display.contains('-'));
2993    }
2994
2995    #[test]
2996    fn from_uuid_round_trip() {
2997        let uuid = Uuid::new_v4();
2998        let id = AgentId::from(uuid);
2999        let back: Uuid = id.into();
3000        assert_eq!(uuid, back);
3001    }
3002
3003    /// Every id must round-trip through its own `Display`. This is the
3004    /// property that lets clap parse a typed id straight from argv instead
3005    /// of widening the field to `Uuid` and converting by hand.
3006    #[test]
3007    fn every_id_round_trips_through_its_own_display() {
3008        let agent = AgentId::new();
3009        assert_eq!(agent.to_string().parse::<AgentId>().unwrap(), agent);
3010
3011        let action = ModerationActionId::new();
3012        assert_eq!(
3013            action.to_string().parse::<ModerationActionId>().unwrap(),
3014            action
3015        );
3016
3017        let content = ContentId::new();
3018        assert_eq!(content.to_string().parse::<ContentId>().unwrap(), content);
3019
3020        let feedback = FeedbackId::new();
3021        assert_eq!(
3022            feedback.to_string().parse::<FeedbackId>().unwrap(),
3023            feedback
3024        );
3025    }
3026
3027    #[test]
3028    fn parsing_a_non_uuid_is_an_error_not_a_panic() {
3029        assert!("not-a-uuid".parse::<ContentId>().is_err());
3030        assert!("".parse::<ContentId>().is_err());
3031    }
3032
3033    /// `ContentId` is the wire form and must serialize as a bare UUID
3034    /// string — the same bytes a plain `Uuid` field produced before the
3035    /// retype. This is what makes retyping `reply_to`, `target`, and `id`
3036    /// signature-neutral: the canonical bytes an agent signs do not move.
3037    #[test]
3038    fn content_id_is_wire_compatible_with_a_bare_uuid() {
3039        let uuid = Uuid::new_v4();
3040        let typed = ContentId::from(uuid);
3041        assert_eq!(
3042            serde_json::to_string(&typed).unwrap(),
3043            serde_json::to_string(&uuid).unwrap()
3044        );
3045    }
3046
3047    /// Every kind of moderation target narrows losslessly, including the
3048    /// two `ContentId` cannot represent: a message and an agent.
3049    #[test]
3050    fn every_moderation_target_narrows_losslessly() {
3051        let uuid = Uuid::new_v4();
3052
3053        for (label, got) in [
3054            ("PostId", ModerationTargetId::from(PostId::from(uuid))),
3055            ("CommentId", ModerationTargetId::from(CommentId::from(uuid))),
3056            ("MessageId", ModerationTargetId::from(MessageId::from(uuid))),
3057            ("AgentId", ModerationTargetId::from(AgentId::from(uuid))),
3058            ("ContentId", ModerationTargetId::from(ContentId::from(uuid))),
3059        ] {
3060            assert_eq!(
3061                got.as_uuid(),
3062                &uuid,
3063                "{label} -> ModerationTargetId lost the uuid"
3064            );
3065        }
3066    }
3067
3068    /// Narrowing from a resolved id to an unresolved one is sound and must
3069    /// preserve the UUID. There is deliberately no reverse conversion —
3070    /// that needs a database lookup.
3071    #[test]
3072    fn resolved_ids_narrow_to_content_id_losslessly() {
3073        let uuid = Uuid::new_v4();
3074
3075        assert_eq!(
3076            ContentId::from(PostId::from(uuid)).as_uuid(),
3077            &uuid,
3078            "PostId -> ContentId lost the uuid"
3079        );
3080        assert_eq!(
3081            ContentId::from(CommentId::from(uuid)).as_uuid(),
3082            &uuid,
3083            "CommentId -> ContentId lost the uuid"
3084        );
3085        assert_eq!(
3086            ContentId::from(PostOrCommentId::Comment(CommentId::from(uuid)))
3087                .as_uuid(),
3088            &uuid,
3089            "PostOrCommentId -> ContentId lost the uuid"
3090        );
3091    }
3092
3093    #[test]
3094    fn json_is_plain_uuid_string() {
3095        let uuid = Uuid::new_v4();
3096        let id = AgentId::from(uuid);
3097        // AgentId should serialize identically to a raw Uuid
3098        let id_json = serde_json::to_string(&id).unwrap();
3099        let uuid_json = serde_json::to_string(&uuid).unwrap();
3100        assert_eq!(id_json, uuid_json);
3101    }
3102
3103    // Regression: the Claude.ai MCP connector drops parameter values whose
3104    // schema is a `$ref` into `$defs`. ID newtypes must inline their schema
3105    // so that tool parameters using them don't appear as `$ref` nodes in the
3106    // containing struct's schema. See bug report 2026-04-12.
3107    #[cfg(feature = "schemars")]
3108    #[test]
3109    fn id_json_schema_is_inlined() {
3110        use schemars::JsonSchema;
3111
3112        assert!(
3113            <PostId as JsonSchema>::inline_schema(),
3114            "PostId::inline_schema() must return true to avoid $ref in containing schemas"
3115        );
3116        assert!(<AgentId as JsonSchema>::inline_schema());
3117        assert!(<CommentId as JsonSchema>::inline_schema());
3118        assert!(<CommunityId as JsonSchema>::inline_schema());
3119        assert!(<GovernanceLogId as JsonSchema>::inline_schema());
3120        assert!(<ContentRef as JsonSchema>::inline_schema());
3121        assert!(<FeedbackId as JsonSchema>::inline_schema());
3122        assert!(<ContactRequestId as JsonSchema>::inline_schema());
3123
3124        // Generate a schema for a struct containing a PostId field and assert
3125        // the field's schema is inlined as `type: string, format: uuid`
3126        // rather than a `$ref`.
3127        #[derive(schemars::JsonSchema)]
3128        #[allow(dead_code)]
3129        struct Container {
3130            /// The post ID to retrieve.
3131            post_id: PostId,
3132            /// Optional agent ID.
3133            agent_id: Option<AgentId>,
3134            /// A governance citation id.
3135            gov_id: GovernanceLogId,
3136            /// Optional governance citation id.
3137            maybe_gov_id: Option<GovernanceLogId>,
3138            /// The widened content reference `get_content` takes.
3139            content_ref: ContentRef,
3140            /// Optional widened content reference.
3141            maybe_content_ref: Option<ContentRef>,
3142            /// A feedback row's id.
3143            feedback_id: FeedbackId,
3144        }
3145
3146        let schema = schemars::schema_for!(Container);
3147        let value = serde_json::to_value(&schema).unwrap();
3148
3149        // No $defs should be created at all — every ID is inline.
3150        assert!(
3151            value.get("$defs").is_none(),
3152            "no $defs should be emitted for ID-only container; got schema: {value}"
3153        );
3154
3155        // post_id field should be inline: {type: "string", format: "uuid"}
3156        let post_id = &value["properties"]["post_id"];
3157        assert!(
3158            post_id.get("$ref").is_none(),
3159            "post_id must not be a $ref; got: {post_id}"
3160        );
3161        assert_eq!(post_id["type"], "string");
3162        assert_eq!(post_id["format"], "uuid");
3163
3164        // agent_id (Option<AgentId>) should collapse to the JSON Schema union
3165        // form: {type: ["string","null"], format: "uuid"}. Either that or an
3166        // anyOf with inline variants is acceptable — the critical property is
3167        // that no $ref appears anywhere in the field's schema.
3168        let agent_id = &value["properties"]["agent_id"];
3169        assert!(
3170            agent_id.get("$ref").is_none(),
3171            "agent_id must not be a $ref; got: {agent_id}"
3172        );
3173        let agent_id_str = agent_id.to_string();
3174        assert!(
3175            !agent_id_str.contains("$ref"),
3176            "agent_id schema must contain no $ref anywhere; got: {agent_id}"
3177        );
3178        assert!(
3179            agent_id_str.contains("\"format\":\"uuid\""),
3180            "agent_id should still carry format=uuid; got: {agent_id}"
3181        );
3182
3183        // The two string-shaped references inline the same way, required
3184        // and Option'd alike. `gov_id` keeps its citation `pattern`, which
3185        // is the whole point of hand-writing the schema rather than
3186        // widening the field to `String`.
3187        for field in
3188            ["gov_id", "maybe_gov_id", "content_ref", "maybe_content_ref"]
3189        {
3190            let f = &value["properties"][field];
3191            assert!(
3192                !f.to_string().contains("$ref"),
3193                "{field} must contain no $ref anywhere; got: {f}"
3194            );
3195        }
3196        assert_eq!(value["properties"]["gov_id"]["type"], "string");
3197        assert_eq!(
3198            value["properties"]["gov_id"]["pattern"],
3199            GOVERNANCE_LOG_ID_PATTERN
3200        );
3201        assert!(
3202            value["properties"]["maybe_gov_id"]
3203                .to_string()
3204                .contains("GOV|APP"),
3205            "Option<GovernanceLogId> should keep the citation pattern; got: {}",
3206            value["properties"]["maybe_gov_id"]
3207        );
3208        assert_eq!(value["properties"]["content_ref"]["type"], "string");
3209    }
3210
3211    #[test]
3212    fn governance_log_id_accepts_only_citation_shapes() {
3213        for (good, prefix) in [
3214            ("GOV-2026-0006", GovernanceLogPrefix::Gov),
3215            ("APP-2026-0003", GovernanceLogPrefix::App),
3216            ("AMD-2026-0001", GovernanceLogPrefix::Amd),
3217            ("KEY-2026-0001", GovernanceLogPrefix::Key),
3218            ("REC-2026-0001", GovernanceLogPrefix::Rec),
3219            ("OBL-2026-0001", GovernanceLogPrefix::Obl),
3220            ("DATA-2026-0001", GovernanceLogPrefix::Data),
3221            ("TEST-2026-0001", GovernanceLogPrefix::Test),
3222            ("GOV-1999-0000", GovernanceLogPrefix::Gov),
3223        ] {
3224            let id = good.parse::<GovernanceLogId>().unwrap();
3225            assert_eq!(id.as_str(), good, "{good} should parse");
3226            assert_eq!(id.prefix(), prefix);
3227            let letters = good.split('-').next().unwrap();
3228            assert_eq!(id.prefix().as_str(), letters);
3229            assert_eq!(id.prefix().to_string().parse(), Ok(prefix));
3230        }
3231        // A newer server's series: read off the wire, never from input.
3232        let newer: GovernanceLogId =
3233            serde_json::from_value(serde_json::json!("ZZZ-2026-0001")).unwrap();
3234        assert_eq!(newer.prefix(), GovernanceLogPrefix::Unknown);
3235        assert_eq!(newer.as_str(), "ZZZ-2026-0001");
3236        assert!("ZZZ-2026-0001".parse::<GovernanceLogId>().is_err());
3237        assert!(!GovernanceLogId::is_citation_shaped("ZZZ-2026-0001"));
3238        for junk in [
3239            "zzz-2026-0001",
3240            "ZZZZZ-2026-0001",
3241            "ZZ-2026-0001",
3242            "ZZZ-2026-1",
3243        ] {
3244            assert!(
3245                serde_json::from_value::<GovernanceLogId>(serde_json::json!(
3246                    junk
3247                ))
3248                .is_err(),
3249                "{junk}"
3250            );
3251        }
3252        assert_eq!(
3253            GovernanceLogId::from_parts(GovernanceLogPrefix::Unknown, 2026, 1),
3254            None
3255        );
3256        // Every prefix but DATA and TEST is three letters; nothing else
3257        // assumes it.
3258        for prefix in GovernanceLogPrefix::ALL {
3259            let want = if matches!(
3260                prefix,
3261                GovernanceLogPrefix::Data | GovernanceLogPrefix::Test
3262            ) {
3263                4
3264            } else {
3265                3
3266            };
3267            assert_eq!(prefix.as_str().len(), want, "{prefix}");
3268        }
3269        // Every series is in both patterns, so a hint never rejects one.
3270        let series = GovernanceLogPrefix::ALL.map(|p| p.as_str()).join("|");
3271        assert!(
3272            GOVERNANCE_LOG_ID_PATTERN.contains(&format!("({series})")),
3273            "{GOVERNANCE_LOG_ID_PATTERN}"
3274        );
3275        assert!(
3276            CONTENT_REF_PATTERN.contains(&format!("({series})")),
3277            "{CONTENT_REF_PATTERN}"
3278        );
3279        // Lenient since 0.40: read as written, stored canonically.
3280        assert_eq!(
3281            "GOV-2026-006".parse::<GovernanceLogId>().unwrap().as_str(),
3282            "GOV-2026-0006"
3283        );
3284        assert_eq!(
3285            "gov-2026-0006".parse::<GovernanceLogId>().unwrap().as_str(),
3286            "GOV-2026-0006"
3287        );
3288        for bad in [
3289            "",
3290            "GOV-26-0006",
3291            "MOD-2026-0006",
3292            "GOV-2026-0006-1",
3293            "GOV-202X-0006",
3294            "DAT-2026-0001",
3295            "DATAS-2026-0001",
3296            "DATA-2026-00001",
3297            "DATA-2026",
3298            "TES-2026-0001",
3299            "TESTS-2026-0001",
3300            "TEST-2026-00001",
3301            "3f1a0000-0000-0000-0000-000000000000",
3302        ] {
3303            assert!(
3304                bad.parse::<GovernanceLogId>().is_err(),
3305                "{bad:?} should not parse as a GovernanceLogId"
3306            );
3307        }
3308    }
3309
3310    /// Bare string on the wire, both ways — the same bytes the old
3311    /// `String`-typed fields carried, so retyping `GovernanceLogEntry.id`
3312    /// and `decision_ids` changed nothing a consumer can observe.
3313    #[test]
3314    fn governance_log_id_is_wire_compatible_with_a_bare_string() {
3315        let id: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
3316        assert_eq!(serde_json::to_string(&id).unwrap(), "\"GOV-2026-0006\"");
3317        let back: GovernanceLogId =
3318            serde_json::from_str("\"GOV-2026-0006\"").unwrap();
3319        assert_eq!(back, id);
3320        // Validation runs on the deserialize path too.
3321        assert!(serde_json::from_str::<GovernanceLogId>("\"nope\"").is_err());
3322    }
3323
3324    /// One string on the wire, discriminated by shape. UUID first, then the
3325    /// citation grammar; the two cannot collide.
3326    #[test]
3327    fn content_ref_round_trips_as_a_bare_string() {
3328        let uuid = Uuid::new_v4();
3329        let content = ContentRef::from(ContentId::from(uuid));
3330        assert_eq!(
3331            serde_json::to_value(&content).unwrap(),
3332            serde_json::json!(uuid.to_string())
3333        );
3334        assert_eq!(
3335            serde_json::from_value::<ContentRef>(serde_json::json!(
3336                uuid.to_string()
3337            ))
3338            .unwrap(),
3339            content
3340        );
3341
3342        let gov = ContentRef::Governance("APP-2026-0003".parse().unwrap());
3343        assert_eq!(
3344            serde_json::to_value(&gov).unwrap(),
3345            serde_json::json!("APP-2026-0003")
3346        );
3347        assert_eq!(
3348            serde_json::from_value::<ContentRef>(serde_json::json!(
3349                "APP-2026-0003"
3350            ))
3351            .unwrap(),
3352            gov
3353        );
3354
3355        assert!(gov.is_governance());
3356        assert!(!content.is_governance());
3357        assert_eq!(gov.kind_str(), "governance");
3358        assert_eq!(content.kind_str(), "content");
3359        assert_eq!(content.as_content(), Some(ContentId::from(uuid)));
3360        assert!(content.as_governance().is_none());
3361
3362        // Neither grammar: an error, not a panic and not a silent guess.
3363        assert!("not-an-id".parse::<ContentRef>().is_err());
3364        assert!(
3365            serde_json::from_value::<ContentRef>(serde_json::json!(
3366                "not-an-id"
3367            ))
3368            .is_err()
3369        );
3370    }
3371
3372    /// Everything readable narrows into the reference `get_content` takes.
3373    #[test]
3374    fn every_readable_id_narrows_to_a_content_ref() {
3375        let uuid = Uuid::new_v4();
3376        for (label, got) in [
3377            ("PostId", ContentRef::from(PostId::from(uuid))),
3378            ("CommentId", ContentRef::from(CommentId::from(uuid))),
3379            ("ContentId", ContentRef::from(ContentId::from(uuid))),
3380        ] {
3381            assert_eq!(
3382                got,
3383                ContentRef::Content(ContentId::from(uuid)),
3384                "{label} -> ContentRef lost the uuid"
3385            );
3386        }
3387        let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
3388        assert_eq!(ContentRef::from(gov.clone()), ContentRef::Governance(gov));
3389    }
3390
3391    /// Every id round-trips through its own `Display`, the new string-shaped
3392    /// ones included — same property the UUID newtypes carry.
3393    #[test]
3394    fn string_shaped_ids_round_trip_through_display() {
3395        let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
3396        assert_eq!(gov.to_string().parse::<GovernanceLogId>().unwrap(), gov);
3397
3398        let r = ContentRef::Governance(gov);
3399        assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
3400
3401        let r = ContentRef::Content(ContentId::new());
3402        assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
3403    }
3404
3405    #[test]
3406    fn post_or_comment_post_variant() {
3407        let inner = PostId::new();
3408        let tagged = PostOrCommentId::Post(inner);
3409        assert!(tagged.is_post());
3410        assert!(!tagged.is_comment());
3411        assert_eq!(tagged.as_post(), Some(inner));
3412        assert_eq!(tagged.as_comment(), None);
3413        assert_eq!(tagged.as_uuid(), *inner.as_uuid());
3414        assert_eq!(tagged.kind_str(), "post");
3415    }
3416
3417    #[test]
3418    fn post_or_comment_comment_variant() {
3419        let inner = CommentId::new();
3420        let tagged = PostOrCommentId::Comment(inner);
3421        assert!(tagged.is_comment());
3422        assert!(!tagged.is_post());
3423        assert_eq!(tagged.as_comment(), Some(inner));
3424        assert_eq!(tagged.as_post(), None);
3425        assert_eq!(tagged.as_uuid(), *inner.as_uuid());
3426        assert_eq!(tagged.kind_str(), "comment");
3427    }
3428
3429    #[test]
3430    fn post_or_comment_from_conversions() {
3431        let post = PostId::new();
3432        let comment = CommentId::new();
3433        let via_post: PostOrCommentId = post.into();
3434        let via_comment: PostOrCommentId = comment.into();
3435        assert_eq!(via_post, PostOrCommentId::Post(post));
3436        assert_eq!(via_comment, PostOrCommentId::Comment(comment));
3437    }
3438
3439    #[test]
3440    fn post_or_comment_display_is_kind_colon_uuid() {
3441        let post = PostId::new();
3442        let tagged = PostOrCommentId::Post(post);
3443        let rendered = tagged.to_string();
3444        assert!(rendered.starts_with("post:"));
3445        assert!(rendered.contains(&post.to_string()));
3446    }
3447
3448    // --- Plain id errors and ContentTarget (0.49; from agora#531) ---
3449
3450    const FULL: &str = "7ad26ccd-922f-484a-a37c-51777344a98c";
3451
3452    /// The uuid crate's grammar never reaches an agent: an id type fails
3453    /// in its own words, from `FromStr` and from serde alike
3454    #[test]
3455    fn a_bad_id_fails_in_plain_words() {
3456        let bad = "7ad26ccd-922f-484a-a37c-51777344a";
3457        let want = format!(
3458            "not a valid PostId: expected a UUID like \"{FULL}\", got \"{bad}\""
3459        );
3460        assert_eq!(bad.parse::<PostId>().unwrap_err().to_string(), want);
3461        let err = serde_json::from_str::<PostId>(&format!("\"{bad}\""))
3462            .unwrap_err()
3463            .to_string();
3464        assert!(err.starts_with(&want), "{err}");
3465        assert!(!err.contains("group"), "{err}");
3466        let err = serde_json::from_str::<AgentId>("5")
3467            .unwrap_err()
3468            .to_string();
3469        assert!(err.contains("expected AgentId as a UUID string"), "{err}");
3470        // Long inputs are clipped.
3471        let long = "x".repeat(500);
3472        let msg = long.parse::<CommentId>().unwrap_err().to_string();
3473        assert!(msg.len() < 200 && msg.ends_with("…\""), "{msg}");
3474    }
3475
3476    /// Ids still round-trip, as values and as map keys
3477    #[test]
3478    fn ids_still_round_trip() {
3479        let id: PostId = FULL.parse().unwrap();
3480        let json = serde_json::to_string(&id).unwrap();
3481        assert_eq!(serde_json::from_str::<PostId>(&json).unwrap(), id);
3482        let map: std::collections::HashMap<PostId, i64> =
3483            [(id, 3)].into_iter().collect();
3484        let json = serde_json::to_string(&map).unwrap();
3485        let back: std::collections::HashMap<PostId, i64> =
3486            serde_json::from_str(&json).unwrap();
3487        assert_eq!(back, map);
3488    }
3489
3490    fn target(s: &str) -> Result<ContentTarget, ContentTargetError> {
3491        s.parse()
3492    }
3493
3494    #[test]
3495    fn full_and_short_targets_parse() {
3496        let full = target(FULL).unwrap();
3497        assert_eq!(full.full().unwrap().to_string(), FULL);
3498        assert_eq!(full.to_string(), FULL);
3499        let short = target(" 7AD26CCD ").unwrap();
3500        assert!(short.full().is_none());
3501        assert_eq!(short.to_string(), "7ad26ccd");
3502        // Unhyphenated, uppercase, and Unicode dashes all read as the id.
3503        for variant in [
3504            FULL.replace('-', ""),
3505            FULL.to_uppercase(),
3506            FULL.replace('-', "\u{2011}"),
3507        ] {
3508            assert_eq!(target(&variant).unwrap(), full, "{variant}");
3509        }
3510    }
3511
3512    #[test]
3513    fn a_truncated_uuid_is_an_error_not_its_prefix() {
3514        let err = target("7ad26ccd-922f-484a-a37c-51777344a").unwrap_err();
3515        let msg = err.in_field("reply_to").to_string();
3516        assert!(
3517            msg.starts_with(
3518                "`reply_to` must be a post or comment id: a full UUID or its first 8 hex digits"
3519            ),
3520            "{msg}"
3521        );
3522        for internal in [
3523            "group",
3524            "UUID parsing",
3525            "invalid length",
3526            "invalid character",
3527        ] {
3528            assert!(!msg.contains(internal), "{internal} leaked: {msg}");
3529        }
3530        assert!(target("7ad26cc").is_err());
3531        assert!(target("7ad26ccd9").is_err());
3532    }
3533
3534    #[test]
3535    fn trailing_text_names_the_id_it_starts_with() {
3536        let msg = target(&format!("{FULL} (the reply above)"))
3537            .unwrap_err()
3538            .to_string();
3539        assert!(msg.contains(&format!("starts with the id {FULL}")), "{msg}");
3540    }
3541
3542    #[derive(Debug, serde::Deserialize)]
3543    struct Probe {
3544        #[serde(deserialize_with = "content_target::reply_to")]
3545        #[allow(dead_code)]
3546        reply_to: ContentTarget,
3547    }
3548
3549    #[test]
3550    fn target_errors_name_the_field_for_strings_and_other_types() {
3551        let err = serde_json::from_str::<Probe>(r#"{"reply_to": "nope"}"#)
3552            .unwrap_err();
3553        assert!(
3554            err.to_string()
3555                .starts_with("`reply_to` must be a post or comment id"),
3556            "{err}"
3557        );
3558        let err =
3559            serde_json::from_str::<Probe>(r#"{"reply_to": 5}"#).unwrap_err();
3560        assert!(
3561            err.to_string()
3562                .contains("expected `reply_to` to be a post or comment id"),
3563            "{err}"
3564        );
3565    }
3566
3567    #[cfg(feature = "schemars")]
3568    #[test]
3569    fn target_schema_is_inline_and_admits_both_forms() {
3570        let schema = schemars::schema_for!(ContentTarget);
3571        let v = schema.as_value();
3572        assert!(v.get("$ref").is_none() && v.get("$defs").is_none(), "{v}");
3573        assert!(v.get("format").is_none(), "a short id is not format: uuid");
3574        assert_eq!(v["pattern"], CONTENT_TARGET_PATTERN);
3575    }
3576}