Cotton code
67 lines · 2.6 KB · RustRaw
//! Typed facts for a serving Mac's temporarily held AI work.//!//! The stored device column is JSON, but the facts it carries stay structured//! so a surface can resolve the clock and reason in its own vocabulary.use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};/// Why a serving Mac is holding AI work.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum AiHoldReason {    AnthropicCredits,}/// One provider hold, retained until a successful paid call clears it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct AiHold {    pub held_until: DateTime<Utc>,    pub reason: AiHoldReason,}impl AiHold {    /// Decode only the structured payload this version writes. Earlier prose    /// is deliberately absent: parsing display words would make them data.    pub fn from_json(text: &str) -> Option<Self> {        serde_json::from_str(text).ok()    }    /// Decode the wire payload with the same strict shape as stored JSON.    pub fn from_value(value: &Value) -> Option<Self> {        serde_json::from_value(value.clone()).ok()    }    /// The typed device columns a definition reads. It owns no display words.    pub fn columns(&self) -> Map<String, Value> {        let mut columns = Map::new();        columns.insert("held_until".into(), serde_json::to_value(&self.held_until).expect("AI hold stamp serializes"));        columns.insert("hold_reason".into(), serde_json::to_value(self.reason).expect("AI hold reason serializes"));        columns    }}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// RULE: A hold is typed facts only. Malformed timestamps, unknown reasons,    /// and the old composed prose never become a device's display columns.    #[test]    fn only_a_typed_hold_projects_columns() {        let value = json!({"held_until":"2026-10-16T12:30:00Z","reason":"anthropic_credits"});        let hold = AiHold::from_value(&value).expect("typed hold");        assert_eq!(hold.columns(), serde_json::from_value::<Map<String, Value>>(json!({"held_until":"2026-10-16T12:30:00Z","hold_reason":"anthropic_credits"})).unwrap());        assert_eq!(serde_json::to_value(&hold).unwrap(), value);        for invalid in [            json!({"held_until":"not a stamp","reason":"anthropic_credits"}),            json!({"held_until":"2026-10-16T12:30:00Z","reason":"other"}),            json!("paused until 2026-10-16T12:30:00Z · Anthropic credits"),        ] {            assert!(AiHold::from_value(&invalid).is_none(), "{invalid}");        }    }}