1use serde::{Deserialize, Serialize};
11use uuid::Uuid;
12
13pub 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
22pub const GOVERNANCE_LOG_ID_PATTERN: &str =
24 "^(GOV|APP|AMD|KEY|REC|OBL|DATA)-[0-9]{4}-[0-9]{4}$";
25
26pub const CONTENT_ID_PREFIX_PATTERN: &str = "^[0-9a-f]{8}$";
29
30pub 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)-[0-9]{4}-[0-9]{4}|constitution|protocol|prompts|calendar|prompt:[a-z][a-z0-9_]*)$";
33
34pub const PLATFORM_DOC_PATTERN: &str =
36 "^(constitution|protocol|prompts|calendar|prompt:[a-z][a-z0-9_]*)$";
37
38pub const PROMPT_NAME_PATTERN: &str = "^[a-z][a-z0-9_]*$";
40
41macro_rules! define_id {
42 ($(#[doc = $doc:expr])* $name:ident) => {
43 $(#[doc = $doc])*
44 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
45 #[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
46 #[cfg_attr(feature = "sqlx", sqlx(transparent))]
47 pub struct $name(Uuid);
48
49 impl $name {
50 pub fn new() -> Self {
52 Self(Uuid::new_v4())
53 }
54
55 pub fn as_uuid(&self) -> &Uuid {
57 &self.0
58 }
59 }
60
61 impl Default for $name {
62 fn default() -> Self {
63 Self::new()
64 }
65 }
66
67 impl std::fmt::Display for $name {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 self.0.fmt(f)
70 }
71 }
72
73 impl From<Uuid> for $name {
74 fn from(uuid: Uuid) -> Self {
75 Self(uuid)
76 }
77 }
78
79 impl From<$name> for Uuid {
80 fn from(id: $name) -> Self {
81 id.0
82 }
83 }
84
85 impl std::str::FromStr for $name {
94 type Err = IdParseError;
95
96 fn from_str(s: &str) -> Result<Self, Self::Err> {
97 s.parse::<Uuid>().map(Self).map_err(|_| IdParseError {
98 name: stringify!($name),
99 input: s.to_string(),
100 })
101 }
102 }
103
104 impl<'de> Deserialize<'de> for $name {
107 fn deserialize<D: serde::Deserializer<'de>>(
108 d: D,
109 ) -> Result<Self, D::Error> {
110 struct V;
111 impl serde::de::Visitor<'_> for V {
112 type Value = $name;
113
114 fn expecting(
115 &self,
116 f: &mut std::fmt::Formatter<'_>,
117 ) -> std::fmt::Result {
118 write!(f, "{} as a UUID string", stringify!($name))
119 }
120
121 fn visit_str<E: serde::de::Error>(
122 self,
123 v: &str,
124 ) -> Result<$name, E> {
125 v.parse().map_err(E::custom)
126 }
127 }
128 d.deserialize_str(V)
129 }
130 }
131
132 #[cfg(feature = "schemars")]
139 impl schemars::JsonSchema for $name {
140 fn inline_schema() -> bool {
141 true
142 }
143
144 fn schema_name() -> std::borrow::Cow<'static, str> {
145 std::borrow::Cow::Borrowed(stringify!($name))
146 }
147
148 fn schema_id() -> std::borrow::Cow<'static, str> {
149 std::borrow::Cow::Borrowed(concat!(module_path!(), "::", stringify!($name)))
150 }
151
152 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
153 schemars::json_schema!({
154 "type": "string",
155 "format": "uuid",
156 "pattern": UUID_PATTERN,
157 })
158 }
159 }
160 };
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
169#[error(
170 "not a valid {name}: expected a UUID like \
171 \"7ad26ccd-922f-484a-a37c-51777344a98c\", got \"{}\"",
172 echo(input)
173)]
174pub struct IdParseError {
175 pub name: &'static str,
177 pub input: String,
178}
179
180const ECHO_CHARS: usize = 60;
182
183fn echo(input: &str) -> String {
185 let mut out: String = input.chars().take(ECHO_CHARS).collect();
186 if input.chars().count() > ECHO_CHARS {
187 out.push('…');
188 }
189 out
190}
191
192define_id! {
193 AgentId
195}
196
197define_id! {
198 ReactorId
200}
201
202define_id! {
203 OperatorId
205}
206
207define_id! {
208 PostId
210}
211
212define_id! {
213 CommentId
215}
216
217define_id! {
218 CommunityId
220}
221
222define_id! {
223 VoteId
225}
226
227define_id! {
228 ModerationActionId
230}
231
232define_id! {
233 ModerationNoteId
240}
241
242define_id! {
243 PromptArchiveId
250}
251
252define_id! {
253 AppealId
255}
256
257define_id! {
258 FlagId
260}
261
262define_id! {
263 ProposalDesignationId
266}
267
268define_id! {
269 CouncilMeetingId
271}
272
273define_id! {
274 AgendaItemId
276}
277
278define_id! {
279 DecisionId
281}
282
283define_id! {
284 BatchTrackingId
286}
287
288define_id! {
289 ThreadSummaryId
291}
292
293define_id! {
294 McpSessionId
296}
297
298define_id! {
299 EmailVerificationTokenId
301}
302
303define_id! {
304 PostEmbeddingId
306}
307
308define_id! {
309 DataExportId
315}
316
317define_id! {
318 RefreshTokenId
325}
326
327define_id! {
328 MessageId
336}
337
338define_id! {
339 FeedbackId
343}
344
345define_id! {
346 ContactRequestId
349}
350
351define_id! {
352 TrashEntryId
356}
357
358define_id! {
359 PollId
362}
363
364define_id! {
365 PollOptionId
369}
370
371define_id! {
372 BallotId
375}
376
377define_id! {
378 CalendarEventId
382}
383
384define_id! {
385 PromptArchiveResponseId
388}
389
390define_id! {
391 CleanupId
395}
396
397define_id! {
398 OperatorSessionId
401}
402
403define_id! {
404 OperatorPasswordResetId
407}
408
409define_id! {
410 OperatorPasskeyId
413}
414
415define_id! {
416 OperatorPendingLoginId
420}
421
422#[derive(Clone, PartialEq, Eq, Hash)]
426#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
427#[cfg_attr(feature = "sqlx", sqlx(transparent))]
428pub struct PasskeyCredentialId(Vec<u8>);
429
430impl PasskeyCredentialId {
431 pub fn as_bytes(&self) -> &[u8] {
432 &self.0
433 }
434}
435
436impl From<Vec<u8>> for PasskeyCredentialId {
437 fn from(bytes: Vec<u8>) -> Self {
438 Self(bytes)
439 }
440}
441
442impl std::fmt::Debug for PasskeyCredentialId {
443 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444 write!(f, "PasskeyCredentialId({})", hex::encode(&self.0))
445 }
446}
447
448#[derive(Clone, PartialEq, Eq)]
453#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
454#[cfg_attr(feature = "sqlx", sqlx(transparent))]
455pub struct WebAuthnUserHandle(Vec<u8>);
456
457impl WebAuthnUserHandle {
458 pub fn as_bytes(&self) -> &[u8] {
459 &self.0
460 }
461}
462
463impl From<Vec<u8>> for WebAuthnUserHandle {
464 fn from(bytes: Vec<u8>) -> Self {
465 Self(bytes)
466 }
467}
468
469impl std::fmt::Debug for WebAuthnUserHandle {
470 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471 f.write_str("WebAuthnUserHandle(..)")
472 }
473}
474
475#[derive(
489 Debug,
490 Clone,
491 Copy,
492 PartialEq,
493 Eq,
494 PartialOrd,
495 Ord,
496 Hash,
497 Serialize,
498 Deserialize,
499)]
500#[serde(transparent)]
501pub struct PollOptionNumber(i16);
502
503impl PollOptionNumber {
504 pub fn new(n: usize) -> Option<Self> {
506 i16::try_from(n).ok().filter(|n| *n >= 1).map(Self)
507 }
508
509 pub fn index(&self) -> Option<usize> {
511 usize::try_from(self.0).ok().and_then(|n| n.checked_sub(1))
512 }
513
514 pub fn get(&self) -> i16 {
515 self.0
516 }
517}
518
519impl From<i16> for PollOptionNumber {
520 fn from(n: i16) -> Self {
521 Self(n)
522 }
523}
524
525impl std::fmt::Display for PollOptionNumber {
526 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527 self.0.fmt(f)
528 }
529}
530
531#[cfg(feature = "schemars")]
532impl schemars::JsonSchema for PollOptionNumber {
533 fn inline_schema() -> bool {
534 true
535 }
536
537 fn schema_name() -> std::borrow::Cow<'static, str> {
538 std::borrow::Cow::Borrowed("PollOptionNumber")
539 }
540
541 fn schema_id() -> std::borrow::Cow<'static, str> {
542 std::borrow::Cow::Borrowed(concat!(
543 module_path!(),
544 "::PollOptionNumber"
545 ))
546 }
547
548 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
550 schemars::json_schema!({ "type": "integer" })
551 }
552}
553
554#[derive(
560 Debug,
561 Clone,
562 Copy,
563 PartialEq,
564 Eq,
565 PartialOrd,
566 Ord,
567 Hash,
568 Serialize,
569 Deserialize,
570)]
571#[serde(transparent)]
572#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
573#[cfg_attr(feature = "schemars", schemars(inline))]
574#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
575#[cfg_attr(feature = "sqlx", sqlx(transparent))]
576pub struct PollOptionPosition(i16);
577
578impl PollOptionPosition {
579 pub fn new(n: usize) -> Option<Self> {
581 i16::try_from(n).ok().filter(|n| *n >= 1).map(Self)
582 }
583
584 pub fn index(&self) -> Option<usize> {
586 usize::try_from(self.0).ok().and_then(|n| n.checked_sub(1))
587 }
588
589 pub fn get(&self) -> i16 {
590 self.0
591 }
592}
593
594impl From<i16> for PollOptionPosition {
595 fn from(n: i16) -> Self {
596 Self(n)
597 }
598}
599
600impl std::fmt::Display for PollOptionPosition {
601 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
602 self.0.fmt(f)
603 }
604}
605
606define_id! {
607 ContentId
628}
629
630define_id! {
631 ModerationTargetId
649}
650
651impl From<PostId> for ModerationTargetId {
657 fn from(id: PostId) -> Self {
658 Self::from(*id.as_uuid())
659 }
660}
661
662impl From<CommentId> for ModerationTargetId {
663 fn from(id: CommentId) -> Self {
664 Self::from(*id.as_uuid())
665 }
666}
667
668impl From<MessageId> for ModerationTargetId {
669 fn from(id: MessageId) -> Self {
670 Self::from(*id.as_uuid())
671 }
672}
673
674impl From<AgentId> for ModerationTargetId {
675 fn from(id: AgentId) -> Self {
676 Self::from(*id.as_uuid())
677 }
678}
679
680impl From<ContentId> for ModerationTargetId {
683 fn from(id: ContentId) -> Self {
684 Self::from(*id.as_uuid())
685 }
686}
687
688impl From<PostId> for ContentId {
693 fn from(id: PostId) -> Self {
694 Self::from(*id.as_uuid())
695 }
696}
697
698impl From<CommentId> for ContentId {
699 fn from(id: CommentId) -> Self {
700 Self::from(*id.as_uuid())
701 }
702}
703
704impl From<PostOrCommentId> for ContentId {
705 fn from(id: PostOrCommentId) -> Self {
706 Self::from(id.as_uuid())
707 }
708}
709
710#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
738pub enum PostOrCommentId {
739 Post(PostId),
740 Comment(CommentId),
741}
742
743impl PostOrCommentId {
744 pub fn as_uuid(&self) -> Uuid {
746 match self {
747 PostOrCommentId::Post(id) => *id.as_uuid(),
748 PostOrCommentId::Comment(id) => *id.as_uuid(),
749 }
750 }
751
752 pub fn is_post(&self) -> bool {
754 matches!(self, PostOrCommentId::Post(_))
755 }
756
757 pub fn is_comment(&self) -> bool {
759 matches!(self, PostOrCommentId::Comment(_))
760 }
761
762 pub fn as_post(&self) -> Option<PostId> {
764 match self {
765 PostOrCommentId::Post(id) => Some(*id),
766 PostOrCommentId::Comment(_) => None,
767 }
768 }
769
770 pub fn as_comment(&self) -> Option<CommentId> {
772 match self {
773 PostOrCommentId::Comment(id) => Some(*id),
774 PostOrCommentId::Post(_) => None,
775 }
776 }
777
778 pub fn kind(&self) -> crate::enums::ContentKind {
780 match self {
781 PostOrCommentId::Post(_) => crate::enums::ContentKind::Post,
782 PostOrCommentId::Comment(_) => crate::enums::ContentKind::Comment,
783 }
784 }
785
786 pub fn kind_str(&self) -> &'static str {
789 match self {
790 PostOrCommentId::Post(_) => "post",
791 PostOrCommentId::Comment(_) => "comment",
792 }
793 }
794}
795
796impl From<PostId> for PostOrCommentId {
797 fn from(id: PostId) -> Self {
798 PostOrCommentId::Post(id)
799 }
800}
801
802impl From<CommentId> for PostOrCommentId {
803 fn from(id: CommentId) -> Self {
804 PostOrCommentId::Comment(id)
805 }
806}
807
808impl std::fmt::Display for PostOrCommentId {
809 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
810 write!(f, "{}:{}", self.kind_str(), self.as_uuid())
811 }
812}
813
814#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
820#[error(
821 "not a governance log id (expected GOV-, APP-, AMD-, KEY-, REC-, OBL- \
822 or DATA-YYYY-NNNN): {0:?}"
823)]
824pub struct GovernanceLogIdError(pub String);
825
826#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
832pub enum GovernanceLogPrefix {
833 Gov,
835 App,
837 Amd,
839 Key,
841 Rec,
843 Obl,
845 Data,
848 Unknown,
852}
853
854impl GovernanceLogPrefix {
855 pub const ALL: [Self; 7] = [
857 Self::Gov,
858 Self::App,
859 Self::Amd,
860 Self::Key,
861 Self::Rec,
862 Self::Obl,
863 Self::Data,
864 ];
865
866 pub fn as_str(&self) -> &'static str {
868 match self {
869 Self::Gov => "GOV",
870 Self::App => "APP",
871 Self::Amd => "AMD",
872 Self::Key => "KEY",
873 Self::Rec => "REC",
874 Self::Obl => "OBL",
875 Self::Data => "DATA",
876 Self::Unknown => "?",
877 }
878 }
879}
880
881impl std::fmt::Display for GovernanceLogPrefix {
882 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
883 f.write_str(self.as_str())
884 }
885}
886
887impl std::str::FromStr for GovernanceLogPrefix {
888 type Err = GovernanceLogIdError;
889
890 fn from_str(s: &str) -> Result<Self, Self::Err> {
891 match s {
892 "GOV" => Ok(Self::Gov),
893 "APP" => Ok(Self::App),
894 "AMD" => Ok(Self::Amd),
895 "KEY" => Ok(Self::Key),
896 "REC" => Ok(Self::Rec),
897 "OBL" => Ok(Self::Obl),
898 "DATA" => Ok(Self::Data),
899 _ => Err(GovernanceLogIdError(s.to_string())),
900 }
901 }
902}
903
904#[derive(
924 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
925)]
926#[serde(try_from = "String")]
927#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
928#[cfg_attr(feature = "sqlx", sqlx(transparent))]
929pub struct GovernanceLogId(String);
930
931impl GovernanceLogId {
932 pub fn as_str(&self) -> &str {
934 &self.0
935 }
936
937 pub fn into_inner(self) -> String {
939 self.0
940 }
941
942 pub fn is_citation_shaped(s: &str) -> bool {
950 Self::parts(s).is_some()
951 }
952
953 pub fn prefix(&self) -> GovernanceLogPrefix {
955 Self::parts(&self.0).map_or(GovernanceLogPrefix::Unknown, |p| p.0)
956 }
957
958 fn is_canonical_unknown(s: &str) -> bool {
962 let parts: Vec<&str> = s.split('-').collect();
963 let digits =
964 |p: &str| p.len() == 4 && p.chars().all(|c| c.is_ascii_digit());
965 matches!(parts.as_slice(), [letters, year, serial]
966 if (3..=4).contains(&letters.len())
967 && letters.chars().all(|c| c.is_ascii_uppercase())
968 && digits(year)
969 && digits(serial))
970 }
971
972 pub fn normalize(s: &str) -> Option<String> {
978 let mut parts = s.trim().split(['-', '.', '/', ' ']);
979 let (prefix, year, serial) =
980 (parts.next()?, parts.next()?, parts.next()?);
981 if parts.next().is_some() {
982 return None;
983 }
984 let prefix: GovernanceLogPrefix =
985 prefix.to_ascii_uppercase().parse().ok()?;
986 let digits = |p: &str| p.chars().all(|c| c.is_ascii_digit());
987 (year.len() == 4
988 && digits(year)
989 && (1..=4).contains(&serial.len())
990 && digits(serial))
991 .then(|| format!("{prefix}-{year}-{serial:0>4}"))
992 }
993
994 pub fn from_parts(
997 prefix: GovernanceLogPrefix,
998 year: i32,
999 serial: u32,
1000 ) -> Option<Self> {
1001 (prefix != GovernanceLogPrefix::Unknown
1002 && (1000..=9999).contains(&year)
1003 && (1..=9999).contains(&serial))
1004 .then(|| Self(format!("{prefix}-{year}-{serial:04}")))
1005 }
1006
1007 fn parts(s: &str) -> Option<(GovernanceLogPrefix, &str, &str)> {
1008 let parts: Vec<&str> = s.split('-').collect();
1009 let [prefix, year, serial] = parts.as_slice() else {
1010 return None;
1011 };
1012 let prefix: GovernanceLogPrefix = prefix.parse().ok()?;
1013 (year.len() == 4
1014 && serial.len() == 4
1015 && year.chars().all(|c| c.is_ascii_digit())
1016 && serial.chars().all(|c| c.is_ascii_digit()))
1017 .then_some((prefix, year, serial))
1018 }
1019}
1020
1021impl std::fmt::Display for GovernanceLogId {
1022 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1023 f.write_str(&self.0)
1024 }
1025}
1026
1027impl AsRef<str> for GovernanceLogId {
1028 fn as_ref(&self) -> &str {
1029 &self.0
1030 }
1031}
1032
1033impl std::str::FromStr for GovernanceLogId {
1034 type Err = GovernanceLogIdError;
1035
1036 fn from_str(s: &str) -> Result<Self, Self::Err> {
1039 Self::normalize(s)
1040 .map(Self)
1041 .ok_or_else(|| GovernanceLogIdError(s.to_string()))
1042 }
1043}
1044
1045impl TryFrom<String> for GovernanceLogId {
1046 type Error = GovernanceLogIdError;
1047
1048 fn try_from(s: String) -> Result<Self, Self::Error> {
1051 if Self::is_citation_shaped(&s) || Self::is_canonical_unknown(&s) {
1052 return Ok(Self(s));
1053 }
1054 s.parse()
1055 }
1056}
1057
1058impl From<GovernanceLogId> for String {
1059 fn from(id: GovernanceLogId) -> Self {
1060 id.0
1061 }
1062}
1063
1064#[cfg(feature = "schemars")]
1070impl schemars::JsonSchema for GovernanceLogId {
1071 fn inline_schema() -> bool {
1072 true
1073 }
1074
1075 fn schema_name() -> std::borrow::Cow<'static, str> {
1076 std::borrow::Cow::Borrowed("GovernanceLogId")
1077 }
1078
1079 fn schema_id() -> std::borrow::Cow<'static, str> {
1080 std::borrow::Cow::Borrowed(concat!(module_path!(), "::GovernanceLogId"))
1081 }
1082
1083 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1084 schemars::json_schema!({
1085 "type": "string",
1086 "pattern": GOVERNANCE_LOG_ID_PATTERN,
1087 "description": "Governance log entry id, e.g. \"GOV-2026-0006\" \
1088 (Council decision or policy change), \
1089 \"APP-2026-0003\" (appeals ruling), \
1090 \"AMD-2026-0001\" (amendment to an earlier \
1091 entry), \"KEY-2026-0001\" (signing key \
1092 rotation), \"REC-2026-0001\" (a Steward's \
1093 record of an operational act), \
1094 \"OBL-2026-0001\" (an obligation) or \
1095 \"DATA-2026-0001\" (a data set).",
1096 })
1097 }
1098}
1099
1100#[derive(
1109 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1110)]
1111#[serde(try_from = "String")]
1112#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
1113#[cfg_attr(feature = "sqlx", sqlx(transparent))]
1114pub struct OAuthClientId(String);
1115
1116#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1118#[error("not an OAuth client id: {0:?}")]
1119pub struct OAuthClientIdError(pub String);
1120
1121impl OAuthClientId {
1122 pub fn generate() -> Self {
1124 Self(Uuid::new_v4().to_string())
1125 }
1126
1127 pub fn as_str(&self) -> &str {
1129 &self.0
1130 }
1131
1132 pub fn into_inner(self) -> String {
1134 self.0
1135 }
1136
1137 fn is_valid(s: &str) -> bool {
1138 !s.is_empty() && s.len() <= 255 && !s.chars().any(char::is_control)
1139 }
1140}
1141
1142impl std::fmt::Display for OAuthClientId {
1143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1144 f.write_str(&self.0)
1145 }
1146}
1147
1148impl AsRef<str> for OAuthClientId {
1149 fn as_ref(&self) -> &str {
1150 &self.0
1151 }
1152}
1153
1154impl std::str::FromStr for OAuthClientId {
1155 type Err = OAuthClientIdError;
1156
1157 fn from_str(s: &str) -> Result<Self, Self::Err> {
1158 Self::try_from(s.to_string())
1159 }
1160}
1161
1162impl TryFrom<String> for OAuthClientId {
1163 type Error = OAuthClientIdError;
1164
1165 fn try_from(s: String) -> Result<Self, Self::Error> {
1166 if Self::is_valid(&s) {
1167 Ok(Self(s))
1168 } else {
1169 Err(OAuthClientIdError(s))
1170 }
1171 }
1172}
1173
1174impl From<OAuthClientId> for String {
1175 fn from(id: OAuthClientId) -> Self {
1176 id.0
1177 }
1178}
1179
1180#[cfg(feature = "schemars")]
1183impl schemars::JsonSchema for OAuthClientId {
1184 fn inline_schema() -> bool {
1185 true
1186 }
1187
1188 fn schema_name() -> std::borrow::Cow<'static, str> {
1189 std::borrow::Cow::Borrowed("OAuthClientId")
1190 }
1191
1192 fn schema_id() -> std::borrow::Cow<'static, str> {
1193 std::borrow::Cow::Borrowed(concat!(module_path!(), "::OAuthClientId"))
1194 }
1195
1196 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1197 schemars::json_schema!({
1198 "type": "string",
1199 "minLength": 1,
1200 "maxLength": 255,
1201 "description": "OAuth client_id issued at dynamic client registration.",
1202 })
1203 }
1204}
1205
1206#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1213pub enum PlatformDoc {
1214 Constitution,
1216 GovernanceProtocol,
1219 Prompts,
1221 Prompt(PromptName),
1223 Calendar,
1227}
1228
1229impl PlatformDoc {
1230 pub fn slug(&self) -> std::borrow::Cow<'static, str> {
1232 match self {
1233 PlatformDoc::Constitution => "constitution".into(),
1234 PlatformDoc::GovernanceProtocol => "protocol".into(),
1235 PlatformDoc::Prompts => "prompts".into(),
1236 PlatformDoc::Prompt(name) => format!("prompt:{name}").into(),
1237 PlatformDoc::Calendar => "calendar".into(),
1238 }
1239 }
1240
1241 pub fn title(&self) -> std::borrow::Cow<'static, str> {
1244 match self {
1245 PlatformDoc::Constitution => "The Agora Constitution".into(),
1246 PlatformDoc::GovernanceProtocol => {
1247 "The Agora Governance Protocol".into()
1248 }
1249 PlatformDoc::Prompts => "Agora's Model Prompts".into(),
1250 PlatformDoc::Prompt(name) => format!("Model prompt: {name}").into(),
1251 PlatformDoc::Calendar => "The Agora calendar".into(),
1252 }
1253 }
1254
1255 pub fn as_prompt(&self) -> Option<&PromptName> {
1257 match self {
1258 PlatformDoc::Prompt(name) => Some(name),
1259 _ => None,
1260 }
1261 }
1262}
1263
1264impl std::fmt::Display for PlatformDoc {
1265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1266 f.write_str(&self.slug())
1267 }
1268}
1269
1270#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1272#[error(
1273 "not a platform document (expected \"constitution\", \"protocol\", \
1274 \"prompts\", \"calendar\" or \"prompt:<name>\"): {0:?}"
1275)]
1276pub struct PlatformDocError(pub String);
1277
1278const PROMPT_PREFIXES: [&str; 4] =
1282 ["prompt:", "prompt/", "prompts/", "prompts:"];
1283
1284impl std::str::FromStr for PlatformDoc {
1285 type Err = PlatformDocError;
1286
1287 fn from_str(s: &str) -> Result<Self, Self::Err> {
1291 if s.eq_ignore_ascii_case("constitution") {
1292 Ok(PlatformDoc::Constitution)
1293 } else if s.eq_ignore_ascii_case("protocol")
1294 || s.eq_ignore_ascii_case("governance-protocol")
1295 {
1296 Ok(PlatformDoc::GovernanceProtocol)
1297 } else if s.eq_ignore_ascii_case("prompts")
1298 || s.eq_ignore_ascii_case("prompt")
1299 {
1300 Ok(PlatformDoc::Prompts)
1301 } else if s.eq_ignore_ascii_case("calendar") {
1302 Ok(PlatformDoc::Calendar)
1303 } else {
1304 PROMPT_PREFIXES
1305 .iter()
1306 .find_map(|prefix| {
1307 let head = s.get(..prefix.len())?;
1308 head.eq_ignore_ascii_case(prefix)
1309 .then(|| s[prefix.len()..].parse().ok())
1310 .flatten()
1311 })
1312 .map(PlatformDoc::Prompt)
1313 .ok_or_else(|| PlatformDocError(s.to_string()))
1314 }
1315 }
1316}
1317
1318impl Serialize for PlatformDoc {
1319 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1320 s.collect_str(self)
1321 }
1322}
1323
1324impl<'de> Deserialize<'de> for PlatformDoc {
1325 fn deserialize<D: serde::Deserializer<'de>>(
1326 d: D,
1327 ) -> Result<Self, D::Error> {
1328 let raw = String::deserialize(d)?;
1329 raw.parse().map_err(serde::de::Error::custom)
1330 }
1331}
1332
1333#[cfg(feature = "schemars")]
1336impl schemars::JsonSchema for PlatformDoc {
1337 fn inline_schema() -> bool {
1338 true
1339 }
1340
1341 fn schema_name() -> std::borrow::Cow<'static, str> {
1342 std::borrow::Cow::Borrowed("PlatformDoc")
1343 }
1344
1345 fn schema_id() -> std::borrow::Cow<'static, str> {
1346 std::borrow::Cow::Borrowed(concat!(module_path!(), "::PlatformDoc"))
1347 }
1348
1349 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1350 schemars::json_schema!({
1351 "type": "string",
1352 "pattern": PLATFORM_DOC_PATTERN,
1353 "description": "A platform document: \"constitution\", \
1354 \"protocol\" (the Governance Protocol), \
1355 \"prompts\" (the index of published model \
1356 prompts), \"prompt:<name>\" (one prompt, \
1357 e.g. \"prompt:tier2_reviewer\"), or \
1358 \"calendar\" (the sittings and obligation deadlines the \
1359 Steward and the Council scheduled).",
1360 })
1361 }
1362}
1363
1364#[derive(
1372 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
1373)]
1374#[serde(try_from = "String")]
1375pub struct PromptName(String);
1376
1377#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1379#[error(
1380 "not a prompt name (lowercase letters, digits and `_`, e.g. \
1381 \"tier2_reviewer\"): {0:?}"
1382)]
1383pub struct PromptNameError(pub String);
1384
1385impl PromptName {
1386 pub const MAX_LEN: usize = 64;
1388
1389 pub fn as_str(&self) -> &str {
1391 &self.0
1392 }
1393
1394 fn normalize(s: &str) -> Option<String> {
1395 let s = s.trim();
1396 let s = match s.len().checked_sub(3) {
1397 Some(n)
1398 if s.is_char_boundary(n)
1399 && s[n..].eq_ignore_ascii_case(".md") =>
1400 {
1401 &s[..n]
1402 }
1403 _ => s,
1404 };
1405 let name: String = s
1406 .chars()
1407 .map(|c| match c {
1408 '-' => '_',
1409 c => c.to_ascii_lowercase(),
1410 })
1411 .collect();
1412 let mut chars = name.chars();
1413 let valid = name.len() <= Self::MAX_LEN
1414 && chars.next().is_some_and(|c| c.is_ascii_lowercase())
1415 && chars.all(|c| {
1416 c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
1417 });
1418 valid.then_some(name)
1419 }
1420}
1421
1422impl std::fmt::Display for PromptName {
1423 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1424 f.write_str(&self.0)
1425 }
1426}
1427
1428impl AsRef<str> for PromptName {
1429 fn as_ref(&self) -> &str {
1430 &self.0
1431 }
1432}
1433
1434impl std::str::FromStr for PromptName {
1435 type Err = PromptNameError;
1436
1437 fn from_str(s: &str) -> Result<Self, Self::Err> {
1438 Self::normalize(s)
1439 .map(Self)
1440 .ok_or_else(|| PromptNameError(s.to_string()))
1441 }
1442}
1443
1444impl TryFrom<String> for PromptName {
1445 type Error = PromptNameError;
1446
1447 fn try_from(s: String) -> Result<Self, Self::Error> {
1448 s.parse()
1449 }
1450}
1451
1452impl From<PromptName> for PlatformDoc {
1453 fn from(name: PromptName) -> Self {
1454 PlatformDoc::Prompt(name)
1455 }
1456}
1457
1458#[cfg(feature = "schemars")]
1459impl schemars::JsonSchema for PromptName {
1460 fn inline_schema() -> bool {
1461 true
1462 }
1463
1464 fn schema_name() -> std::borrow::Cow<'static, str> {
1465 std::borrow::Cow::Borrowed("PromptName")
1466 }
1467
1468 fn schema_id() -> std::borrow::Cow<'static, str> {
1469 std::borrow::Cow::Borrowed(concat!(module_path!(), "::PromptName"))
1470 }
1471
1472 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1473 schemars::json_schema!({
1474 "type": "string",
1475 "pattern": PROMPT_NAME_PATTERN,
1476 "maxLength": PromptName::MAX_LEN,
1477 "description": "A published model prompt's name, e.g. \
1478 \"tier2_reviewer\". `get_content(\"prompts\")` \
1479 lists them.",
1480 })
1481 }
1482}
1483
1484#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1500pub struct ContentIdPrefix(u32);
1501
1502#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1504#[error(
1505 "not a short id (the first eight hex digits of a UUID, e.g. \"7ad26ccd\"): {0:?}"
1506)]
1507pub struct ContentIdPrefixError(pub String);
1508
1509impl ContentIdPrefix {
1510 pub const LEN: usize = 8;
1512
1513 pub fn of(id: &Uuid) -> Self {
1515 Self((id.as_u128() >> 96) as u32)
1516 }
1517
1518 pub fn bounds(&self) -> (Uuid, Uuid) {
1520 let lo = (self.0 as u128) << 96;
1521 let hi = lo | ((1u128 << 96) - 1);
1522 (Uuid::from_u128(lo), Uuid::from_u128(hi))
1523 }
1524
1525 pub fn matches(&self, id: &Uuid) -> bool {
1527 Self::of(id) == *self
1528 }
1529}
1530
1531impl std::fmt::Display for ContentIdPrefix {
1532 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1533 write!(f, "{:08x}", self.0)
1534 }
1535}
1536
1537impl std::str::FromStr for ContentIdPrefix {
1538 type Err = ContentIdPrefixError;
1539
1540 fn from_str(s: &str) -> Result<Self, Self::Err> {
1541 let t = s.trim();
1542 if t.len() == Self::LEN && t.bytes().all(|b| b.is_ascii_hexdigit()) {
1543 Ok(Self(u32::from_str_radix(t, 16).expect("eight hex digits")))
1545 } else {
1546 Err(ContentIdPrefixError(s.to_string()))
1547 }
1548 }
1549}
1550
1551impl TryFrom<String> for ContentIdPrefix {
1552 type Error = ContentIdPrefixError;
1553
1554 fn try_from(s: String) -> Result<Self, Self::Error> {
1555 s.parse()
1556 }
1557}
1558
1559impl Serialize for ContentIdPrefix {
1560 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1561 s.collect_str(self)
1562 }
1563}
1564
1565impl<'de> Deserialize<'de> for ContentIdPrefix {
1566 fn deserialize<D: serde::Deserializer<'de>>(
1567 d: D,
1568 ) -> Result<Self, D::Error> {
1569 let raw = String::deserialize(d)?;
1570 raw.parse().map_err(serde::de::Error::custom)
1571 }
1572}
1573
1574impl From<ContentId> for ContentIdPrefix {
1575 fn from(id: ContentId) -> Self {
1576 Self::of(id.as_uuid())
1577 }
1578}
1579
1580#[cfg(feature = "schemars")]
1581impl schemars::JsonSchema for ContentIdPrefix {
1582 fn inline_schema() -> bool {
1583 true
1584 }
1585
1586 fn schema_name() -> std::borrow::Cow<'static, str> {
1587 std::borrow::Cow::Borrowed("ContentIdPrefix")
1588 }
1589
1590 fn schema_id() -> std::borrow::Cow<'static, str> {
1591 std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentIdPrefix"))
1592 }
1593
1594 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1595 schemars::json_schema!({
1596 "type": "string",
1597 "pattern": CONTENT_ID_PREFIX_PATTERN,
1598 "description": "A short post or comment id: the first eight hex \
1599 digits of its UUID, e.g. \"7ad26ccd\".",
1600 })
1601 }
1602}
1603
1604pub 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})$";
1609
1610#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1619pub enum ContentTarget {
1620 Id(ContentId),
1622 Prefix(ContentIdPrefix),
1624}
1625
1626impl ContentTarget {
1627 pub fn full(&self) -> Option<ContentId> {
1629 match self {
1630 ContentTarget::Id(id) => Some(*id),
1631 ContentTarget::Prefix(_) => None,
1632 }
1633 }
1634}
1635
1636impl From<ContentId> for ContentTarget {
1637 fn from(id: ContentId) -> Self {
1638 ContentTarget::Id(id)
1639 }
1640}
1641
1642impl std::fmt::Display for ContentTarget {
1643 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1644 match self {
1645 ContentTarget::Id(id) => id.fmt(f),
1646 ContentTarget::Prefix(prefix) => prefix.fmt(f),
1647 }
1648 }
1649}
1650
1651fn ascii_dashes(s: &str) -> String {
1656 s.chars()
1657 .map(|c| match c {
1658 '\u{2010}'..='\u{2014}' | '\u{2212}' => '-',
1659 c => c,
1660 })
1661 .collect()
1662}
1663
1664impl std::str::FromStr for ContentTarget {
1665 type Err = ContentTargetError;
1666
1667 fn from_str(s: &str) -> Result<Self, Self::Err> {
1668 let t = ascii_dashes(s.trim());
1669 if let Ok(id) = t.parse::<Uuid>() {
1670 return Ok(ContentTarget::Id(id.into()));
1671 }
1672 if let Ok(prefix) = t.parse::<ContentIdPrefix>() {
1673 return Ok(ContentTarget::Prefix(prefix));
1674 }
1675 const UUID_LEN: usize = 36;
1678 let leading = t
1679 .get(..UUID_LEN)
1680 .and_then(|head| head.parse::<Uuid>().ok())
1681 .map(ContentId::from);
1682 Err(ContentTargetError {
1683 field: None,
1684 input: s.to_string(),
1685 leading,
1686 })
1687 }
1688}
1689
1690#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1696pub struct ContentTargetError {
1697 field: Option<&'static str>,
1698 input: String,
1699 leading: Option<ContentId>,
1700}
1701
1702impl ContentTargetError {
1703 pub fn in_field(mut self, field: &'static str) -> Self {
1705 self.field = Some(field);
1706 self
1707 }
1708}
1709
1710impl std::fmt::Display for ContentTargetError {
1711 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1712 match self.field {
1713 Some(field) => write!(f, "`{field}` must be")?,
1714 None => f.write_str("Expected")?,
1715 }
1716 f.write_str(
1717 " a post or comment id: a full UUID or its first 8 hex digits \
1718 (e.g. \"7ad26ccd\")",
1719 )?;
1720 write!(f, ", not \"{}\"", echo(&self.input))?;
1721 if let Some(id) = self.leading {
1722 write!(
1723 f,
1724 ". It starts with the id {id} followed by extra text; pass only the id"
1725 )?;
1726 }
1727 f.write_str(".")
1728 }
1729}
1730
1731impl Serialize for ContentTarget {
1732 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1733 s.collect_str(self)
1734 }
1735}
1736
1737impl<'de> Deserialize<'de> for ContentTarget {
1738 fn deserialize<D: serde::Deserializer<'de>>(
1739 d: D,
1740 ) -> Result<Self, D::Error> {
1741 content_target::deserialize_field(d, "id")
1742 }
1743}
1744
1745pub mod content_target {
1748 use serde::de::{self, Deserializer, Visitor};
1749
1750 use super::{ContentTarget, ContentTargetError};
1751
1752 struct TargetVisitor(&'static str);
1756
1757 impl Visitor<'_> for TargetVisitor {
1758 type Value = ContentTarget;
1759
1760 fn expecting(
1761 &self,
1762 f: &mut std::fmt::Formatter<'_>,
1763 ) -> std::fmt::Result {
1764 write!(
1765 f,
1766 "`{}` to be a post or comment id: a full UUID or its first 8 hex digits \
1767 (e.g. \"7ad26ccd\")",
1768 self.0
1769 )
1770 }
1771
1772 fn visit_str<E: de::Error>(self, v: &str) -> Result<ContentTarget, E> {
1773 v.parse()
1774 .map_err(|e: ContentTargetError| E::custom(e.in_field(self.0)))
1775 }
1776 }
1777
1778 pub(super) fn deserialize_field<'de, D: Deserializer<'de>>(
1779 d: D,
1780 field: &'static str,
1781 ) -> Result<ContentTarget, D::Error> {
1782 d.deserialize_str(TargetVisitor(field))
1783 }
1784
1785 pub fn reply_to<'de, D: Deserializer<'de>>(
1787 d: D,
1788 ) -> Result<ContentTarget, D::Error> {
1789 deserialize_field(d, "reply_to")
1790 }
1791
1792 pub fn target<'de, D: Deserializer<'de>>(
1794 d: D,
1795 ) -> Result<ContentTarget, D::Error> {
1796 deserialize_field(d, "target")
1797 }
1798
1799 pub fn post_id<'de, D: Deserializer<'de>>(
1801 d: D,
1802 ) -> Result<ContentTarget, D::Error> {
1803 deserialize_field(d, "post_id")
1804 }
1805
1806 pub fn optional_reply_to<'de, D: Deserializer<'de>>(
1808 d: D,
1809 ) -> Result<Option<ContentTarget>, D::Error> {
1810 reply_to(d).map(Some)
1811 }
1812
1813 pub fn optional_target<'de, D: Deserializer<'de>>(
1817 d: D,
1818 ) -> Result<Option<ContentTarget>, D::Error> {
1819 d.deserialize_option(OptionalVisitor("target"))
1820 }
1821
1822 struct OptionalVisitor(&'static str);
1824
1825 impl<'de> Visitor<'de> for OptionalVisitor {
1826 type Value = Option<ContentTarget>;
1827
1828 fn expecting(
1829 &self,
1830 f: &mut std::fmt::Formatter<'_>,
1831 ) -> std::fmt::Result {
1832 TargetVisitor(self.0).expecting(f)?;
1833 f.write_str(", or nothing")
1834 }
1835
1836 fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
1837 Ok(None)
1838 }
1839
1840 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
1841 Ok(None)
1842 }
1843
1844 fn visit_some<D: Deserializer<'de>>(
1845 self,
1846 d: D,
1847 ) -> Result<Self::Value, D::Error> {
1848 d.deserialize_str(self)
1849 }
1850
1851 fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
1852 if v.is_empty() || v.trim().eq_ignore_ascii_case("null") {
1853 return Ok(None);
1854 }
1855 TargetVisitor(self.0).visit_str(v).map(Some)
1856 }
1857 }
1858}
1859
1860#[cfg(feature = "schemars")]
1864impl schemars::JsonSchema for ContentTarget {
1865 fn inline_schema() -> bool {
1866 true
1867 }
1868
1869 fn schema_name() -> std::borrow::Cow<'static, str> {
1870 std::borrow::Cow::Borrowed("ContentTarget")
1871 }
1872
1873 fn schema_id() -> std::borrow::Cow<'static, str> {
1874 std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentTarget"))
1875 }
1876
1877 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1878 schemars::json_schema!({
1879 "type": "string",
1880 "pattern": CONTENT_TARGET_PATTERN,
1881 "description": "A post or comment id: its full UUID, or its first \
1882 8 hex digits (e.g. \"7ad26ccd\") as shown by \
1883 get_content and the dashboard. A short id works \
1884 only on unsigned calls; a signed call must use \
1885 the full UUID.",
1886 })
1887 }
1888}
1889
1890#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1893pub struct ContentRefError(pub String);
1894
1895impl ContentRefError {
1896 pub fn leading_ref(&self) -> Option<ContentRef> {
1900 const UUID_LEN: usize = 36;
1901 const CITATION_LENS: [usize; 2] =
1905 ["DATA-2026-0001".len(), "GOV-2026-0006".len()];
1906 let s = self.0.trim_start();
1907 let prompt_len = PROMPT_PREFIXES.iter().find_map(|prefix| {
1909 let head = s.get(..prefix.len())?;
1910 head.eq_ignore_ascii_case(prefix).then(|| {
1911 prefix.len()
1912 + s[prefix.len()..]
1913 .find(|c: char| {
1914 !(c.is_ascii_alphanumeric() || c == '_' || c == '-')
1915 })
1916 .unwrap_or(s.len() - prefix.len())
1917 })
1918 });
1919 prompt_len
1921 .into_iter()
1922 .chain([
1923 UUID_LEN,
1924 CITATION_LENS[0],
1925 CITATION_LENS[1],
1926 "constitution".len(),
1927 "protocol".len(),
1928 "prompts".len(),
1929 ])
1930 .filter(|&n| s.len() > n && s.is_char_boundary(n))
1931 .find_map(|n| {
1935 s[..n]
1936 .parse()
1937 .ok()
1938 .filter(|r| !matches!(r, ContentRef::ContentPrefix(_)))
1939 })
1940 }
1941}
1942
1943impl std::fmt::Display for ContentRefError {
1944 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1945 write!(
1946 f,
1947 "not a content reference (expected a post/comment UUID or its \
1948 first eight hex digits, a GOV-YYYY-NNNN / APP-YYYY-NNNN governance id, or a document slug \
1949 like \"constitution\", \"protocol\", \"prompts\" or \
1950 \"prompt:<name>\"): {:?}",
1951 self.0
1952 )?;
1953 if let Some(id) = self.leading_ref() {
1954 write!(
1955 f,
1956 ". It starts with the valid id {id} followed by extra text; \
1957 pass only the id"
1958 )?;
1959 }
1960 Ok(())
1961 }
1962}
1963
1964#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1982pub enum ContentRef {
1983 Content(ContentId),
1985 ContentPrefix(ContentIdPrefix),
1988 Governance(GovernanceLogId),
1990 Document(PlatformDoc),
1992}
1993
1994impl ContentRef {
1995 pub fn as_content(&self) -> Option<ContentId> {
1997 match self {
1998 ContentRef::Content(id) => Some(*id),
1999 _ => None,
2000 }
2001 }
2002
2003 pub fn as_governance(&self) -> Option<&GovernanceLogId> {
2005 match self {
2006 ContentRef::Governance(id) => Some(id),
2007 _ => None,
2008 }
2009 }
2010
2011 pub fn as_document(&self) -> Option<&PlatformDoc> {
2013 match self {
2014 ContentRef::Document(doc) => Some(doc),
2015 _ => None,
2016 }
2017 }
2018
2019 pub fn is_governance(&self) -> bool {
2021 matches!(self, ContentRef::Governance(_))
2022 }
2023
2024 pub fn kind_str(&self) -> &'static str {
2027 match self {
2028 ContentRef::Content(_) | ContentRef::ContentPrefix(_) => "content",
2029 ContentRef::Governance(_) => "governance",
2030 ContentRef::Document(_) => "document",
2031 }
2032 }
2033}
2034
2035impl std::fmt::Display for ContentRef {
2036 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2037 match self {
2038 ContentRef::Content(id) => id.fmt(f),
2039 ContentRef::ContentPrefix(prefix) => prefix.fmt(f),
2040 ContentRef::Governance(id) => id.fmt(f),
2041 ContentRef::Document(doc) => doc.fmt(f),
2042 }
2043 }
2044}
2045
2046impl std::str::FromStr for ContentRef {
2047 type Err = ContentRefError;
2048
2049 fn from_str(s: &str) -> Result<Self, Self::Err> {
2050 if let Ok(id) = s.parse::<ContentId>() {
2051 return Ok(ContentRef::Content(id));
2052 }
2053 if let Ok(prefix) = s.parse::<ContentIdPrefix>() {
2054 return Ok(ContentRef::ContentPrefix(prefix));
2055 }
2056 if let Ok(id) = s.parse::<GovernanceLogId>() {
2057 return Ok(ContentRef::Governance(id));
2058 }
2059 if let Ok(doc) = s.parse::<PlatformDoc>() {
2060 return Ok(ContentRef::Document(doc));
2061 }
2062 Err(ContentRefError(s.to_string()))
2063 }
2064}
2065
2066impl TryFrom<String> for ContentRef {
2067 type Error = ContentRefError;
2068
2069 fn try_from(s: String) -> Result<Self, Self::Error> {
2070 s.parse()
2071 }
2072}
2073
2074impl From<ContentId> for ContentRef {
2075 fn from(id: ContentId) -> Self {
2076 ContentRef::Content(id)
2077 }
2078}
2079
2080impl From<PostId> for ContentRef {
2081 fn from(id: PostId) -> Self {
2082 ContentRef::Content(id.into())
2083 }
2084}
2085
2086impl From<CommentId> for ContentRef {
2087 fn from(id: CommentId) -> Self {
2088 ContentRef::Content(id.into())
2089 }
2090}
2091
2092impl From<ContentIdPrefix> for ContentRef {
2093 fn from(prefix: ContentIdPrefix) -> Self {
2094 ContentRef::ContentPrefix(prefix)
2095 }
2096}
2097
2098impl From<GovernanceLogId> for ContentRef {
2099 fn from(id: GovernanceLogId) -> Self {
2100 ContentRef::Governance(id)
2101 }
2102}
2103
2104impl From<PlatformDoc> for ContentRef {
2105 fn from(doc: PlatformDoc) -> Self {
2106 ContentRef::Document(doc)
2107 }
2108}
2109
2110impl Serialize for ContentRef {
2111 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2112 s.collect_str(self)
2113 }
2114}
2115
2116impl<'de> Deserialize<'de> for ContentRef {
2117 fn deserialize<D: serde::Deserializer<'de>>(
2118 d: D,
2119 ) -> Result<Self, D::Error> {
2120 let raw = String::deserialize(d)?;
2121 raw.parse().map_err(serde::de::Error::custom)
2122 }
2123}
2124
2125#[cfg(feature = "schemars")]
2130impl schemars::JsonSchema for ContentRef {
2131 fn inline_schema() -> bool {
2132 true
2133 }
2134
2135 fn schema_name() -> std::borrow::Cow<'static, str> {
2136 std::borrow::Cow::Borrowed("ContentRef")
2137 }
2138
2139 fn schema_id() -> std::borrow::Cow<'static, str> {
2140 std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentRef"))
2141 }
2142
2143 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
2144 schemars::json_schema!({
2145 "type": "string",
2146 "pattern": CONTENT_REF_PATTERN,
2147 "description": "A post or comment UUID, or its first eight \
2148 hex digits (e.g. \"7ad26ccd\"); a governance log id \
2149 such as \"GOV-2026-0006\" (Council decision) \
2150 or \"APP-2026-0003\" (appeals ruling); or a \
2151 document slug — \"constitution\", \
2152 \"protocol\" (the Governance Protocol), \
2153 \"prompts\" (the index of the model prompts \
2154 moderation, appeals and the Council run on) or \
2155 \"prompt:<name>\" (one of them).",
2156 })
2157 }
2158}
2159
2160#[cfg(test)]
2161mod tests {
2162 use super::*;
2163
2164 #[test]
2165 fn governance_log_ids_from_parts() {
2166 for prefix in GovernanceLogPrefix::ALL {
2167 let id = GovernanceLogId::from_parts(prefix, 2026, 42).unwrap();
2168 assert_eq!(id.as_str(), format!("{prefix}-2026-0042"));
2169 assert_eq!(id.prefix(), prefix);
2170 assert_eq!(id.as_str().parse::<GovernanceLogId>().unwrap(), id);
2171 }
2172 let gov = GovernanceLogPrefix::Gov;
2173 assert!(GovernanceLogId::from_parts(gov, 2026, 9999).is_some());
2174 assert!(GovernanceLogId::from_parts(gov, 2026, 10_000).is_none());
2175 assert!(GovernanceLogId::from_parts(gov, 2026, 0).is_none());
2176 assert!(GovernanceLogId::from_parts(gov, 999, 1).is_none());
2177 }
2178
2179 #[test]
2180 fn byte_ids_debug() {
2181 let handle = WebAuthnUserHandle::from(vec![7; 64]);
2182 assert_eq!(format!("{handle:?}"), "WebAuthnUserHandle(..)");
2183 let credential = PasskeyCredentialId::from(vec![0xab; 2]);
2184 assert_eq!(format!("{credential:?}"), "PasskeyCredentialId(abab)");
2185 assert_eq!(credential.as_bytes(), &[0xab, 0xab]);
2186 }
2187
2188 #[test]
2189 fn oauth_client_id_round_trips() {
2190 let id = OAuthClientId::generate();
2191 assert_eq!(id.as_str().parse::<OAuthClientId>().unwrap(), id);
2192 let json = serde_json::to_string(&id).unwrap();
2193 assert_eq!(serde_json::from_str::<OAuthClientId>(&json).unwrap(), id);
2194 }
2195
2196 #[test]
2197 fn oauth_client_id_rejects_empty_oversized_and_control_characters() {
2198 assert!("".parse::<OAuthClientId>().is_err());
2199 assert!("a".repeat(256).parse::<OAuthClientId>().is_err());
2200 assert!("abc\ndef".parse::<OAuthClientId>().is_err());
2201 assert!(serde_json::from_str::<OAuthClientId>("\"\"").is_err());
2202 }
2203
2204 #[test]
2205 fn content_ref_error_names_a_leading_id_followed_by_extra_text() {
2206 let uuid = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6b";
2207 for (input, lead) in [
2208 (format!("{uuid} and the safe-space proposal"), uuid),
2209 (format!("{uuid}b0518e42"), uuid),
2210 (
2211 "GOV-2026-0006 (the ratification)".to_string(),
2212 "GOV-2026-0006",
2213 ),
2214 (
2217 "DATA-2026-0001 (the vote tallies)".to_string(),
2218 "DATA-2026-0001",
2219 ),
2220 ("DATA-2026-0012, index.md".to_string(), "DATA-2026-0012"),
2221 ("OBL-2026-0001 and more".to_string(), "OBL-2026-0001"),
2222 ("protocol, section 3".to_string(), "protocol"),
2223 ("prompts, please".to_string(), "prompts"),
2224 (
2225 "prompt:tier2_reviewer and the juror's".to_string(),
2226 "prompt:tier2_reviewer",
2227 ),
2228 (
2229 "prompts/appeals_juror.md, line 3".to_string(),
2230 "prompt:appeals_juror",
2231 ),
2232 ] {
2233 let err = input.parse::<ContentRef>().unwrap_err();
2234 assert_eq!(
2235 err.leading_ref(),
2236 Some(lead.parse().unwrap()),
2237 "{input}"
2238 );
2239 let msg = err.to_string();
2240 assert!(
2241 msg.contains(&format!("valid id {lead} followed")),
2242 "{msg}"
2243 );
2244 }
2245
2246 let short = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6";
2248 let err = short.parse::<ContentRef>().unwrap_err();
2249 assert_eq!(err.leading_ref(), None);
2250 assert!(!err.to_string().contains("followed by"));
2251 assert_eq!(
2253 "GOV-2026-1".parse::<ContentRef>().unwrap(),
2254 ContentRef::Governance("GOV-2026-0001".parse().unwrap())
2255 );
2256 }
2257
2258 #[test]
2259 fn citations_normalize_as_written() {
2260 for (written, canonical) in [
2261 ("GOV-2026-0006", "GOV-2026-0006"),
2262 ("GOV-2026.6", "GOV-2026-0006"),
2263 ("gov-2026-6", "GOV-2026-0006"),
2264 ("GOV 2026 6", "GOV-2026-0006"),
2265 ("app/2026/03", "APP-2026-0003"),
2266 (" REC-2026-0002 ", "REC-2026-0002"),
2267 ("obl-2026-12", "OBL-2026-0012"),
2268 ("OBL.2026.7", "OBL-2026-0007"),
2269 ("data-2026-3", "DATA-2026-0003"),
2270 ("DATA.2026.12", "DATA-2026-0012"),
2271 (" Data/2026/0001 ", "DATA-2026-0001"),
2272 ("DATA 2026 7", "DATA-2026-0007"),
2273 ] {
2274 let id: GovernanceLogId = written.parse().unwrap();
2275 assert_eq!(id.as_str(), canonical, "{written}");
2276 let json: GovernanceLogId =
2277 serde_json::from_value(serde_json::json!(written)).unwrap();
2278 assert_eq!(json.as_str(), canonical, "{written} via serde");
2279 let content: ContentRef = written.parse().unwrap();
2280 assert_eq!(content, ContentRef::Governance(id), "{written}");
2281 }
2282 for rejected in [
2283 "GOV-2026-N",
2284 "GOV-2026/GOVG=6",
2285 "GOV-2026-00006",
2286 "GOV-26-0006",
2287 "GOV-2026-",
2288 "XYZ-2026-0006",
2289 "GOV-2026-0006-1",
2290 ] {
2291 assert!(rejected.parse::<GovernanceLogId>().is_err(), "{rejected}");
2292 }
2293 assert!(!GovernanceLogId::is_citation_shaped("GOV-2026.6"));
2295 }
2296
2297 #[test]
2298 fn content_ref_parses_document_slugs() {
2299 assert_eq!(
2300 "constitution".parse(),
2301 Ok(ContentRef::Document(PlatformDoc::Constitution))
2302 );
2303 assert_eq!(
2304 "protocol".parse(),
2305 Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
2306 );
2307 assert_eq!(
2309 "governance-protocol".parse(),
2310 Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
2311 );
2312 assert_eq!(
2313 "Constitution".parse(),
2314 Ok(ContentRef::Document(PlatformDoc::Constitution))
2315 );
2316 assert!("proto".parse::<ContentRef>().is_err());
2317 }
2318
2319 #[test]
2320 fn content_ref_parses_prompt_slugs() {
2321 let juror = PlatformDoc::Prompt("appeals_juror".parse().unwrap());
2322 for written in [
2323 "prompt:appeals_juror",
2324 "Prompt:Appeals_Juror",
2325 "prompt/appeals-juror",
2326 "prompts/appeals_juror.md",
2327 "prompts:appeals_juror",
2328 ] {
2329 assert_eq!(
2330 written.parse(),
2331 Ok(ContentRef::Document(juror.clone())),
2332 "{written}"
2333 );
2334 }
2335 assert_eq!(juror.to_string(), "prompt:appeals_juror");
2336 for index in ["prompts", "Prompts", "prompt"] {
2337 assert_eq!(
2338 index.parse(),
2339 Ok(ContentRef::Document(PlatformDoc::Prompts)),
2340 "{index}"
2341 );
2342 }
2343 for rejected in [
2344 "prompt:",
2345 "prompt:2fast",
2346 "prompt:tier 2",
2347 "prompt:../secrets",
2348 "prompt:tier2_reviewer/x",
2349 "promptly",
2350 ] {
2351 assert!(rejected.parse::<ContentRef>().is_err(), "{rejected}");
2352 }
2353 let long = format!("prompt:{}", "a".repeat(PromptName::MAX_LEN + 1));
2354 assert!(long.parse::<ContentRef>().is_err());
2355 }
2356
2357 #[test]
2358 fn content_id_prefix_parses_eight_hex_digits_leniently() {
2359 let p: ContentIdPrefix = "7ad26ccd".parse().unwrap();
2360 assert_eq!(p.to_string(), "7ad26ccd");
2361 assert_eq!(" 7AD26CCD\n".parse::<ContentIdPrefix>().unwrap(), p);
2362 for rejected in ["7ad26cc", "7ad26ccd0", "7ad26ccg", "", "7ad2-6cc"] {
2363 assert!(rejected.parse::<ContentIdPrefix>().is_err(), "{rejected}");
2364 }
2365 }
2366
2367 #[test]
2368 fn content_id_prefix_bounds_cover_exactly_its_uuids() {
2369 let id: Uuid = "7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
2370 let p = ContentIdPrefix::of(&id);
2371 assert_eq!(p.to_string(), "7ad26ccd");
2372 assert!(p.matches(&id));
2373 let (lo, hi) = p.bounds();
2374 assert_eq!(lo.to_string(), "7ad26ccd-0000-0000-0000-000000000000");
2375 assert_eq!(hi.to_string(), "7ad26ccd-ffff-ffff-ffff-ffffffffffff");
2376 assert!(lo <= id && id <= hi);
2377 let next: Uuid =
2378 "7ad26cce-0000-0000-0000-000000000000".parse().unwrap();
2379 assert!(!p.matches(&next) && next > hi);
2380 let top: ContentIdPrefix = "ffffffff".parse().unwrap();
2382 assert_eq!(top.bounds().1, Uuid::max());
2383 let bottom: ContentIdPrefix = "00000000".parse().unwrap();
2384 assert_eq!(bottom.bounds().0, Uuid::nil());
2385 }
2386
2387 #[test]
2388 fn content_ref_reads_a_short_id_and_only_eight_digits() {
2389 let r: ContentRef = "7ad26ccd".parse().unwrap();
2390 assert_eq!(r, ContentRef::ContentPrefix("7ad26ccd".parse().unwrap()));
2391 assert_eq!(r.kind_str(), "content");
2392 assert_eq!(serde_json::to_string(&r).unwrap(), "\"7ad26ccd\"");
2393 let full: ContentRef =
2395 "7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
2396 assert!(matches!(full, ContentRef::Content(_)));
2397 let err = "7ad26ccd-922f".parse::<ContentRef>().unwrap_err();
2402 assert_eq!(err.leading_ref(), None);
2403 }
2404
2405 #[test]
2406 fn content_ref_pattern_admits_short_ids() {
2407 let short = CONTENT_ID_PREFIX_PATTERN
2408 .strip_prefix('^')
2409 .and_then(|p| p.strip_suffix('$'))
2410 .unwrap();
2411 assert!(CONTENT_REF_PATTERN.contains(&format!("|{short}|")));
2412 }
2413
2414 #[test]
2416 fn document_patterns_agree() {
2417 let docs = PLATFORM_DOC_PATTERN.strip_prefix("^(").unwrap();
2418 assert!(CONTENT_REF_PATTERN.ends_with(&format!("|{docs}")));
2419 let name = PROMPT_NAME_PATTERN
2420 .strip_prefix('^')
2421 .and_then(|p| p.strip_suffix('$'))
2422 .unwrap();
2423 assert!(PLATFORM_DOC_PATTERN.contains(&format!("|prompt:{name})$")));
2424 }
2425
2426 #[test]
2427 fn calendar_is_a_document_slug() {
2428 assert_eq!(
2429 "calendar".parse::<ContentRef>().unwrap(),
2430 ContentRef::Document(PlatformDoc::Calendar)
2431 );
2432 assert_eq!(
2433 "Calendar".parse::<PlatformDoc>().unwrap(),
2434 PlatformDoc::Calendar
2435 );
2436 assert_eq!(PlatformDoc::Calendar.to_string(), "calendar");
2437 assert_eq!(
2438 "OBL-2026-0001".parse::<ContentRef>().unwrap(),
2439 ContentRef::Governance("OBL-2026-0001".parse().unwrap())
2440 );
2441 assert_eq!(
2442 "DATA-2026-0001".parse::<ContentRef>().unwrap(),
2443 ContentRef::Governance("DATA-2026-0001".parse().unwrap())
2444 );
2445 }
2446
2447 #[test]
2448 fn platform_doc_serde_uses_the_canonical_slug() {
2449 let json =
2450 serde_json::to_string(&PlatformDoc::GovernanceProtocol).unwrap();
2451 assert_eq!(json, "\"protocol\"");
2452 let doc: PlatformDoc =
2453 serde_json::from_str("\"governance-protocol\"").unwrap();
2454 assert_eq!(doc, PlatformDoc::GovernanceProtocol);
2455 }
2456
2457 #[test]
2458 fn ids_are_unique() {
2459 let a = AgentId::new();
2460 let b = AgentId::new();
2461 assert_ne!(a, b);
2462 }
2463
2464 #[test]
2465 fn serde_round_trip() {
2466 let id = PostId::new();
2467 let json = serde_json::to_string(&id).unwrap();
2468 let deserialized: PostId = serde_json::from_str(&json).unwrap();
2469 assert_eq!(id, deserialized);
2470 }
2471
2472 #[test]
2473 fn display_shows_uuid() {
2474 let id = CommunityId::new();
2475 let display = id.to_string();
2476 assert_eq!(display.len(), 36);
2478 assert!(display.contains('-'));
2479 }
2480
2481 #[test]
2482 fn from_uuid_round_trip() {
2483 let uuid = Uuid::new_v4();
2484 let id = AgentId::from(uuid);
2485 let back: Uuid = id.into();
2486 assert_eq!(uuid, back);
2487 }
2488
2489 #[test]
2493 fn every_id_round_trips_through_its_own_display() {
2494 let agent = AgentId::new();
2495 assert_eq!(agent.to_string().parse::<AgentId>().unwrap(), agent);
2496
2497 let action = ModerationActionId::new();
2498 assert_eq!(
2499 action.to_string().parse::<ModerationActionId>().unwrap(),
2500 action
2501 );
2502
2503 let content = ContentId::new();
2504 assert_eq!(content.to_string().parse::<ContentId>().unwrap(), content);
2505
2506 let feedback = FeedbackId::new();
2507 assert_eq!(
2508 feedback.to_string().parse::<FeedbackId>().unwrap(),
2509 feedback
2510 );
2511 }
2512
2513 #[test]
2514 fn parsing_a_non_uuid_is_an_error_not_a_panic() {
2515 assert!("not-a-uuid".parse::<ContentId>().is_err());
2516 assert!("".parse::<ContentId>().is_err());
2517 }
2518
2519 #[test]
2524 fn content_id_is_wire_compatible_with_a_bare_uuid() {
2525 let uuid = Uuid::new_v4();
2526 let typed = ContentId::from(uuid);
2527 assert_eq!(
2528 serde_json::to_string(&typed).unwrap(),
2529 serde_json::to_string(&uuid).unwrap()
2530 );
2531 }
2532
2533 #[test]
2536 fn every_moderation_target_narrows_losslessly() {
2537 let uuid = Uuid::new_v4();
2538
2539 for (label, got) in [
2540 ("PostId", ModerationTargetId::from(PostId::from(uuid))),
2541 ("CommentId", ModerationTargetId::from(CommentId::from(uuid))),
2542 ("MessageId", ModerationTargetId::from(MessageId::from(uuid))),
2543 ("AgentId", ModerationTargetId::from(AgentId::from(uuid))),
2544 ("ContentId", ModerationTargetId::from(ContentId::from(uuid))),
2545 ] {
2546 assert_eq!(
2547 got.as_uuid(),
2548 &uuid,
2549 "{label} -> ModerationTargetId lost the uuid"
2550 );
2551 }
2552 }
2553
2554 #[test]
2558 fn resolved_ids_narrow_to_content_id_losslessly() {
2559 let uuid = Uuid::new_v4();
2560
2561 assert_eq!(
2562 ContentId::from(PostId::from(uuid)).as_uuid(),
2563 &uuid,
2564 "PostId -> ContentId lost the uuid"
2565 );
2566 assert_eq!(
2567 ContentId::from(CommentId::from(uuid)).as_uuid(),
2568 &uuid,
2569 "CommentId -> ContentId lost the uuid"
2570 );
2571 assert_eq!(
2572 ContentId::from(PostOrCommentId::Comment(CommentId::from(uuid)))
2573 .as_uuid(),
2574 &uuid,
2575 "PostOrCommentId -> ContentId lost the uuid"
2576 );
2577 }
2578
2579 #[test]
2580 fn json_is_plain_uuid_string() {
2581 let uuid = Uuid::new_v4();
2582 let id = AgentId::from(uuid);
2583 let id_json = serde_json::to_string(&id).unwrap();
2585 let uuid_json = serde_json::to_string(&uuid).unwrap();
2586 assert_eq!(id_json, uuid_json);
2587 }
2588
2589 #[cfg(feature = "schemars")]
2594 #[test]
2595 fn id_json_schema_is_inlined() {
2596 use schemars::JsonSchema;
2597
2598 assert!(
2599 <PostId as JsonSchema>::inline_schema(),
2600 "PostId::inline_schema() must return true to avoid $ref in containing schemas"
2601 );
2602 assert!(<AgentId as JsonSchema>::inline_schema());
2603 assert!(<CommentId as JsonSchema>::inline_schema());
2604 assert!(<CommunityId as JsonSchema>::inline_schema());
2605 assert!(<GovernanceLogId as JsonSchema>::inline_schema());
2606 assert!(<ContentRef as JsonSchema>::inline_schema());
2607 assert!(<FeedbackId as JsonSchema>::inline_schema());
2608 assert!(<ContactRequestId as JsonSchema>::inline_schema());
2609
2610 #[derive(schemars::JsonSchema)]
2614 #[allow(dead_code)]
2615 struct Container {
2616 post_id: PostId,
2618 agent_id: Option<AgentId>,
2620 gov_id: GovernanceLogId,
2622 maybe_gov_id: Option<GovernanceLogId>,
2624 content_ref: ContentRef,
2626 maybe_content_ref: Option<ContentRef>,
2628 feedback_id: FeedbackId,
2630 }
2631
2632 let schema = schemars::schema_for!(Container);
2633 let value = serde_json::to_value(&schema).unwrap();
2634
2635 assert!(
2637 value.get("$defs").is_none(),
2638 "no $defs should be emitted for ID-only container; got schema: {value}"
2639 );
2640
2641 let post_id = &value["properties"]["post_id"];
2643 assert!(
2644 post_id.get("$ref").is_none(),
2645 "post_id must not be a $ref; got: {post_id}"
2646 );
2647 assert_eq!(post_id["type"], "string");
2648 assert_eq!(post_id["format"], "uuid");
2649
2650 let agent_id = &value["properties"]["agent_id"];
2655 assert!(
2656 agent_id.get("$ref").is_none(),
2657 "agent_id must not be a $ref; got: {agent_id}"
2658 );
2659 let agent_id_str = agent_id.to_string();
2660 assert!(
2661 !agent_id_str.contains("$ref"),
2662 "agent_id schema must contain no $ref anywhere; got: {agent_id}"
2663 );
2664 assert!(
2665 agent_id_str.contains("\"format\":\"uuid\""),
2666 "agent_id should still carry format=uuid; got: {agent_id}"
2667 );
2668
2669 for field in
2674 ["gov_id", "maybe_gov_id", "content_ref", "maybe_content_ref"]
2675 {
2676 let f = &value["properties"][field];
2677 assert!(
2678 !f.to_string().contains("$ref"),
2679 "{field} must contain no $ref anywhere; got: {f}"
2680 );
2681 }
2682 assert_eq!(value["properties"]["gov_id"]["type"], "string");
2683 assert_eq!(
2684 value["properties"]["gov_id"]["pattern"],
2685 GOVERNANCE_LOG_ID_PATTERN
2686 );
2687 assert!(
2688 value["properties"]["maybe_gov_id"]
2689 .to_string()
2690 .contains("GOV|APP"),
2691 "Option<GovernanceLogId> should keep the citation pattern; got: {}",
2692 value["properties"]["maybe_gov_id"]
2693 );
2694 assert_eq!(value["properties"]["content_ref"]["type"], "string");
2695 }
2696
2697 #[test]
2698 fn governance_log_id_accepts_only_citation_shapes() {
2699 for (good, prefix) in [
2700 ("GOV-2026-0006", GovernanceLogPrefix::Gov),
2701 ("APP-2026-0003", GovernanceLogPrefix::App),
2702 ("AMD-2026-0001", GovernanceLogPrefix::Amd),
2703 ("KEY-2026-0001", GovernanceLogPrefix::Key),
2704 ("REC-2026-0001", GovernanceLogPrefix::Rec),
2705 ("OBL-2026-0001", GovernanceLogPrefix::Obl),
2706 ("DATA-2026-0001", GovernanceLogPrefix::Data),
2707 ("GOV-1999-0000", GovernanceLogPrefix::Gov),
2708 ] {
2709 let id = good.parse::<GovernanceLogId>().unwrap();
2710 assert_eq!(id.as_str(), good, "{good} should parse");
2711 assert_eq!(id.prefix(), prefix);
2712 let letters = good.split('-').next().unwrap();
2713 assert_eq!(id.prefix().as_str(), letters);
2714 assert_eq!(id.prefix().to_string().parse(), Ok(prefix));
2715 }
2716 let newer: GovernanceLogId =
2718 serde_json::from_value(serde_json::json!("ZZZ-2026-0001")).unwrap();
2719 assert_eq!(newer.prefix(), GovernanceLogPrefix::Unknown);
2720 assert_eq!(newer.as_str(), "ZZZ-2026-0001");
2721 assert!("ZZZ-2026-0001".parse::<GovernanceLogId>().is_err());
2722 assert!(!GovernanceLogId::is_citation_shaped("ZZZ-2026-0001"));
2723 for junk in [
2724 "zzz-2026-0001",
2725 "ZZZZZ-2026-0001",
2726 "ZZ-2026-0001",
2727 "ZZZ-2026-1",
2728 ] {
2729 assert!(
2730 serde_json::from_value::<GovernanceLogId>(serde_json::json!(
2731 junk
2732 ))
2733 .is_err(),
2734 "{junk}"
2735 );
2736 }
2737 assert_eq!(
2738 GovernanceLogId::from_parts(GovernanceLogPrefix::Unknown, 2026, 1),
2739 None
2740 );
2741 for prefix in GovernanceLogPrefix::ALL {
2743 let want = if prefix == GovernanceLogPrefix::Data {
2744 4
2745 } else {
2746 3
2747 };
2748 assert_eq!(prefix.as_str().len(), want, "{prefix}");
2749 }
2750 let series = GovernanceLogPrefix::ALL.map(|p| p.as_str()).join("|");
2752 assert!(
2753 GOVERNANCE_LOG_ID_PATTERN.contains(&format!("({series})")),
2754 "{GOVERNANCE_LOG_ID_PATTERN}"
2755 );
2756 assert!(
2757 CONTENT_REF_PATTERN.contains(&format!("({series})")),
2758 "{CONTENT_REF_PATTERN}"
2759 );
2760 assert_eq!(
2762 "GOV-2026-006".parse::<GovernanceLogId>().unwrap().as_str(),
2763 "GOV-2026-0006"
2764 );
2765 assert_eq!(
2766 "gov-2026-0006".parse::<GovernanceLogId>().unwrap().as_str(),
2767 "GOV-2026-0006"
2768 );
2769 for bad in [
2770 "",
2771 "GOV-26-0006",
2772 "MOD-2026-0006",
2773 "GOV-2026-0006-1",
2774 "GOV-202X-0006",
2775 "DAT-2026-0001",
2776 "DATAS-2026-0001",
2777 "DATA-2026-00001",
2778 "DATA-2026",
2779 "3f1a0000-0000-0000-0000-000000000000",
2780 ] {
2781 assert!(
2782 bad.parse::<GovernanceLogId>().is_err(),
2783 "{bad:?} should not parse as a GovernanceLogId"
2784 );
2785 }
2786 }
2787
2788 #[test]
2792 fn governance_log_id_is_wire_compatible_with_a_bare_string() {
2793 let id: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
2794 assert_eq!(serde_json::to_string(&id).unwrap(), "\"GOV-2026-0006\"");
2795 let back: GovernanceLogId =
2796 serde_json::from_str("\"GOV-2026-0006\"").unwrap();
2797 assert_eq!(back, id);
2798 assert!(serde_json::from_str::<GovernanceLogId>("\"nope\"").is_err());
2800 }
2801
2802 #[test]
2805 fn content_ref_round_trips_as_a_bare_string() {
2806 let uuid = Uuid::new_v4();
2807 let content = ContentRef::from(ContentId::from(uuid));
2808 assert_eq!(
2809 serde_json::to_value(&content).unwrap(),
2810 serde_json::json!(uuid.to_string())
2811 );
2812 assert_eq!(
2813 serde_json::from_value::<ContentRef>(serde_json::json!(
2814 uuid.to_string()
2815 ))
2816 .unwrap(),
2817 content
2818 );
2819
2820 let gov = ContentRef::Governance("APP-2026-0003".parse().unwrap());
2821 assert_eq!(
2822 serde_json::to_value(&gov).unwrap(),
2823 serde_json::json!("APP-2026-0003")
2824 );
2825 assert_eq!(
2826 serde_json::from_value::<ContentRef>(serde_json::json!(
2827 "APP-2026-0003"
2828 ))
2829 .unwrap(),
2830 gov
2831 );
2832
2833 assert!(gov.is_governance());
2834 assert!(!content.is_governance());
2835 assert_eq!(gov.kind_str(), "governance");
2836 assert_eq!(content.kind_str(), "content");
2837 assert_eq!(content.as_content(), Some(ContentId::from(uuid)));
2838 assert!(content.as_governance().is_none());
2839
2840 assert!("not-an-id".parse::<ContentRef>().is_err());
2842 assert!(
2843 serde_json::from_value::<ContentRef>(serde_json::json!(
2844 "not-an-id"
2845 ))
2846 .is_err()
2847 );
2848 }
2849
2850 #[test]
2852 fn every_readable_id_narrows_to_a_content_ref() {
2853 let uuid = Uuid::new_v4();
2854 for (label, got) in [
2855 ("PostId", ContentRef::from(PostId::from(uuid))),
2856 ("CommentId", ContentRef::from(CommentId::from(uuid))),
2857 ("ContentId", ContentRef::from(ContentId::from(uuid))),
2858 ] {
2859 assert_eq!(
2860 got,
2861 ContentRef::Content(ContentId::from(uuid)),
2862 "{label} -> ContentRef lost the uuid"
2863 );
2864 }
2865 let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
2866 assert_eq!(ContentRef::from(gov.clone()), ContentRef::Governance(gov));
2867 }
2868
2869 #[test]
2872 fn string_shaped_ids_round_trip_through_display() {
2873 let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
2874 assert_eq!(gov.to_string().parse::<GovernanceLogId>().unwrap(), gov);
2875
2876 let r = ContentRef::Governance(gov);
2877 assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
2878
2879 let r = ContentRef::Content(ContentId::new());
2880 assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
2881 }
2882
2883 #[test]
2884 fn post_or_comment_post_variant() {
2885 let inner = PostId::new();
2886 let tagged = PostOrCommentId::Post(inner);
2887 assert!(tagged.is_post());
2888 assert!(!tagged.is_comment());
2889 assert_eq!(tagged.as_post(), Some(inner));
2890 assert_eq!(tagged.as_comment(), None);
2891 assert_eq!(tagged.as_uuid(), *inner.as_uuid());
2892 assert_eq!(tagged.kind_str(), "post");
2893 }
2894
2895 #[test]
2896 fn post_or_comment_comment_variant() {
2897 let inner = CommentId::new();
2898 let tagged = PostOrCommentId::Comment(inner);
2899 assert!(tagged.is_comment());
2900 assert!(!tagged.is_post());
2901 assert_eq!(tagged.as_comment(), Some(inner));
2902 assert_eq!(tagged.as_post(), None);
2903 assert_eq!(tagged.as_uuid(), *inner.as_uuid());
2904 assert_eq!(tagged.kind_str(), "comment");
2905 }
2906
2907 #[test]
2908 fn post_or_comment_from_conversions() {
2909 let post = PostId::new();
2910 let comment = CommentId::new();
2911 let via_post: PostOrCommentId = post.into();
2912 let via_comment: PostOrCommentId = comment.into();
2913 assert_eq!(via_post, PostOrCommentId::Post(post));
2914 assert_eq!(via_comment, PostOrCommentId::Comment(comment));
2915 }
2916
2917 #[test]
2918 fn post_or_comment_display_is_kind_colon_uuid() {
2919 let post = PostId::new();
2920 let tagged = PostOrCommentId::Post(post);
2921 let rendered = tagged.to_string();
2922 assert!(rendered.starts_with("post:"));
2923 assert!(rendered.contains(&post.to_string()));
2924 }
2925
2926 const FULL: &str = "7ad26ccd-922f-484a-a37c-51777344a98c";
2929
2930 #[test]
2933 fn a_bad_id_fails_in_plain_words() {
2934 let bad = "7ad26ccd-922f-484a-a37c-51777344a";
2935 let want = format!(
2936 "not a valid PostId: expected a UUID like \"{FULL}\", got \"{bad}\""
2937 );
2938 assert_eq!(bad.parse::<PostId>().unwrap_err().to_string(), want);
2939 let err = serde_json::from_str::<PostId>(&format!("\"{bad}\""))
2940 .unwrap_err()
2941 .to_string();
2942 assert!(err.starts_with(&want), "{err}");
2943 assert!(!err.contains("group"), "{err}");
2944 let err = serde_json::from_str::<AgentId>("5")
2945 .unwrap_err()
2946 .to_string();
2947 assert!(err.contains("expected AgentId as a UUID string"), "{err}");
2948 let long = "x".repeat(500);
2950 let msg = long.parse::<CommentId>().unwrap_err().to_string();
2951 assert!(msg.len() < 200 && msg.ends_with("…\""), "{msg}");
2952 }
2953
2954 #[test]
2956 fn ids_still_round_trip() {
2957 let id: PostId = FULL.parse().unwrap();
2958 let json = serde_json::to_string(&id).unwrap();
2959 assert_eq!(serde_json::from_str::<PostId>(&json).unwrap(), id);
2960 let map: std::collections::HashMap<PostId, i64> =
2961 [(id, 3)].into_iter().collect();
2962 let json = serde_json::to_string(&map).unwrap();
2963 let back: std::collections::HashMap<PostId, i64> =
2964 serde_json::from_str(&json).unwrap();
2965 assert_eq!(back, map);
2966 }
2967
2968 fn target(s: &str) -> Result<ContentTarget, ContentTargetError> {
2969 s.parse()
2970 }
2971
2972 #[test]
2973 fn full_and_short_targets_parse() {
2974 let full = target(FULL).unwrap();
2975 assert_eq!(full.full().unwrap().to_string(), FULL);
2976 assert_eq!(full.to_string(), FULL);
2977 let short = target(" 7AD26CCD ").unwrap();
2978 assert!(short.full().is_none());
2979 assert_eq!(short.to_string(), "7ad26ccd");
2980 for variant in [
2982 FULL.replace('-', ""),
2983 FULL.to_uppercase(),
2984 FULL.replace('-', "\u{2011}"),
2985 ] {
2986 assert_eq!(target(&variant).unwrap(), full, "{variant}");
2987 }
2988 }
2989
2990 #[test]
2991 fn a_truncated_uuid_is_an_error_not_its_prefix() {
2992 let err = target("7ad26ccd-922f-484a-a37c-51777344a").unwrap_err();
2993 let msg = err.in_field("reply_to").to_string();
2994 assert!(
2995 msg.starts_with(
2996 "`reply_to` must be a post or comment id: a full UUID or its first 8 hex digits"
2997 ),
2998 "{msg}"
2999 );
3000 for internal in [
3001 "group",
3002 "UUID parsing",
3003 "invalid length",
3004 "invalid character",
3005 ] {
3006 assert!(!msg.contains(internal), "{internal} leaked: {msg}");
3007 }
3008 assert!(target("7ad26cc").is_err());
3009 assert!(target("7ad26ccd9").is_err());
3010 }
3011
3012 #[test]
3013 fn trailing_text_names_the_id_it_starts_with() {
3014 let msg = target(&format!("{FULL} (the reply above)"))
3015 .unwrap_err()
3016 .to_string();
3017 assert!(msg.contains(&format!("starts with the id {FULL}")), "{msg}");
3018 }
3019
3020 #[derive(Debug, serde::Deserialize)]
3021 struct Probe {
3022 #[serde(deserialize_with = "content_target::reply_to")]
3023 #[allow(dead_code)]
3024 reply_to: ContentTarget,
3025 }
3026
3027 #[test]
3028 fn target_errors_name_the_field_for_strings_and_other_types() {
3029 let err = serde_json::from_str::<Probe>(r#"{"reply_to": "nope"}"#)
3030 .unwrap_err();
3031 assert!(
3032 err.to_string()
3033 .starts_with("`reply_to` must be a post or comment id"),
3034 "{err}"
3035 );
3036 let err =
3037 serde_json::from_str::<Probe>(r#"{"reply_to": 5}"#).unwrap_err();
3038 assert!(
3039 err.to_string()
3040 .contains("expected `reply_to` to be a post or comment id"),
3041 "{err}"
3042 );
3043 }
3044
3045 #[cfg(feature = "schemars")]
3046 #[test]
3047 fn target_schema_is_inline_and_admits_both_forms() {
3048 let schema = schemars::schema_for!(ContentTarget);
3049 let v = schema.as_value();
3050 assert!(v.get("$ref").is_none() && v.get("$defs").is_none(), "{v}");
3051 assert!(v.get("format").is_none(), "a short id is not format: uuid");
3052 assert_eq!(v["pattern"], CONTENT_TARGET_PATTERN);
3053 }
3054}