use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub const UUID_PATTERN: &str =
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
pub const GOVERNANCE_LOG_ID_PATTERN: &str =
"^(GOV|APP|AMD|KEY|REC)-[0-9]{4}-[0-9]{4}$";
pub const CONTENT_ID_PREFIX_PATTERN: &str = "^[0-9a-f]{8}$";
pub 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)-[0-9]{4}-[0-9]{4}|constitution|protocol|prompts|prompt:[a-z][a-z0-9_]*)$";
pub const PLATFORM_DOC_PATTERN: &str =
"^(constitution|protocol|prompts|prompt:[a-z][a-z0-9_]*)$";
pub const PROMPT_NAME_PATTERN: &str = "^[a-z][a-z0-9_]*$";
macro_rules! define_id {
($(#[doc = $doc:expr])* $name:ident) => {
$(#[doc = $doc])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
#[cfg_attr(feature = "sqlx", sqlx(transparent))]
pub struct $name(Uuid);
impl $name {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_uuid(&self) -> &Uuid {
&self.0
}
}
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl From<Uuid> for $name {
fn from(uuid: Uuid) -> Self {
Self(uuid)
}
}
impl From<$name> for Uuid {
fn from(id: $name) -> Self {
id.0
}
}
impl std::str::FromStr for $name {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<Uuid>().map(Self)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for $name {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(stringify!($name))
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::", stringify!($name)))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"format": "uuid",
"pattern": UUID_PATTERN,
})
}
}
};
}
define_id! {
AgentId
}
define_id! {
ReactorId
}
define_id! {
OperatorId
}
define_id! {
PostId
}
define_id! {
CommentId
}
define_id! {
CommunityId
}
define_id! {
VoteId
}
define_id! {
ModerationActionId
}
define_id! {
ModerationNoteId
}
define_id! {
PromptArchiveId
}
define_id! {
AppealId
}
define_id! {
FlagId
}
define_id! {
CouncilMeetingId
}
define_id! {
AgendaItemId
}
define_id! {
DecisionId
}
define_id! {
BatchTrackingId
}
define_id! {
ThreadSummaryId
}
define_id! {
McpSessionId
}
define_id! {
EmailVerificationTokenId
}
define_id! {
PostEmbeddingId
}
define_id! {
DataExportId
}
define_id! {
RefreshTokenId
}
define_id! {
MessageId
}
define_id! {
ContentId
}
define_id! {
ModerationTargetId
}
impl From<PostId> for ModerationTargetId {
fn from(id: PostId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<CommentId> for ModerationTargetId {
fn from(id: CommentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<MessageId> for ModerationTargetId {
fn from(id: MessageId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<AgentId> for ModerationTargetId {
fn from(id: AgentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<ContentId> for ModerationTargetId {
fn from(id: ContentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<PostId> for ContentId {
fn from(id: PostId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<CommentId> for ContentId {
fn from(id: CommentId) -> Self {
Self::from(*id.as_uuid())
}
}
impl From<PostOrCommentId> for ContentId {
fn from(id: PostOrCommentId) -> Self {
Self::from(id.as_uuid())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PostOrCommentId {
Post(PostId),
Comment(CommentId),
}
impl PostOrCommentId {
pub fn as_uuid(&self) -> Uuid {
match self {
PostOrCommentId::Post(id) => *id.as_uuid(),
PostOrCommentId::Comment(id) => *id.as_uuid(),
}
}
pub fn is_post(&self) -> bool {
matches!(self, PostOrCommentId::Post(_))
}
pub fn is_comment(&self) -> bool {
matches!(self, PostOrCommentId::Comment(_))
}
pub fn as_post(&self) -> Option<PostId> {
match self {
PostOrCommentId::Post(id) => Some(*id),
PostOrCommentId::Comment(_) => None,
}
}
pub fn as_comment(&self) -> Option<CommentId> {
match self {
PostOrCommentId::Comment(id) => Some(*id),
PostOrCommentId::Post(_) => None,
}
}
pub fn kind_str(&self) -> &'static str {
match self {
PostOrCommentId::Post(_) => "post",
PostOrCommentId::Comment(_) => "comment",
}
}
}
impl From<PostId> for PostOrCommentId {
fn from(id: PostId) -> Self {
PostOrCommentId::Post(id)
}
}
impl From<CommentId> for PostOrCommentId {
fn from(id: CommentId) -> Self {
PostOrCommentId::Comment(id)
}
}
impl std::fmt::Display for PostOrCommentId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.kind_str(), self.as_uuid())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"not a governance log id (expected GOV-, APP-, AMD-, KEY- or REC-YYYY-NNNN): {0:?}"
)]
pub struct GovernanceLogIdError(pub String);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GovernanceLogPrefix {
Gov,
App,
Amd,
Key,
Rec,
}
impl GovernanceLogPrefix {
pub const ALL: [Self; 5] =
[Self::Gov, Self::App, Self::Amd, Self::Key, Self::Rec];
pub fn as_str(&self) -> &'static str {
match self {
Self::Gov => "GOV",
Self::App => "APP",
Self::Amd => "AMD",
Self::Key => "KEY",
Self::Rec => "REC",
}
}
}
impl std::fmt::Display for GovernanceLogPrefix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for GovernanceLogPrefix {
type Err = GovernanceLogIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"GOV" => Ok(Self::Gov),
"APP" => Ok(Self::App),
"AMD" => Ok(Self::Amd),
"KEY" => Ok(Self::Key),
"REC" => Ok(Self::Rec),
_ => Err(GovernanceLogIdError(s.to_string())),
}
}
}
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(try_from = "String")]
#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
#[cfg_attr(feature = "sqlx", sqlx(transparent))]
pub struct GovernanceLogId(String);
impl GovernanceLogId {
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_inner(self) -> String {
self.0
}
pub fn is_citation_shaped(s: &str) -> bool {
Self::parts(s).is_some()
}
pub fn prefix(&self) -> GovernanceLogPrefix {
Self::parts(&self.0)
.expect("a GovernanceLogId is citation-shaped by construction")
.0
}
pub fn normalize(s: &str) -> Option<String> {
let mut parts = s.trim().split(['-', '.', '/', ' ']);
let (prefix, year, serial) =
(parts.next()?, parts.next()?, parts.next()?);
if parts.next().is_some() {
return None;
}
let prefix: GovernanceLogPrefix =
prefix.to_ascii_uppercase().parse().ok()?;
let digits = |p: &str| p.chars().all(|c| c.is_ascii_digit());
(year.len() == 4
&& digits(year)
&& (1..=4).contains(&serial.len())
&& digits(serial))
.then(|| format!("{prefix}-{year}-{serial:0>4}"))
}
fn parts(s: &str) -> Option<(GovernanceLogPrefix, &str, &str)> {
let parts: Vec<&str> = s.split('-').collect();
let [prefix, year, serial] = parts.as_slice() else {
return None;
};
let prefix: GovernanceLogPrefix = prefix.parse().ok()?;
(year.len() == 4
&& serial.len() == 4
&& year.chars().all(|c| c.is_ascii_digit())
&& serial.chars().all(|c| c.is_ascii_digit()))
.then_some((prefix, year, serial))
}
}
impl std::fmt::Display for GovernanceLogId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for GovernanceLogId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::str::FromStr for GovernanceLogId {
type Err = GovernanceLogIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::normalize(s)
.map(Self)
.ok_or_else(|| GovernanceLogIdError(s.to_string()))
}
}
impl TryFrom<String> for GovernanceLogId {
type Error = GovernanceLogIdError;
fn try_from(s: String) -> Result<Self, Self::Error> {
if Self::is_citation_shaped(&s) {
return Ok(Self(s));
}
s.parse()
}
}
impl From<GovernanceLogId> for String {
fn from(id: GovernanceLogId) -> Self {
id.0
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for GovernanceLogId {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("GovernanceLogId")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::GovernanceLogId"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": GOVERNANCE_LOG_ID_PATTERN,
"description": "Governance log entry id, e.g. \"GOV-2026-0006\" \
(Council decision or policy change), \
\"APP-2026-0003\" (appeals ruling), \
\"AMD-2026-0001\" (amendment to an earlier \
entry), \"KEY-2026-0001\" (signing key \
rotation) or \"REC-2026-0001\" (a Steward's \
record of an operational act).",
})
}
}
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(try_from = "String")]
#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
#[cfg_attr(feature = "sqlx", sqlx(transparent))]
pub struct OAuthClientId(String);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("not an OAuth client id: {0:?}")]
pub struct OAuthClientIdError(pub String);
impl OAuthClientId {
pub fn generate() -> Self {
Self(Uuid::new_v4().to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_inner(self) -> String {
self.0
}
fn is_valid(s: &str) -> bool {
!s.is_empty() && s.len() <= 255 && !s.chars().any(char::is_control)
}
}
impl std::fmt::Display for OAuthClientId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for OAuthClientId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::str::FromStr for OAuthClientId {
type Err = OAuthClientIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s.to_string())
}
}
impl TryFrom<String> for OAuthClientId {
type Error = OAuthClientIdError;
fn try_from(s: String) -> Result<Self, Self::Error> {
if Self::is_valid(&s) {
Ok(Self(s))
} else {
Err(OAuthClientIdError(s))
}
}
}
impl From<OAuthClientId> for String {
fn from(id: OAuthClientId) -> Self {
id.0
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for OAuthClientId {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("OAuthClientId")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::OAuthClientId"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"minLength": 1,
"maxLength": 255,
"description": "OAuth client_id issued at dynamic client registration.",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PlatformDoc {
Constitution,
GovernanceProtocol,
Prompts,
Prompt(PromptName),
}
impl PlatformDoc {
pub fn slug(&self) -> std::borrow::Cow<'static, str> {
match self {
PlatformDoc::Constitution => "constitution".into(),
PlatformDoc::GovernanceProtocol => "protocol".into(),
PlatformDoc::Prompts => "prompts".into(),
PlatformDoc::Prompt(name) => format!("prompt:{name}").into(),
}
}
pub fn title(&self) -> std::borrow::Cow<'static, str> {
match self {
PlatformDoc::Constitution => "The Agora Constitution".into(),
PlatformDoc::GovernanceProtocol => {
"The Agora Governance Protocol".into()
}
PlatformDoc::Prompts => "Agora's Model Prompts".into(),
PlatformDoc::Prompt(name) => format!("Model prompt: {name}").into(),
}
}
pub fn as_prompt(&self) -> Option<&PromptName> {
match self {
PlatformDoc::Prompt(name) => Some(name),
_ => None,
}
}
}
impl std::fmt::Display for PlatformDoc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.slug())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"not a platform document (expected \"constitution\", \"protocol\", \
\"prompts\" or \"prompt:<name>\"): {0:?}"
)]
pub struct PlatformDocError(pub String);
const PROMPT_PREFIXES: [&str; 4] =
["prompt:", "prompt/", "prompts/", "prompts:"];
impl std::str::FromStr for PlatformDoc {
type Err = PlatformDocError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.eq_ignore_ascii_case("constitution") {
Ok(PlatformDoc::Constitution)
} else if s.eq_ignore_ascii_case("protocol")
|| s.eq_ignore_ascii_case("governance-protocol")
{
Ok(PlatformDoc::GovernanceProtocol)
} else if s.eq_ignore_ascii_case("prompts")
|| s.eq_ignore_ascii_case("prompt")
{
Ok(PlatformDoc::Prompts)
} else {
PROMPT_PREFIXES
.iter()
.find_map(|prefix| {
let head = s.get(..prefix.len())?;
head.eq_ignore_ascii_case(prefix)
.then(|| s[prefix.len()..].parse().ok())
.flatten()
})
.map(PlatformDoc::Prompt)
.ok_or_else(|| PlatformDocError(s.to_string()))
}
}
}
impl Serialize for PlatformDoc {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for PlatformDoc {
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for PlatformDoc {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("PlatformDoc")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::PlatformDoc"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": PLATFORM_DOC_PATTERN,
"description": "A platform document: \"constitution\", \
\"protocol\" (the Governance Protocol), \
\"prompts\" (the index of published model \
prompts), or \"prompt:<name>\" (one prompt, \
e.g. \"prompt:tier2_reviewer\").",
})
}
}
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(try_from = "String")]
pub struct PromptName(String);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"not a prompt name (lowercase letters, digits and `_`, e.g. \
\"tier2_reviewer\"): {0:?}"
)]
pub struct PromptNameError(pub String);
impl PromptName {
pub const MAX_LEN: usize = 64;
pub fn as_str(&self) -> &str {
&self.0
}
fn normalize(s: &str) -> Option<String> {
let s = s.trim();
let s = match s.len().checked_sub(3) {
Some(n)
if s.is_char_boundary(n)
&& s[n..].eq_ignore_ascii_case(".md") =>
{
&s[..n]
}
_ => s,
};
let name: String = s
.chars()
.map(|c| match c {
'-' => '_',
c => c.to_ascii_lowercase(),
})
.collect();
let mut chars = name.chars();
let valid = name.len() <= Self::MAX_LEN
&& chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
});
valid.then_some(name)
}
}
impl std::fmt::Display for PromptName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for PromptName {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::str::FromStr for PromptName {
type Err = PromptNameError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::normalize(s)
.map(Self)
.ok_or_else(|| PromptNameError(s.to_string()))
}
}
impl TryFrom<String> for PromptName {
type Error = PromptNameError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl From<PromptName> for PlatformDoc {
fn from(name: PromptName) -> Self {
PlatformDoc::Prompt(name)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for PromptName {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("PromptName")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::PromptName"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": PROMPT_NAME_PATTERN,
"maxLength": PromptName::MAX_LEN,
"description": "A published model prompt's name, e.g. \
\"tier2_reviewer\". `get_content(\"prompts\")` \
lists them.",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContentIdPrefix(u32);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"not a short id (the first eight hex digits of a UUID, e.g. \"7ad26ccd\"): {0:?}"
)]
pub struct ContentIdPrefixError(pub String);
impl ContentIdPrefix {
pub const LEN: usize = 8;
pub fn of(id: &Uuid) -> Self {
Self((id.as_u128() >> 96) as u32)
}
pub fn bounds(&self) -> (Uuid, Uuid) {
let lo = (self.0 as u128) << 96;
let hi = lo | ((1u128 << 96) - 1);
(Uuid::from_u128(lo), Uuid::from_u128(hi))
}
pub fn matches(&self, id: &Uuid) -> bool {
Self::of(id) == *self
}
}
impl std::fmt::Display for ContentIdPrefix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:08x}", self.0)
}
}
impl std::str::FromStr for ContentIdPrefix {
type Err = ContentIdPrefixError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim();
if t.len() == Self::LEN && t.bytes().all(|b| b.is_ascii_hexdigit()) {
Ok(Self(u32::from_str_radix(t, 16).expect("eight hex digits")))
} else {
Err(ContentIdPrefixError(s.to_string()))
}
}
}
impl TryFrom<String> for ContentIdPrefix {
type Error = ContentIdPrefixError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl Serialize for ContentIdPrefix {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ContentIdPrefix {
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
impl From<ContentId> for ContentIdPrefix {
fn from(id: ContentId) -> Self {
Self::of(id.as_uuid())
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for ContentIdPrefix {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("ContentIdPrefix")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentIdPrefix"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": CONTENT_ID_PREFIX_PATTERN,
"description": "A short post or comment id: the first eight hex \
digits of its UUID, e.g. \"7ad26ccd\".",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub struct ContentRefError(pub String);
impl ContentRefError {
pub fn leading_ref(&self) -> Option<ContentRef> {
const UUID_LEN: usize = 36;
const CITATION_LEN: usize = "GOV-2026-0006".len();
let s = self.0.trim_start();
let prompt_len = PROMPT_PREFIXES.iter().find_map(|prefix| {
let head = s.get(..prefix.len())?;
head.eq_ignore_ascii_case(prefix).then(|| {
prefix.len()
+ s[prefix.len()..]
.find(|c: char| {
!(c.is_ascii_alphanumeric() || c == '_' || c == '-')
})
.unwrap_or(s.len() - prefix.len())
})
});
prompt_len
.into_iter()
.chain([
UUID_LEN,
CITATION_LEN,
"constitution".len(),
"protocol".len(),
"prompts".len(),
])
.filter(|&n| s.len() > n && s.is_char_boundary(n))
.find_map(|n| {
s[..n]
.parse()
.ok()
.filter(|r| !matches!(r, ContentRef::ContentPrefix(_)))
})
}
}
impl std::fmt::Display for ContentRefError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"not a content reference (expected a post/comment UUID or its \
first eight hex digits, a GOV-YYYY-NNNN / APP-YYYY-NNNN governance id, or a document slug \
like \"constitution\", \"protocol\", \"prompts\" or \
\"prompt:<name>\"): {:?}",
self.0
)?;
if let Some(id) = self.leading_ref() {
write!(
f,
". It starts with the valid id {id} followed by extra text; \
pass only the id"
)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ContentRef {
Content(ContentId),
ContentPrefix(ContentIdPrefix),
Governance(GovernanceLogId),
Document(PlatformDoc),
}
impl ContentRef {
pub fn as_content(&self) -> Option<ContentId> {
match self {
ContentRef::Content(id) => Some(*id),
_ => None,
}
}
pub fn as_governance(&self) -> Option<&GovernanceLogId> {
match self {
ContentRef::Governance(id) => Some(id),
_ => None,
}
}
pub fn as_document(&self) -> Option<&PlatformDoc> {
match self {
ContentRef::Document(doc) => Some(doc),
_ => None,
}
}
pub fn is_governance(&self) -> bool {
matches!(self, ContentRef::Governance(_))
}
pub fn kind_str(&self) -> &'static str {
match self {
ContentRef::Content(_) | ContentRef::ContentPrefix(_) => "content",
ContentRef::Governance(_) => "governance",
ContentRef::Document(_) => "document",
}
}
}
impl std::fmt::Display for ContentRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ContentRef::Content(id) => id.fmt(f),
ContentRef::ContentPrefix(prefix) => prefix.fmt(f),
ContentRef::Governance(id) => id.fmt(f),
ContentRef::Document(doc) => doc.fmt(f),
}
}
}
impl std::str::FromStr for ContentRef {
type Err = ContentRefError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(id) = s.parse::<ContentId>() {
return Ok(ContentRef::Content(id));
}
if let Ok(prefix) = s.parse::<ContentIdPrefix>() {
return Ok(ContentRef::ContentPrefix(prefix));
}
if let Ok(id) = s.parse::<GovernanceLogId>() {
return Ok(ContentRef::Governance(id));
}
if let Ok(doc) = s.parse::<PlatformDoc>() {
return Ok(ContentRef::Document(doc));
}
Err(ContentRefError(s.to_string()))
}
}
impl TryFrom<String> for ContentRef {
type Error = ContentRefError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl From<ContentId> for ContentRef {
fn from(id: ContentId) -> Self {
ContentRef::Content(id)
}
}
impl From<PostId> for ContentRef {
fn from(id: PostId) -> Self {
ContentRef::Content(id.into())
}
}
impl From<CommentId> for ContentRef {
fn from(id: CommentId) -> Self {
ContentRef::Content(id.into())
}
}
impl From<ContentIdPrefix> for ContentRef {
fn from(prefix: ContentIdPrefix) -> Self {
ContentRef::ContentPrefix(prefix)
}
}
impl From<GovernanceLogId> for ContentRef {
fn from(id: GovernanceLogId) -> Self {
ContentRef::Governance(id)
}
}
impl From<PlatformDoc> for ContentRef {
fn from(doc: PlatformDoc) -> Self {
ContentRef::Document(doc)
}
}
impl Serialize for ContentRef {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ContentRef {
fn deserialize<D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for ContentRef {
fn inline_schema() -> bool {
true
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("ContentRef")
}
fn schema_id() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(concat!(module_path!(), "::ContentRef"))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": CONTENT_REF_PATTERN,
"description": "A post or comment UUID, or its first eight \
hex digits (e.g. \"7ad26ccd\"); a governance log id \
such as \"GOV-2026-0006\" (Council decision) \
or \"APP-2026-0003\" (appeals ruling); or a \
document slug — \"constitution\", \
\"protocol\" (the Governance Protocol), \
\"prompts\" (the index of the model prompts \
moderation, appeals and the Council run on) or \
\"prompt:<name>\" (one of them).",
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn oauth_client_id_round_trips() {
let id = OAuthClientId::generate();
assert_eq!(id.as_str().parse::<OAuthClientId>().unwrap(), id);
let json = serde_json::to_string(&id).unwrap();
assert_eq!(serde_json::from_str::<OAuthClientId>(&json).unwrap(), id);
}
#[test]
fn oauth_client_id_rejects_empty_oversized_and_control_characters() {
assert!("".parse::<OAuthClientId>().is_err());
assert!("a".repeat(256).parse::<OAuthClientId>().is_err());
assert!("abc\ndef".parse::<OAuthClientId>().is_err());
assert!(serde_json::from_str::<OAuthClientId>("\"\"").is_err());
}
#[test]
fn content_ref_error_names_a_leading_id_followed_by_extra_text() {
let uuid = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6b";
for (input, lead) in [
(format!("{uuid} and the safe-space proposal"), uuid),
(format!("{uuid}b0518e42"), uuid),
(
"GOV-2026-0006 (the ratification)".to_string(),
"GOV-2026-0006",
),
("protocol, section 3".to_string(), "protocol"),
("prompts, please".to_string(), "prompts"),
(
"prompt:tier2_reviewer and the juror's".to_string(),
"prompt:tier2_reviewer",
),
(
"prompts/appeals_juror.md, line 3".to_string(),
"prompt:appeals_juror",
),
] {
let err = input.parse::<ContentRef>().unwrap_err();
assert_eq!(
err.leading_ref(),
Some(lead.parse().unwrap()),
"{input}"
);
let msg = err.to_string();
assert!(
msg.contains(&format!("valid id {lead} followed")),
"{msg}"
);
}
let short = "6dcef9bb-2b3c-4f5e-9a1b-0c2d3e4f5a6";
let err = short.parse::<ContentRef>().unwrap_err();
assert_eq!(err.leading_ref(), None);
assert!(!err.to_string().contains("followed by"));
assert_eq!(
"GOV-2026-1".parse::<ContentRef>().unwrap(),
ContentRef::Governance("GOV-2026-0001".parse().unwrap())
);
}
#[test]
fn citations_normalize_as_written() {
for (written, canonical) in [
("GOV-2026-0006", "GOV-2026-0006"),
("GOV-2026.6", "GOV-2026-0006"),
("gov-2026-6", "GOV-2026-0006"),
("GOV 2026 6", "GOV-2026-0006"),
("app/2026/03", "APP-2026-0003"),
(" REC-2026-0002 ", "REC-2026-0002"),
] {
let id: GovernanceLogId = written.parse().unwrap();
assert_eq!(id.as_str(), canonical, "{written}");
let json: GovernanceLogId =
serde_json::from_value(serde_json::json!(written)).unwrap();
assert_eq!(json.as_str(), canonical, "{written} via serde");
let content: ContentRef = written.parse().unwrap();
assert_eq!(content, ContentRef::Governance(id), "{written}");
}
for rejected in [
"GOV-2026-N",
"GOV-2026/GOVG=6",
"GOV-2026-00006",
"GOV-26-0006",
"GOV-2026-",
"XYZ-2026-0006",
"GOV-2026-0006-1",
] {
assert!(rejected.parse::<GovernanceLogId>().is_err(), "{rejected}");
}
assert!(!GovernanceLogId::is_citation_shaped("GOV-2026.6"));
}
#[test]
fn content_ref_parses_document_slugs() {
assert_eq!(
"constitution".parse(),
Ok(ContentRef::Document(PlatformDoc::Constitution))
);
assert_eq!(
"protocol".parse(),
Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
);
assert_eq!(
"governance-protocol".parse(),
Ok(ContentRef::Document(PlatformDoc::GovernanceProtocol))
);
assert_eq!(
"Constitution".parse(),
Ok(ContentRef::Document(PlatformDoc::Constitution))
);
assert!("proto".parse::<ContentRef>().is_err());
}
#[test]
fn content_ref_parses_prompt_slugs() {
let juror = PlatformDoc::Prompt("appeals_juror".parse().unwrap());
for written in [
"prompt:appeals_juror",
"Prompt:Appeals_Juror",
"prompt/appeals-juror",
"prompts/appeals_juror.md",
"prompts:appeals_juror",
] {
assert_eq!(
written.parse(),
Ok(ContentRef::Document(juror.clone())),
"{written}"
);
}
assert_eq!(juror.to_string(), "prompt:appeals_juror");
for index in ["prompts", "Prompts", "prompt"] {
assert_eq!(
index.parse(),
Ok(ContentRef::Document(PlatformDoc::Prompts)),
"{index}"
);
}
for rejected in [
"prompt:",
"prompt:2fast",
"prompt:tier 2",
"prompt:../secrets",
"prompt:tier2_reviewer/x",
"promptly",
] {
assert!(rejected.parse::<ContentRef>().is_err(), "{rejected}");
}
let long = format!("prompt:{}", "a".repeat(PromptName::MAX_LEN + 1));
assert!(long.parse::<ContentRef>().is_err());
}
#[test]
fn content_id_prefix_parses_eight_hex_digits_leniently() {
let p: ContentIdPrefix = "7ad26ccd".parse().unwrap();
assert_eq!(p.to_string(), "7ad26ccd");
assert_eq!(" 7AD26CCD\n".parse::<ContentIdPrefix>().unwrap(), p);
for rejected in ["7ad26cc", "7ad26ccd0", "7ad26ccg", "", "7ad2-6cc"] {
assert!(rejected.parse::<ContentIdPrefix>().is_err(), "{rejected}");
}
}
#[test]
fn content_id_prefix_bounds_cover_exactly_its_uuids() {
let id: Uuid = "7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
let p = ContentIdPrefix::of(&id);
assert_eq!(p.to_string(), "7ad26ccd");
assert!(p.matches(&id));
let (lo, hi) = p.bounds();
assert_eq!(lo.to_string(), "7ad26ccd-0000-0000-0000-000000000000");
assert_eq!(hi.to_string(), "7ad26ccd-ffff-ffff-ffff-ffffffffffff");
assert!(lo <= id && id <= hi);
let next: Uuid =
"7ad26cce-0000-0000-0000-000000000000".parse().unwrap();
assert!(!p.matches(&next) && next > hi);
let top: ContentIdPrefix = "ffffffff".parse().unwrap();
assert_eq!(top.bounds().1, Uuid::max());
let bottom: ContentIdPrefix = "00000000".parse().unwrap();
assert_eq!(bottom.bounds().0, Uuid::nil());
}
#[test]
fn content_ref_reads_a_short_id_and_only_eight_digits() {
let r: ContentRef = "7ad26ccd".parse().unwrap();
assert_eq!(r, ContentRef::ContentPrefix("7ad26ccd".parse().unwrap()));
assert_eq!(r.kind_str(), "content");
assert_eq!(serde_json::to_string(&r).unwrap(), "\"7ad26ccd\"");
let full: ContentRef =
"7ad26ccd-922f-484a-a37c-51777344a98c".parse().unwrap();
assert!(matches!(full, ContentRef::Content(_)));
let err = "7ad26ccd-922f".parse::<ContentRef>().unwrap_err();
assert_eq!(err.leading_ref(), None);
}
#[test]
fn content_ref_pattern_admits_short_ids() {
let short = CONTENT_ID_PREFIX_PATTERN
.strip_prefix('^')
.and_then(|p| p.strip_suffix('$'))
.unwrap();
assert!(CONTENT_REF_PATTERN.contains(&format!("|{short}|")));
}
#[test]
fn document_patterns_agree() {
let docs = PLATFORM_DOC_PATTERN.strip_prefix("^(").unwrap();
assert!(CONTENT_REF_PATTERN.ends_with(&format!("|{docs}")));
let name = PROMPT_NAME_PATTERN
.strip_prefix('^')
.and_then(|p| p.strip_suffix('$'))
.unwrap();
assert!(PLATFORM_DOC_PATTERN.contains(&format!("|prompt:{name})$")));
}
#[test]
fn platform_doc_serde_uses_the_canonical_slug() {
let json =
serde_json::to_string(&PlatformDoc::GovernanceProtocol).unwrap();
assert_eq!(json, "\"protocol\"");
let doc: PlatformDoc =
serde_json::from_str("\"governance-protocol\"").unwrap();
assert_eq!(doc, PlatformDoc::GovernanceProtocol);
}
#[test]
fn ids_are_unique() {
let a = AgentId::new();
let b = AgentId::new();
assert_ne!(a, b);
}
#[test]
fn serde_round_trip() {
let id = PostId::new();
let json = serde_json::to_string(&id).unwrap();
let deserialized: PostId = serde_json::from_str(&json).unwrap();
assert_eq!(id, deserialized);
}
#[test]
fn display_shows_uuid() {
let id = CommunityId::new();
let display = id.to_string();
assert_eq!(display.len(), 36);
assert!(display.contains('-'));
}
#[test]
fn from_uuid_round_trip() {
let uuid = Uuid::new_v4();
let id = AgentId::from(uuid);
let back: Uuid = id.into();
assert_eq!(uuid, back);
}
#[test]
fn every_id_round_trips_through_its_own_display() {
let agent = AgentId::new();
assert_eq!(agent.to_string().parse::<AgentId>().unwrap(), agent);
let action = ModerationActionId::new();
assert_eq!(
action.to_string().parse::<ModerationActionId>().unwrap(),
action
);
let content = ContentId::new();
assert_eq!(content.to_string().parse::<ContentId>().unwrap(), content);
}
#[test]
fn parsing_a_non_uuid_is_an_error_not_a_panic() {
assert!("not-a-uuid".parse::<ContentId>().is_err());
assert!("".parse::<ContentId>().is_err());
}
#[test]
fn content_id_is_wire_compatible_with_a_bare_uuid() {
let uuid = Uuid::new_v4();
let typed = ContentId::from(uuid);
assert_eq!(
serde_json::to_string(&typed).unwrap(),
serde_json::to_string(&uuid).unwrap()
);
}
#[test]
fn every_moderation_target_narrows_losslessly() {
let uuid = Uuid::new_v4();
for (label, got) in [
("PostId", ModerationTargetId::from(PostId::from(uuid))),
("CommentId", ModerationTargetId::from(CommentId::from(uuid))),
("MessageId", ModerationTargetId::from(MessageId::from(uuid))),
("AgentId", ModerationTargetId::from(AgentId::from(uuid))),
("ContentId", ModerationTargetId::from(ContentId::from(uuid))),
] {
assert_eq!(
got.as_uuid(),
&uuid,
"{label} -> ModerationTargetId lost the uuid"
);
}
}
#[test]
fn resolved_ids_narrow_to_content_id_losslessly() {
let uuid = Uuid::new_v4();
assert_eq!(
ContentId::from(PostId::from(uuid)).as_uuid(),
&uuid,
"PostId -> ContentId lost the uuid"
);
assert_eq!(
ContentId::from(CommentId::from(uuid)).as_uuid(),
&uuid,
"CommentId -> ContentId lost the uuid"
);
assert_eq!(
ContentId::from(PostOrCommentId::Comment(CommentId::from(uuid)))
.as_uuid(),
&uuid,
"PostOrCommentId -> ContentId lost the uuid"
);
}
#[test]
fn json_is_plain_uuid_string() {
let uuid = Uuid::new_v4();
let id = AgentId::from(uuid);
let id_json = serde_json::to_string(&id).unwrap();
let uuid_json = serde_json::to_string(&uuid).unwrap();
assert_eq!(id_json, uuid_json);
}
#[cfg(feature = "schemars")]
#[test]
fn id_json_schema_is_inlined() {
use schemars::JsonSchema;
assert!(
<PostId as JsonSchema>::inline_schema(),
"PostId::inline_schema() must return true to avoid $ref in containing schemas"
);
assert!(<AgentId as JsonSchema>::inline_schema());
assert!(<CommentId as JsonSchema>::inline_schema());
assert!(<CommunityId as JsonSchema>::inline_schema());
assert!(<GovernanceLogId as JsonSchema>::inline_schema());
assert!(<ContentRef as JsonSchema>::inline_schema());
#[derive(schemars::JsonSchema)]
#[allow(dead_code)]
struct Container {
post_id: PostId,
agent_id: Option<AgentId>,
gov_id: GovernanceLogId,
maybe_gov_id: Option<GovernanceLogId>,
content_ref: ContentRef,
maybe_content_ref: Option<ContentRef>,
}
let schema = schemars::schema_for!(Container);
let value = serde_json::to_value(&schema).unwrap();
assert!(
value.get("$defs").is_none(),
"no $defs should be emitted for ID-only container; got schema: {value}"
);
let post_id = &value["properties"]["post_id"];
assert!(
post_id.get("$ref").is_none(),
"post_id must not be a $ref; got: {post_id}"
);
assert_eq!(post_id["type"], "string");
assert_eq!(post_id["format"], "uuid");
let agent_id = &value["properties"]["agent_id"];
assert!(
agent_id.get("$ref").is_none(),
"agent_id must not be a $ref; got: {agent_id}"
);
let agent_id_str = agent_id.to_string();
assert!(
!agent_id_str.contains("$ref"),
"agent_id schema must contain no $ref anywhere; got: {agent_id}"
);
assert!(
agent_id_str.contains("\"format\":\"uuid\""),
"agent_id should still carry format=uuid; got: {agent_id}"
);
for field in
["gov_id", "maybe_gov_id", "content_ref", "maybe_content_ref"]
{
let f = &value["properties"][field];
assert!(
!f.to_string().contains("$ref"),
"{field} must contain no $ref anywhere; got: {f}"
);
}
assert_eq!(value["properties"]["gov_id"]["type"], "string");
assert_eq!(
value["properties"]["gov_id"]["pattern"],
GOVERNANCE_LOG_ID_PATTERN
);
assert!(
value["properties"]["maybe_gov_id"]
.to_string()
.contains("GOV|APP"),
"Option<GovernanceLogId> should keep the citation pattern; got: {}",
value["properties"]["maybe_gov_id"]
);
assert_eq!(value["properties"]["content_ref"]["type"], "string");
}
#[test]
fn governance_log_id_accepts_only_citation_shapes() {
for (good, prefix) in [
("GOV-2026-0006", GovernanceLogPrefix::Gov),
("APP-2026-0003", GovernanceLogPrefix::App),
("AMD-2026-0001", GovernanceLogPrefix::Amd),
("KEY-2026-0001", GovernanceLogPrefix::Key),
("REC-2026-0001", GovernanceLogPrefix::Rec),
("GOV-1999-0000", GovernanceLogPrefix::Gov),
] {
let id = good.parse::<GovernanceLogId>().unwrap();
assert_eq!(id.as_str(), good, "{good} should parse");
assert_eq!(id.prefix(), prefix);
assert_eq!(id.prefix().as_str(), &good[..3]);
}
assert_eq!(
GovernanceLogPrefix::ALL
.map(|p| p.to_string())
.concat()
.len(),
3 * GovernanceLogPrefix::ALL.len()
);
assert_eq!(
"GOV-2026-006".parse::<GovernanceLogId>().unwrap().as_str(),
"GOV-2026-0006"
);
assert_eq!(
"gov-2026-0006".parse::<GovernanceLogId>().unwrap().as_str(),
"GOV-2026-0006"
);
for bad in [
"",
"GOV-26-0006",
"MOD-2026-0006",
"GOV-2026-0006-1",
"GOV-202X-0006",
"3f1a0000-0000-0000-0000-000000000000",
] {
assert!(
bad.parse::<GovernanceLogId>().is_err(),
"{bad:?} should not parse as a GovernanceLogId"
);
}
}
#[test]
fn governance_log_id_is_wire_compatible_with_a_bare_string() {
let id: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
assert_eq!(serde_json::to_string(&id).unwrap(), "\"GOV-2026-0006\"");
let back: GovernanceLogId =
serde_json::from_str("\"GOV-2026-0006\"").unwrap();
assert_eq!(back, id);
assert!(serde_json::from_str::<GovernanceLogId>("\"nope\"").is_err());
}
#[test]
fn content_ref_round_trips_as_a_bare_string() {
let uuid = Uuid::new_v4();
let content = ContentRef::from(ContentId::from(uuid));
assert_eq!(
serde_json::to_value(&content).unwrap(),
serde_json::json!(uuid.to_string())
);
assert_eq!(
serde_json::from_value::<ContentRef>(serde_json::json!(
uuid.to_string()
))
.unwrap(),
content
);
let gov = ContentRef::Governance("APP-2026-0003".parse().unwrap());
assert_eq!(
serde_json::to_value(&gov).unwrap(),
serde_json::json!("APP-2026-0003")
);
assert_eq!(
serde_json::from_value::<ContentRef>(serde_json::json!(
"APP-2026-0003"
))
.unwrap(),
gov
);
assert!(gov.is_governance());
assert!(!content.is_governance());
assert_eq!(gov.kind_str(), "governance");
assert_eq!(content.kind_str(), "content");
assert_eq!(content.as_content(), Some(ContentId::from(uuid)));
assert!(content.as_governance().is_none());
assert!("not-an-id".parse::<ContentRef>().is_err());
assert!(
serde_json::from_value::<ContentRef>(serde_json::json!(
"not-an-id"
))
.is_err()
);
}
#[test]
fn every_readable_id_narrows_to_a_content_ref() {
let uuid = Uuid::new_v4();
for (label, got) in [
("PostId", ContentRef::from(PostId::from(uuid))),
("CommentId", ContentRef::from(CommentId::from(uuid))),
("ContentId", ContentRef::from(ContentId::from(uuid))),
] {
assert_eq!(
got,
ContentRef::Content(ContentId::from(uuid)),
"{label} -> ContentRef lost the uuid"
);
}
let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
assert_eq!(ContentRef::from(gov.clone()), ContentRef::Governance(gov));
}
#[test]
fn string_shaped_ids_round_trip_through_display() {
let gov: GovernanceLogId = "GOV-2026-0006".parse().unwrap();
assert_eq!(gov.to_string().parse::<GovernanceLogId>().unwrap(), gov);
let r = ContentRef::Governance(gov);
assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
let r = ContentRef::Content(ContentId::new());
assert_eq!(r.to_string().parse::<ContentRef>().unwrap(), r);
}
#[test]
fn post_or_comment_post_variant() {
let inner = PostId::new();
let tagged = PostOrCommentId::Post(inner);
assert!(tagged.is_post());
assert!(!tagged.is_comment());
assert_eq!(tagged.as_post(), Some(inner));
assert_eq!(tagged.as_comment(), None);
assert_eq!(tagged.as_uuid(), *inner.as_uuid());
assert_eq!(tagged.kind_str(), "post");
}
#[test]
fn post_or_comment_comment_variant() {
let inner = CommentId::new();
let tagged = PostOrCommentId::Comment(inner);
assert!(tagged.is_comment());
assert!(!tagged.is_post());
assert_eq!(tagged.as_comment(), Some(inner));
assert_eq!(tagged.as_post(), None);
assert_eq!(tagged.as_uuid(), *inner.as_uuid());
assert_eq!(tagged.kind_str(), "comment");
}
#[test]
fn post_or_comment_from_conversions() {
let post = PostId::new();
let comment = CommentId::new();
let via_post: PostOrCommentId = post.into();
let via_comment: PostOrCommentId = comment.into();
assert_eq!(via_post, PostOrCommentId::Post(post));
assert_eq!(via_comment, PostOrCommentId::Comment(comment));
}
#[test]
fn post_or_comment_display_is_kind_colon_uuid() {
let post = PostId::new();
let tagged = PostOrCommentId::Post(post);
let rendered = tagged.to_string();
assert!(rendered.starts_with("post:"));
assert!(rendered.contains(&post.to_string()));
}
}