Skip to main content

nenjo_content/
lib.rs

1//! Storage-neutral content contracts for Nenjo.
2//!
3//! Artifact references identify immutable plaintext content without exposing
4//! platform authorization context, object-store locations, worker cache paths,
5//! or decrypted bytes. Raw wire values are parsed into these types once at a
6//! boundary so downstream code can rely on their invariants.
7
8use std::fmt;
9use std::str::FromStr;
10
11use mime::Mime;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use uuid::Uuid;
14
15const SHA256_HEX_LENGTH: usize = 64;
16const MAX_ARTIFACT_INSTRUCTION_CHARS: usize = 16_384;
17
18/// An invalid storage-neutral content value.
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum ContentValueError {
21    /// Artifact identities must refer to a real immutable object.
22    #[error("artifact id cannot be nil")]
23    NilArtifactId,
24    /// Artifact digests use one canonical algorithm-qualified representation.
25    #[error("artifact digest must use sha256:<64 lowercase or uppercase hexadecimal characters>")]
26    InvalidSha256Digest,
27    /// Artifact media types must be concrete, syntactically valid MIME values.
28    #[error("invalid artifact media type '{value}'")]
29    InvalidMediaType { value: String },
30    /// Optional artifact-specific instructions cannot be empty when present.
31    #[error("artifact instruction cannot be empty")]
32    EmptyArtifactInstruction,
33    /// Artifact instructions are bounded before entering a model context.
34    #[error("artifact instruction exceeds {max_chars} characters")]
35    ArtifactInstructionTooLong { max_chars: usize },
36}
37
38/// Immutable artifact identity.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct ArtifactId(Uuid);
41
42impl ArtifactId {
43    /// Parse an artifact identity, rejecting the nil UUID sentinel.
44    pub fn parse(value: Uuid) -> Result<Self, ContentValueError> {
45        if value.is_nil() {
46            return Err(ContentValueError::NilArtifactId);
47        }
48        Ok(Self(value))
49    }
50
51    /// Return the UUID representation used by existing platform APIs.
52    pub const fn as_uuid(self) -> Uuid {
53        self.0
54    }
55}
56
57impl fmt::Display for ArtifactId {
58    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59        self.0.fmt(formatter)
60    }
61}
62
63impl TryFrom<Uuid> for ArtifactId {
64    type Error = ContentValueError;
65
66    fn try_from(value: Uuid) -> Result<Self, Self::Error> {
67        Self::parse(value)
68    }
69}
70
71impl From<ArtifactId> for Uuid {
72    fn from(value: ArtifactId) -> Self {
73        value.as_uuid()
74    }
75}
76
77impl Serialize for ArtifactId {
78    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
79    where
80        S: Serializer,
81    {
82        self.0.serialize(serializer)
83    }
84}
85
86impl<'de> Deserialize<'de> for ArtifactId {
87    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
88    where
89        D: Deserializer<'de>,
90    {
91        let value = Uuid::deserialize(deserializer)?;
92        Self::parse(value).map_err(serde::de::Error::custom)
93    }
94}
95
96/// Canonical SHA-256 digest in `sha256:<hex>` form.
97#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
98pub struct Sha256Digest(String);
99
100impl Sha256Digest {
101    /// Parse and normalize an algorithm-qualified SHA-256 digest.
102    pub fn parse(value: &str) -> Result<Self, ContentValueError> {
103        let Some(hex) = value.strip_prefix("sha256:") else {
104            return Err(ContentValueError::InvalidSha256Digest);
105        };
106        if hex.len() != SHA256_HEX_LENGTH || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
107            return Err(ContentValueError::InvalidSha256Digest);
108        }
109        Ok(Self(format!("sha256:{}", hex.to_ascii_lowercase())))
110    }
111
112    /// Return the canonical algorithm-qualified value.
113    pub fn as_str(&self) -> &str {
114        &self.0
115    }
116
117    /// Return the lowercase digest component for safe cache-key construction.
118    pub fn hex(&self) -> &str {
119        self.0
120            .strip_prefix("sha256:")
121            .expect("validated digest always has the sha256 prefix")
122    }
123}
124
125impl fmt::Display for Sha256Digest {
126    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127        formatter.write_str(self.as_str())
128    }
129}
130
131impl FromStr for Sha256Digest {
132    type Err = ContentValueError;
133
134    fn from_str(value: &str) -> Result<Self, Self::Err> {
135        Self::parse(value)
136    }
137}
138
139impl Serialize for Sha256Digest {
140    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
141    where
142        S: Serializer,
143    {
144        serializer.serialize_str(self.as_str())
145    }
146}
147
148impl<'de> Deserialize<'de> for Sha256Digest {
149    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
150    where
151        D: Deserializer<'de>,
152    {
153        let value = String::deserialize(deserializer)?;
154        Self::parse(&value).map_err(serde::de::Error::custom)
155    }
156}
157
158/// Parsed, concrete MIME type for immutable artifact plaintext.
159#[derive(Debug, Clone, PartialEq, Eq, Hash)]
160pub struct MediaType(Mime);
161
162impl MediaType {
163    /// Parse a MIME value and reject wildcard media ranges.
164    pub fn parse(value: &str) -> Result<Self, ContentValueError> {
165        let trimmed = value.trim();
166        let parsed = trimmed
167            .parse::<Mime>()
168            .map_err(|_| ContentValueError::InvalidMediaType {
169                value: value.to_owned(),
170            })?;
171        if parsed.type_() == mime::STAR || parsed.subtype() == mime::STAR {
172            return Err(ContentValueError::InvalidMediaType {
173                value: value.to_owned(),
174            });
175        }
176        Ok(Self(parsed))
177    }
178
179    /// Return the parsed MIME value.
180    pub fn as_mime(&self) -> &Mime {
181        &self.0
182    }
183
184    /// Return the MIME type and subtype without parameters.
185    pub fn essence_str(&self) -> &str {
186        self.0.essence_str()
187    }
188
189    /// Return whether this media type conventionally carries UTF-8 model-facing text.
190    pub fn is_utf8_text(&self) -> bool {
191        is_utf8_text_media_type(self.essence_str())
192    }
193
194    /// Return whether this media type identifies a PDF document.
195    pub fn is_pdf(&self) -> bool {
196        self.essence_str() == "application/pdf"
197    }
198}
199
200/// Classify storage-neutral media types whose plaintext bytes may be decoded as UTF-8.
201///
202/// Actual bytes are still validated before use. This function classifies the declared
203/// representation; it does not trust the declaration as proof of valid text.
204pub fn is_utf8_text_media_type(media_type: &str) -> bool {
205    let essence = media_type
206        .split(';')
207        .next()
208        .map(str::trim)
209        .unwrap_or_default();
210    essence.starts_with("text/")
211        || matches!(
212            essence,
213            "application/json"
214                | "application/ld+json"
215                | "application/csv"
216                | "application/x-csv"
217                | "application/xml"
218                | "application/javascript"
219                | "application/ecmascript"
220                | "application/yaml"
221                | "application/x-yaml"
222                | "application/toml"
223                | "image/svg+xml"
224        )
225        || (essence.starts_with("application/")
226            && (essence.ends_with("+json") || essence.ends_with("+xml")))
227}
228
229impl fmt::Display for MediaType {
230    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231        self.0.fmt(formatter)
232    }
233}
234
235impl FromStr for MediaType {
236    type Err = ContentValueError;
237
238    fn from_str(value: &str) -> Result<Self, Self::Err> {
239        Self::parse(value)
240    }
241}
242
243impl Serialize for MediaType {
244    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
245    where
246        S: Serializer,
247    {
248        serializer.collect_str(self)
249    }
250}
251
252impl<'de> Deserialize<'de> for MediaType {
253    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
254    where
255        D: Deserializer<'de>,
256    {
257        let value = String::deserialize(deserializer)?;
258        Self::parse(&value).map_err(serde::de::Error::custom)
259    }
260}
261
262/// Authoritative plaintext byte length of an immutable artifact.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
264#[serde(transparent)]
265pub struct ArtifactSize(u64);
266
267impl ArtifactSize {
268    /// Construct an artifact plaintext size. Empty artifacts are valid.
269    pub const fn new(bytes: u64) -> Self {
270        Self(bytes)
271    }
272
273    /// Return the plaintext byte count.
274    pub const fn bytes(self) -> u64 {
275        self.0
276    }
277}
278
279impl From<u64> for ArtifactSize {
280    fn from(value: u64) -> Self {
281        Self::new(value)
282    }
283}
284
285/// Storage-neutral reference to one immutable artifact revision.
286#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
287pub struct ArtifactRef {
288    id: ArtifactId,
289    digest: Sha256Digest,
290    media_type: MediaType,
291    size: ArtifactSize,
292}
293
294impl ArtifactRef {
295    /// Construct a reference from already parsed values.
296    pub const fn new(
297        id: ArtifactId,
298        digest: Sha256Digest,
299        media_type: MediaType,
300        size: ArtifactSize,
301    ) -> Self {
302        Self {
303            id,
304            digest,
305            media_type,
306            size,
307        }
308    }
309
310    /// Return the immutable artifact identity.
311    pub const fn id(&self) -> ArtifactId {
312        self.id
313    }
314
315    /// Return the authoritative plaintext digest.
316    pub fn digest(&self) -> &Sha256Digest {
317        &self.digest
318    }
319
320    /// Return the authoritative plaintext media type.
321    pub fn media_type(&self) -> &MediaType {
322        &self.media_type
323    }
324
325    /// Return the authoritative plaintext length.
326    pub const fn size(&self) -> ArtifactSize {
327        self.size
328    }
329}
330
331/// Origin of an artifact in an agent input.
332///
333/// This provenance is durable and storage neutral. It does not grant access;
334/// authorization remains bound to the authenticated runtime context.
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
336#[serde(rename_all = "snake_case")]
337pub enum ArtifactInputSource {
338    UserAttachment,
339    TaskInput,
340    ToolResult,
341    SessionContext,
342}
343
344/// Optional, bounded instruction associated with an artifact input.
345#[derive(Debug, Clone, PartialEq, Eq, Hash)]
346pub struct ArtifactInstruction(String);
347
348impl ArtifactInstruction {
349    /// Parse a non-empty instruction suitable for model context.
350    pub fn parse(value: &str) -> Result<Self, ContentValueError> {
351        let trimmed = value.trim();
352        if trimmed.is_empty() {
353            return Err(ContentValueError::EmptyArtifactInstruction);
354        }
355        if trimmed.chars().count() > MAX_ARTIFACT_INSTRUCTION_CHARS {
356            return Err(ContentValueError::ArtifactInstructionTooLong {
357                max_chars: MAX_ARTIFACT_INSTRUCTION_CHARS,
358            });
359        }
360        Ok(Self(trimmed.to_owned()))
361    }
362
363    /// Return the normalized instruction.
364    pub fn as_str(&self) -> &str {
365        &self.0
366    }
367}
368
369impl fmt::Display for ArtifactInstruction {
370    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
371        formatter.write_str(self.as_str())
372    }
373}
374
375impl FromStr for ArtifactInstruction {
376    type Err = ContentValueError;
377
378    fn from_str(value: &str) -> Result<Self, Self::Err> {
379        Self::parse(value)
380    }
381}
382
383impl Serialize for ArtifactInstruction {
384    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
385    where
386        S: Serializer,
387    {
388        serializer.serialize_str(self.as_str())
389    }
390}
391
392impl<'de> Deserialize<'de> for ArtifactInstruction {
393    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
394    where
395        D: Deserializer<'de>,
396    {
397        let value = String::deserialize(deserializer)?;
398        Self::parse(&value).map_err(serde::de::Error::custom)
399    }
400}
401
402/// Durable, unresolved artifact input carried through tools and conversations.
403#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
404pub struct ArtifactInput {
405    artifact: ArtifactRef,
406    source: ArtifactInputSource,
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    instruction: Option<ArtifactInstruction>,
409}
410
411impl ArtifactInput {
412    /// Construct an artifact input from validated values.
413    pub const fn new(artifact: ArtifactRef, source: ArtifactInputSource) -> Self {
414        Self {
415            artifact,
416            source,
417            instruction: None,
418        }
419    }
420
421    /// Attach a validated model-facing instruction.
422    pub fn with_instruction(mut self, instruction: ArtifactInstruction) -> Self {
423        self.instruction = Some(instruction);
424        self
425    }
426
427    pub fn artifact(&self) -> &ArtifactRef {
428        &self.artifact
429    }
430
431    pub const fn source(&self) -> ArtifactInputSource {
432        self.source
433    }
434
435    pub fn instruction(&self) -> Option<&ArtifactInstruction> {
436        self.instruction.as_ref()
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    fn valid_id() -> Uuid {
445        Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").expect("valid fixture")
446    }
447
448    #[test]
449    fn artifact_id_rejects_nil_at_construction_and_deserialization() {
450        assert_eq!(
451            ArtifactId::parse(Uuid::nil()),
452            Err(ContentValueError::NilArtifactId)
453        );
454        assert!(serde_json::from_str::<ArtifactId>(&format!("\"{}\"", Uuid::nil())).is_err());
455    }
456
457    #[test]
458    fn digest_normalizes_hex_and_rejects_invalid_values() {
459        let digest =
460            Sha256Digest::parse(&format!("sha256:{}", "A".repeat(64))).expect("valid digest");
461        assert_eq!(digest.hex(), "a".repeat(64));
462        assert_eq!(digest.as_str(), format!("sha256:{}", "a".repeat(64)));
463        assert!(Sha256Digest::parse(&"a".repeat(64)).is_err());
464        assert!(Sha256Digest::parse(&format!("sha256:{}", "z".repeat(64))).is_err());
465    }
466
467    #[test]
468    fn media_type_is_concrete_and_normalized() {
469        let media_type = MediaType::parse(" image/png ").expect("valid MIME type");
470        assert_eq!(media_type.essence_str(), "image/png");
471        assert!(MediaType::parse("image/*").is_err());
472        assert!(MediaType::parse("not a mime type").is_err());
473    }
474
475    #[test]
476    fn utf8_text_media_types_cover_structured_documents() {
477        for media_type in [
478            "text/plain",
479            "text/markdown; charset=utf-8",
480            "application/json",
481            "application/problem+json",
482            "application/csv",
483            "application/x-csv",
484            "application/xml",
485            "application/atom+xml",
486            "application/yaml",
487            "application/toml",
488            "application/javascript",
489            "image/svg+xml",
490        ] {
491            assert!(is_utf8_text_media_type(media_type), "{media_type}");
492        }
493        assert!(!is_utf8_text_media_type("application/pdf"));
494        assert!(!is_utf8_text_media_type("application/vnd.ms-excel"));
495        assert!(!is_utf8_text_media_type("application/octet-stream"));
496    }
497
498    #[test]
499    fn artifact_reference_round_trip_preserves_validated_values() {
500        let reference = ArtifactRef::new(
501            ArtifactId::parse(valid_id()).expect("valid artifact id"),
502            Sha256Digest::parse(&format!("sha256:{}", "b".repeat(64))).expect("valid digest"),
503            MediaType::parse("image/png").expect("valid MIME type"),
504            ArtifactSize::new(42),
505        );
506
507        let encoded = serde_json::to_value(&reference).expect("serialize reference");
508        let decoded: ArtifactRef =
509            serde_json::from_value(encoded.clone()).expect("deserialize reference");
510
511        assert_eq!(decoded, reference);
512        assert_eq!(encoded["id"], valid_id().to_string());
513        assert_eq!(encoded["size"], 42);
514    }
515
516    #[test]
517    fn artifact_input_preserves_provenance_without_authority_fields() {
518        let reference = ArtifactRef::new(
519            ArtifactId::parse(valid_id()).expect("valid artifact id"),
520            Sha256Digest::parse(&format!("sha256:{}", "c".repeat(64))).expect("valid digest"),
521            MediaType::parse("image/png").expect("valid MIME type"),
522            ArtifactSize::new(42),
523        );
524        let input = ArtifactInput::new(reference, ArtifactInputSource::ToolResult)
525            .with_instruction(ArtifactInstruction::parse(" inspect the error ").unwrap());
526
527        let encoded = serde_json::to_value(&input).expect("serialize artifact input");
528        let decoded: ArtifactInput = serde_json::from_value(encoded.clone()).unwrap();
529
530        assert_eq!(decoded, input);
531        assert_eq!(encoded["source"], "tool_result");
532        assert_eq!(encoded["instruction"], "inspect the error");
533        assert!(encoded.get("org_id").is_none());
534        assert!(encoded.get("path").is_none());
535        assert!(encoded.get("bytes").is_none());
536    }
537
538    #[test]
539    fn artifact_instruction_rejects_empty_and_unbounded_values() {
540        assert_eq!(
541            ArtifactInstruction::parse("  "),
542            Err(ContentValueError::EmptyArtifactInstruction)
543        );
544        assert!(
545            ArtifactInstruction::parse(&"x".repeat(MAX_ARTIFACT_INSTRUCTION_CHARS + 1)).is_err()
546        );
547    }
548}