Skip to main content

aidaemon_work/mandates/
mod.rs

1pub mod budget;
2pub mod card;
3pub mod history;
4pub mod policy;
5pub mod validate;
6
7pub use aidaemon_events::mandate_grant::MandateAuthorityGrant;
8
9use std::collections::BTreeSet;
10
11use serde::{Deserialize, Serialize};
12
13use aidaemon_tools::semantics::ToolCallOperation;
14
15const MAX_MANDATE_OBJECTIVE_TEXT: usize = 2 * 1024;
16const MAX_MANDATE_POLICY_ENTRIES: usize = 16;
17const MAX_MANDATE_POLICY_ENTRY_TEXT: usize = 500;
18const MAX_MANDATE_POLICY_TEXT: usize = 8 * 1024;
19const MAX_MANDATE_AUTHORITY_JSON: usize = 16 * 1024;
20const MAX_DECISION_RATIONALE_TEXT: usize = 2 * 1024;
21const MAX_DECISION_OBSERVATIONS: usize = 8;
22const MAX_DECISION_OBSERVATION_TEXT: usize = 750;
23const MAX_DECISION_OBSERVATIONS_JSON: usize = 6 * 1024;
24const MAX_DECISION_QUESTION_TEXT: usize = 500;
25const MAX_INTENTION_DESCRIPTION_TEXT: usize = 1024;
26/// Longest intention metadata a mandate stores; the tool that writes it
27/// checks against the same limit.
28pub const MAX_INTENTION_METADATA_TEXT: usize = 4 * 1024;
29const MAX_MANDATE_STRATEGY_BODY_TEXT: usize = 16 * 1024;
30const MAX_MANDATE_LEARNING_NOTE_TEXT: usize = 1024;
31const MAX_MANDATE_EVIDENCE_REFS: usize = 16;
32
33fn text_within(value: &str, max: usize) -> bool {
34    value.chars().count() <= max && value.len() <= max
35}
36
37/// Most action outcomes one decision may record.
38pub const MAX_MANDATE_ACTION_OUTCOMES: usize = 16;
39/// Most published links one owner notice names.
40pub const MAX_NOTICE_PUBLISHED_LINKS: usize = 8;
41
42/// A machine id of a resource a mutation created: `[A-Za-z0-9_-]{1,64}`.
43pub fn is_canonical_resource_id(value: &str) -> bool {
44    !value.is_empty()
45        && value.len() <= 64
46        && value
47            .bytes()
48            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
49}
50
51/// A format key an ACT declares: `[a-z0-9_-]{1,64}`.
52pub fn is_canonical_format_key(value: &str) -> bool {
53    !value.is_empty()
54        && value.len() <= 64
55        && value.bytes().all(|byte| {
56            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-')
57        })
58}
59
60/// The X post-creation endpoints, matched exactly against a mutation's
61/// canonical target URL (a machine format, never prose).
62const X_POST_CREATE_URLS: [&str; 2] = [
63    "https://api.x.com/2/tweets",
64    "https://api.twitter.com/2/tweets",
65];
66
67/// The owner-facing link for a resource a succeeded mutation created, built
68/// only from typed parts: a post created through the X posts endpoint with a
69/// numeric id becomes its canonical status URL; any other canonical id is
70/// shown as `id:<id>`. Anything else yields `None`.
71pub fn canonical_published_link(
72    targets: &[MandateMutationTarget],
73    external_resource_id: &str,
74) -> Option<String> {
75    let numeric = (1..=32).contains(&external_resource_id.len())
76        && external_resource_id
77            .bytes()
78            .all(|byte| byte.is_ascii_digit());
79    let x_post = targets.iter().any(|target| {
80        target.kind == "url" && X_POST_CREATE_URLS.contains(&target.identifier.as_str())
81    });
82    if x_post && numeric {
83        Some(format!("https://x.com/i/status/{external_resource_id}"))
84    } else if is_canonical_resource_id(external_resource_id) {
85        Some(format!("id:{external_resource_id}"))
86    } else {
87        None
88    }
89}
90
91/// Whether a link is one [`canonical_published_link`] can produce.
92fn is_canonical_published_link(link: &str) -> bool {
93    if let Some(id) = link.strip_prefix("https://x.com/i/status/") {
94        (1..=32).contains(&id.len()) && id.bytes().all(|byte| byte.is_ascii_digit())
95    } else {
96        link.strip_prefix("id:")
97            .is_some_and(is_canonical_resource_id)
98    }
99}
100
101fn canonical_text_within(value: &str, max: usize) -> bool {
102    !value.is_empty() && value.trim() == value && text_within(value, max)
103}
104
105fn canonical_scoped_resource_suffix(value: &str) -> bool {
106    if value.is_empty() || value.len() > 192 {
107        return false;
108    }
109    let bytes = value.as_bytes();
110    let mut index = 0usize;
111    while index < bytes.len() {
112        let byte = bytes[index];
113        if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-') {
114            index += 1;
115        } else if byte == b'%'
116            && index + 2 < bytes.len()
117            && bytes[index + 1].is_ascii_hexdigit()
118            && bytes[index + 2].is_ascii_hexdigit()
119            && !bytes[index + 1].is_ascii_lowercase()
120            && !bytes[index + 2].is_ascii_lowercase()
121        {
122            index += 3;
123        } else {
124            return false;
125        }
126    }
127    true
128}
129
130/// Owner-approved authority envelope for autonomous work.
131///
132/// A mandate delegates an objective and a bounded set of actions to the agent.
133/// It is deliberately separate from a personal goal (a desired outcome) and
134/// from an intention (the agent's revocable commitment for one decision cycle).
135#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
136#[serde(rename_all = "snake_case")]
137pub enum MandateStatus {
138    Active,
139    Paused,
140    AwaitingInput,
141    Completed,
142    Cancelled,
143}
144
145impl MandateStatus {
146    pub const fn as_str(self) -> &'static str {
147        match self {
148            Self::Active => "active",
149            Self::Paused => "paused",
150            Self::AwaitingInput => "awaiting_input",
151            Self::Completed => "completed",
152            Self::Cancelled => "cancelled",
153        }
154    }
155
156    pub fn parse(value: &str) -> Option<Self> {
157        match value {
158            "active" => Some(Self::Active),
159            "paused" => Some(Self::Paused),
160            "awaiting_input" => Some(Self::AwaitingInput),
161            "completed" => Some(Self::Completed),
162            "cancelled" => Some(Self::Cancelled),
163            _ => None,
164        }
165    }
166
167    /// Legal authority-epoch transitions. Terminal states never reopen.
168    pub const fn can_transition_to(self, next: Self) -> bool {
169        matches!(
170            (self, next),
171            (
172                Self::Active,
173                Self::Paused | Self::AwaitingInput | Self::Completed | Self::Cancelled
174            ) | (Self::Paused, Self::Active | Self::Cancelled)
175                | (Self::AwaitingInput, Self::Active | Self::Cancelled)
176        )
177    }
178
179    pub const fn is_terminal(self) -> bool {
180        matches!(self, Self::Completed | Self::Cancelled)
181    }
182}
183
184impl std::fmt::Display for MandateStatus {
185    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        formatter.write_str(self.as_str())
187    }
188}
189
190/// Owner-selected operating posture for a mandate.
191///
192/// This is persisted policy, not a classification inferred from conversation
193/// text. `Autopilot` changes how the worker handles routine judgment and
194/// recovery inside the exact authority envelope; it never widens that
195/// envelope by itself.
196#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
197#[serde(rename_all = "snake_case")]
198pub enum MandateAutonomyMode {
199    #[default]
200    Bounded,
201    Autopilot,
202}
203
204impl MandateAutonomyMode {
205    pub const fn as_str(self) -> &'static str {
206        match self {
207            Self::Bounded => "bounded",
208            Self::Autopilot => "autopilot",
209        }
210    }
211
212    pub fn parse(value: &str) -> Option<Self> {
213        match value {
214            "bounded" => Some(Self::Bounded),
215            "autopilot" => Some(Self::Autopilot),
216            _ => None,
217        }
218    }
219
220    pub const fn is_autopilot(self) -> bool {
221        matches!(self, Self::Autopilot)
222    }
223}
224
225impl std::fmt::Display for MandateAutonomyMode {
226    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        formatter.write_str(self.as_str())
228    }
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
232pub struct Mandate {
233    pub id: String,
234    /// Continuous orchestration goal used by the durable scheduler/executor.
235    pub goal_id: String,
236    /// Optional personal goal that motivated this delegation.
237    pub source_goal_id: Option<String>,
238    /// The short name the owner gave the mandate when creating it, as the
239    /// model passed it (never parsed from the objective). Shown in lists and
240    /// cards, and a selector for later actions.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub name: Option<String>,
243    pub objective: String,
244    pub status: MandateStatus,
245    /// Explicit owner-confirmed operating posture. This is separate from the
246    /// authority envelope so selecting Autopilot cannot authorize a new tool,
247    /// operation, target, account, effect, or query parameter.
248    #[serde(default)]
249    pub autonomy_mode: MandateAutonomyMode,
250    pub authority: MandateAuthority,
251    /// Owner-confirmed, immutable strategy material. This may guide how the
252    /// objective is pursued, but it never contributes authority.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub strategy: Option<MandateStrategySnapshot>,
255    /// Owner-confirmed measurable control loop. This is policy state, not a
256    /// promise that the external metric will improve.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub objective_control: Option<MandateObjectiveControl>,
259    /// Typed reason for a non-active, non-terminal lifecycle state.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub suspension: Option<MandateSuspension>,
262    pub constraints: Vec<String>,
263    pub success_criteria: Vec<String>,
264    pub stop_conditions: Vec<String>,
265    /// Lower and upper bounds for an agent-selected next review.
266    pub min_review_secs: i64,
267    pub max_review_secs: i64,
268    pub default_review_secs: i64,
269    /// Human-readable resource policy. Runtime token arithmetic is derived
270    /// internally from this effort level and the review cadence.
271    pub review_effort: String,
272    /// Durable next wake time for the MAPE-K deliberation loop.
273    pub next_review_at: String,
274    /// Short-lived single-writer lease used by heartbeat dispatch.
275    pub review_lease_token: Option<String>,
276    pub review_lease_expires_at: Option<String>,
277    pub expires_at: Option<String>,
278    /// Durable proof that the owner explicitly confirmed this delegation.
279    /// Pending-confirmation mandates keep this NULL and cannot be activated or
280    /// resumed through ordinary lifecycle transitions.
281    pub confirmed_at: Option<String>,
282    /// Authority epoch, incremented whenever owner-controlled configuration or
283    /// lifecycle state changes so stale decisions and updates fail closed.
284    pub version: i64,
285    /// Stable authorization principal. Session/bot routes may be linked or
286    /// moved without changing this identity or inferring equivalence from a
287    /// session-name suffix.
288    pub owner_principal_id: String,
289    pub created_by_session: String,
290    pub created_at: String,
291    pub updated_at: String,
292}
293
294impl Mandate {
295    #[allow(clippy::too_many_arguments)]
296    pub fn new(
297        goal_id: &str,
298        source_goal_id: Option<String>,
299        objective: &str,
300        created_by_session: &str,
301        authority: MandateAuthority,
302        min_review_secs: i64,
303        max_review_secs: i64,
304        default_review_secs: i64,
305    ) -> Self {
306        let now = chrono::Utc::now().to_rfc3339();
307        let next_review_at =
308            (chrono::Utc::now() + chrono::Duration::seconds(default_review_secs)).to_rfc3339();
309        Self {
310            id: uuid::Uuid::new_v4().to_string(),
311            goal_id: goal_id.to_string(),
312            source_goal_id,
313            name: None,
314            objective: objective.trim().to_string(),
315            status: MandateStatus::Active,
316            autonomy_mode: MandateAutonomyMode::Bounded,
317            authority,
318            strategy: None,
319            objective_control: None,
320            suspension: None,
321            constraints: Vec::new(),
322            success_criteria: Vec::new(),
323            stop_conditions: Vec::new(),
324            min_review_secs,
325            max_review_secs,
326            default_review_secs,
327            review_effort: "balanced".to_string(),
328            next_review_at,
329            review_lease_token: None,
330            review_lease_expires_at: None,
331            expires_at: None,
332            // `new` constructs an active mandate. Callers creating a deferred
333            // controller must explicitly clear this proof before persistence.
334            confirmed_at: Some(now.clone()),
335            version: 1,
336            owner_principal_id: aidaemon_events::session::stable_private_owner_principal_id(
337                created_by_session,
338            )
339            .unwrap_or_else(|| format!("principal:{}", uuid::Uuid::new_v4())),
340            created_by_session: created_by_session.to_string(),
341            created_at: now.clone(),
342            updated_at: now,
343        }
344    }
345
346    /// Whether the owner gave this mandate `name` (trimmed, ignoring case).
347    pub fn has_name(&self, name: &str) -> bool {
348        self.name
349            .as_deref()
350            .is_some_and(|own| own.trim().eq_ignore_ascii_case(name.trim()))
351    }
352
353    /// When the next review will wake this mandate; `None` unless it is
354    /// active, because only active mandates are ever claimed.
355    pub fn scheduled_next_review(&self) -> Option<&str> {
356        self.is_active().then_some(self.next_review_at.as_str())
357    }
358
359    pub fn is_active(&self) -> bool {
360        if self.status != MandateStatus::Active || self.confirmed_at.is_none() {
361            return false;
362        }
363        match self.expires_at.as_deref() {
364            None => true,
365            Some(value) => chrono::DateTime::parse_from_rfc3339(value)
366                .is_ok_and(|expires| expires > chrono::Utc::now()),
367        }
368    }
369
370    pub fn clamp_review_secs(&self, requested: Option<i64>) -> i64 {
371        requested
372            .unwrap_or(self.default_review_secs)
373            .clamp(self.min_review_secs, self.max_review_secs)
374    }
375
376    /// Deterministic activity-to-cadence edge in the proactive review graph.
377    /// The result always remains inside the owner-confirmed bounds.
378    pub fn review_secs_for_activity(&self, activity: MandateActivityLevel) -> i64 {
379        let requested = match activity {
380            MandateActivityLevel::Quiet => self.default_review_secs,
381            MandateActivityLevel::Active => self.default_review_secs / 3,
382            MandateActivityLevel::Urgent => self.min_review_secs,
383        };
384        self.clamp_review_secs(Some(requested))
385    }
386
387    /// Choose the next durable review time without ever scheduling work past
388    /// the owner-approved expiry boundary.
389    pub fn bounded_next_review_at(
390        &self,
391        requested_secs: Option<i64>,
392        now: chrono::DateTime<chrono::Utc>,
393    ) -> String {
394        let candidate = now + chrono::Duration::seconds(self.clamp_review_secs(requested_secs));
395        self.expires_at
396            .as_deref()
397            .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
398            .map(|expires| expires.with_timezone(&chrono::Utc))
399            .filter(|expires| *expires < candidate)
400            .unwrap_or(candidate)
401            .to_rfc3339()
402    }
403
404    /// Content bounds shared by every mandate ingestion path. Persistence
405    /// calls this again so callers cannot bypass the owner-facing tool schema.
406    pub fn validate_content_bounds(&self) -> Result<(), String> {
407        if !canonical_text_within(&self.objective, MAX_MANDATE_OBJECTIVE_TEXT) {
408            return Err(
409                "mandate objective must be canonical non-empty text of at most 2 KiB in both characters and bytes"
410                    .to_string(),
411            );
412        }
413        if !matches!(
414            self.review_effort.as_str(),
415            "efficient" | "balanced" | "thorough" | "legacy_custom"
416        ) {
417            return Err(
418                "mandate review_effort must be efficient, balanced, thorough, or legacy_custom"
419                    .to_string(),
420            );
421        }
422        if let Some(strategy) = self.strategy.as_ref() {
423            strategy.validate()?;
424        }
425        if let Some(control) = self.objective_control.as_ref() {
426            control.validate()?;
427        }
428        if let Some(suspension) = self.suspension.as_ref() {
429            suspension.validate()?;
430        }
431
432        let mut total_chars = 0usize;
433        let mut total_bytes = 0usize;
434        for (label, values) in [
435            ("constraints", &self.constraints),
436            ("success criteria", &self.success_criteria),
437            ("stop conditions", &self.stop_conditions),
438        ] {
439            if values.len() > MAX_MANDATE_POLICY_ENTRIES {
440                return Err(format!("mandate {label} cannot exceed 16 entries"));
441            }
442            for value in values {
443                if !canonical_text_within(value, MAX_MANDATE_POLICY_ENTRY_TEXT) {
444                    return Err(format!(
445                        "each mandate {label} entry must be canonical non-empty text of at most 500 characters and bytes"
446                    ));
447                }
448                total_chars = total_chars.saturating_add(value.chars().count());
449                total_bytes = total_bytes.saturating_add(value.len());
450            }
451        }
452        if total_chars > MAX_MANDATE_POLICY_TEXT || total_bytes > MAX_MANDATE_POLICY_TEXT {
453            return Err(
454                "mandate constraints, success criteria, and stop conditions exceed their combined 8 KiB character/byte bound"
455                    .to_string(),
456            );
457        }
458        Ok(())
459    }
460}
461
462#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
463#[serde(rename_all = "snake_case")]
464pub enum ObjectiveMetricDirection {
465    AtLeast,
466    AtMost,
467}
468
469/// A measured objective: a number the mandate works to move to a target.
470/// Values use caller-declared micro-units to avoid floating-point drift.
471///
472/// New mandates no longer set one; it is kept, read-only, for a mandate that
473/// was confirmed with one, so its reviews still record and read the metric.
474/// Settings older rows also carry (experiment cohort and window, minimum
475/// effect, stagnation and failure budgets) are ignored.
476#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
477pub struct MandateObjectiveControl {
478    pub schema_version: u16,
479    pub metric_name: String,
480    pub unit: String,
481    pub baseline_micros: i64,
482    pub target_micros: i64,
483    pub direction: ObjectiveMetricDirection,
484    /// Exact analytics endpoint or stable metric-source resource identity.
485    pub measurement_source: String,
486    pub measurement_cadence_secs: i64,
487    pub baseline_observed_at: String,
488}
489
490impl MandateObjectiveControl {
491    pub const SCHEMA_VERSION: u16 = 1;
492
493    /// Checks every setting. An error names the one setting that is wrong.
494    pub fn validate(&self) -> Result<(), String> {
495        if self.schema_version != Self::SCHEMA_VERSION {
496            return Err(format!(
497                "schema_version is {}; it must be {}",
498                self.schema_version,
499                Self::SCHEMA_VERSION
500            ));
501        }
502        for (field, value, max) in [
503            ("metric_name", &self.metric_name, 128),
504            ("unit", &self.unit, 64),
505        ] {
506            if !canonical_text_within(value, max) {
507                return Err(format!(
508                    "{field} must be plain text of 1 to {max} characters with no surrounding spaces"
509                ));
510            }
511        }
512        let source_valid = reqwest::Url::parse(&self.measurement_source)
513            .ok()
514            .is_some_and(|url| {
515                url.scheme() == "https"
516                    && url.host_str().is_some()
517                    && url.fragment().is_none()
518                    && url.username().is_empty()
519                    && url.password().is_none()
520            })
521            || self
522                .measurement_source
523                .strip_prefix("metric_source:")
524                .is_some_and(canonical_scoped_resource_suffix);
525        if !source_valid {
526            return Err(
527                "measurement_source must be an HTTPS URL (no login details or #fragment) or an exact metric_source: identity"
528                    .to_string(),
529            );
530        }
531        const MAX_CADENCE_SECS: i64 = 30 * 24 * 60 * 60;
532        if !(60..=MAX_CADENCE_SECS).contains(&self.measurement_cadence_secs) {
533            return Err(format!(
534                "measurement_cadence_secs is {}; allowed: 60 to {MAX_CADENCE_SECS} (1 minute to 30 days)",
535                self.measurement_cadence_secs
536            ));
537        }
538        if chrono::DateTime::parse_from_rfc3339(&self.baseline_observed_at).is_err() {
539            return Err(format!(
540                "baseline_observed_at is {:?}; it must be an RFC 3339 time such as 2026-01-31T09:00:00Z",
541                self.baseline_observed_at
542            ));
543        }
544        Ok(())
545    }
546
547    pub fn target_reached(&self, value_micros: i64) -> bool {
548        match self.direction {
549            ObjectiveMetricDirection::AtLeast => value_micros >= self.target_micros,
550            ObjectiveMetricDirection::AtMost => value_micros <= self.target_micros,
551        }
552    }
553
554    /// When the next measurement is due: one cadence after the latest
555    /// recorded observation, or one cadence after the baseline when nothing
556    /// has been measured yet. A value in the past means a measurement is due
557    /// now. Returns `None` only when neither timestamp parses.
558    pub fn next_measurement_at(&self, latest_observed_at: Option<&str>) -> Option<String> {
559        let anchor = latest_observed_at
560            .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
561            .or_else(|| chrono::DateTime::parse_from_rfc3339(&self.baseline_observed_at).ok())?;
562        let cadence = chrono::Duration::seconds(self.measurement_cadence_secs.max(0));
563        Some(
564            (anchor + cadence)
565                .with_timezone(&chrono::Utc)
566                .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
567        )
568    }
569}
570
571/// One immutable observation of a measured objective. Receipt IDs prove the
572/// measurement.
573#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
574pub struct MandateObjectiveMeasurement {
575    pub id: String,
576    pub mandate_id: String,
577    pub mandate_version: i64,
578    pub goal_run_id: String,
579    pub value_micros: i64,
580    pub confidence_bps: u16,
581    pub evidence_receipt_ids: Vec<String>,
582    pub observed_at: String,
583    pub created_at: String,
584}
585
586impl MandateObjectiveMeasurement {
587    pub fn new(
588        mandate_id: &str,
589        mandate_version: i64,
590        goal_run_id: &str,
591        value_micros: i64,
592        confidence_bps: u16,
593        evidence_receipt_ids: Vec<String>,
594        observed_at: &str,
595    ) -> Self {
596        Self {
597            id: uuid::Uuid::new_v4().to_string(),
598            mandate_id: mandate_id.to_string(),
599            mandate_version,
600            goal_run_id: goal_run_id.to_string(),
601            value_micros,
602            confidence_bps,
603            evidence_receipt_ids,
604            observed_at: observed_at.to_string(),
605            created_at: chrono::Utc::now().to_rfc3339(),
606        }
607    }
608
609    pub fn validate(&self) -> Result<(), String> {
610        if self.mandate_version <= 0
611            || self.confidence_bps > 10_000
612            || self.evidence_receipt_ids.is_empty()
613            || self.evidence_receipt_ids.len() > MAX_MANDATE_EVIDENCE_REFS
614            || chrono::DateTime::parse_from_rfc3339(&self.observed_at).is_err()
615        {
616            return Err("objective measurement metadata is invalid".to_string());
617        }
618        for id in &self.evidence_receipt_ids {
619            if !canonical_text_within(id, 256) {
620                return Err("objective measurement identifiers are invalid".to_string());
621            }
622        }
623        Ok(())
624    }
625}
626
627/// A content-addressed copy of one owner-approved skill. The snapshot body is
628/// persisted so a later filesystem edit cannot silently change a live mandate.
629#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
630pub struct MandateStrategySnapshot {
631    pub skill_name: String,
632    pub snapshot_version: u16,
633    pub content_sha256: String,
634    pub description: String,
635    pub body: String,
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub source: Option<String>,
638}
639
640impl MandateStrategySnapshot {
641    pub const SCHEMA_VERSION: u16 = 1;
642
643    pub fn validate(&self) -> Result<(), String> {
644        if self.snapshot_version != Self::SCHEMA_VERSION {
645            return Err("unsupported mandate strategy snapshot version".to_string());
646        }
647        if !canonical_text_within(&self.skill_name, 256) {
648            return Err(
649                "strategy skill_name must be canonical text of at most 256 bytes".to_string(),
650            );
651        }
652        if self.content_sha256.len() != 64
653            || !self
654                .content_sha256
655                .bytes()
656                .all(|byte| byte.is_ascii_hexdigit())
657        {
658            return Err("strategy content_sha256 must be a 64-character hex digest".to_string());
659        }
660        if !text_within(&self.description, 1024)
661            || !canonical_text_within(&self.body, MAX_MANDATE_STRATEGY_BODY_TEXT)
662        {
663            return Err(
664                "strategy description/body exceed their bounded canonical form".to_string(),
665            );
666        }
667        if self
668            .source
669            .as_deref()
670            .is_some_and(|source| !canonical_text_within(source, 512))
671        {
672            return Err("strategy source exceeds its canonical 512-byte bound".to_string());
673        }
674        Ok(())
675    }
676}
677
678#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
679#[serde(rename_all = "snake_case")]
680pub enum MandateSuspensionKind {
681    OwnerPaused,
682    AwaitingAnswer,
683    ReconciliationRequired,
684    ExecutionLeaseLost,
685    ReviewFailed,
686    AuthorityRevokedWithUnresolvedMutation,
687}
688
689impl MandateSuspensionKind {
690    pub const fn as_str(self) -> &'static str {
691        match self {
692            Self::OwnerPaused => "owner_paused",
693            Self::AwaitingAnswer => "awaiting_answer",
694            Self::ReconciliationRequired => "reconciliation_required",
695            Self::ExecutionLeaseLost => "execution_lease_lost",
696            Self::ReviewFailed => "review_failed",
697            Self::AuthorityRevokedWithUnresolvedMutation => {
698                "authority_revoked_with_unresolved_mutation"
699            }
700        }
701    }
702}
703
704#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
705pub struct MandateSuspension {
706    pub kind: MandateSuspensionKind,
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub reason_code: Option<String>,
709    #[serde(default, skip_serializing_if = "Option::is_none")]
710    pub decision_cycle_id: Option<String>,
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub goal_run_id: Option<String>,
713    pub created_at: String,
714}
715
716/// Whether one exact delegated adapter operation observes or mutates state.
717/// This is owner-approved policy data, not an inference from prose.
718#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
719#[serde(rename_all = "snake_case")]
720pub enum MandateOperationKind {
721    Observation,
722    Mutation,
723}
724
725/// One non-combinable authority tuple.
726///
727/// Keeping tool, adapter operation, effects, and targets in the same record
728/// prevents the unsafe Cartesian product created by independent allowlists
729/// (for example, GET on one URL accidentally authorizing POST to that URL).
730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
731pub struct MandateOperationScope {
732    pub tool: String,
733    pub operation: ToolCallOperation,
734    pub kind: MandateOperationKind,
735    #[serde(default)]
736    pub target_prefixes: Vec<String>,
737    /// Query parameter names whose values may be selected at execution time.
738    ///
739    /// A query embedded in a URL target remains an exact authorization. This
740    /// separate list is the explicit owner-approved escape hatch for APIs such
741    /// as search, where the observation is bounded by endpoint and parameter
742    /// name but the value is deliberately chosen during each review.
743    #[serde(default, skip_serializing_if = "Vec::is_empty")]
744    pub allowed_query_params: Vec<String>,
745    #[serde(default)]
746    pub mutation_effects: Vec<String>,
747}
748
749impl MandateOperationScope {
750    pub fn validate(&self) -> Result<(), String> {
751        if self.tool.trim() != self.tool
752            || !text_within(&self.tool, 256)
753            || !MandateAuthority::DELEGABLE_DATA_TOOLS.contains(&self.tool.as_str())
754        {
755            return Err(format!(
756                "operation scope tool must be an exact delegable adapter name: {}",
757                MandateAuthority::DELEGABLE_DATA_TOOLS.join(", ")
758            ));
759        }
760        if self.target_prefixes.is_empty() || self.target_prefixes.len() > 16 {
761            return Err("operation scopes require 1–16 exact target prefixes".to_string());
762        }
763        for (index, prefix) in self.target_prefixes.iter().enumerate() {
764            validate_mandate_target_prefix(prefix)?;
765            if self.target_prefixes[..index]
766                .iter()
767                .any(|seen| seen == prefix)
768            {
769                return Err("operation scope target prefixes must be unique".to_string());
770            }
771        }
772        let url_targets = self
773            .target_prefixes
774            .iter()
775            .filter(|target| target.contains("://"))
776            .count();
777        if url_targets == 0 {
778            return Err("delegated operation scopes require a URL target".to_string());
779        }
780        if self.allowed_query_params.len() > 16 {
781            return Err("operation scope query parameters exceed their bounded size".to_string());
782        }
783        for (index, name) in self.allowed_query_params.iter().enumerate() {
784            if name.trim() != name
785                || name.is_empty()
786                || name.len() > 128
787                || !name.bytes().all(|byte| {
788                    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b'[' | b']')
789                })
790                || self.allowed_query_params[..index]
791                    .iter()
792                    .any(|seen| seen == name)
793            {
794                return Err(
795                    "operation scope query parameters must be unique canonical parameter names"
796                        .to_string(),
797                );
798            }
799        }
800        if !self.allowed_query_params.is_empty()
801            && self.target_prefixes.iter().any(|target| {
802                reqwest::Url::parse(target)
803                    .ok()
804                    .is_some_and(|url| url.query().is_some())
805            })
806        {
807            return Err(
808                "operation scopes must use either an exact URL query or allowed_query_params, not both"
809                    .to_string(),
810            );
811        }
812        let auth_targets = self
813            .target_prefixes
814            .iter()
815            .filter(|target| target.starts_with("auth_profile:"))
816            .count();
817        let account_targets = self
818            .target_prefixes
819            .iter()
820            .filter(|target| target.starts_with("account:"))
821            .count();
822        if auth_targets > 1 || account_targets > 1 || (auth_targets == 1) != (account_targets == 1)
823        {
824            return Err(
825                "authenticated operation scopes require exactly one auth_profile target paired with exactly one account target"
826                    .to_string(),
827            );
828        }
829        let requires_bound_identity = self.tool == "http_request"
830            && self.target_prefixes.iter().any(|target| {
831                let Ok(url) = reqwest::Url::parse(target) else {
832                    return false;
833                };
834                matches!(url.host_str(), Some("api.x.com" | "api.twitter.com"))
835            });
836        if requires_bound_identity && (auth_targets != 1 || account_targets != 1) {
837            return Err(
838                "X API operation scopes require exact auth_profile: and account: identity targets in every authenticated operation"
839                    .to_string(),
840            );
841        }
842        if self.mutation_effects.len() > MandateAuthority::EFFECT_NAMES.len() {
843            return Err("operation scope mutation effects exceed their bounded size".to_string());
844        }
845        for (index, effect) in self.mutation_effects.iter().enumerate() {
846            if effect.trim() != effect
847                || !MandateAuthority::EFFECT_NAMES.contains(&effect.as_str())
848                || self.mutation_effects[..index]
849                    .iter()
850                    .any(|seen| seen == effect)
851            {
852                return Err(
853                    "operation scope mutation effects must be unique canonical effect names"
854                        .to_string(),
855                );
856            }
857        }
858
859        match (self.tool.as_str(), self.operation, self.kind) {
860            ("web_fetch", ToolCallOperation::Get, MandateOperationKind::Observation) => {
861                if auth_targets != 0 || account_targets != 0 {
862                    return Err(
863                        "web_fetch operation scopes cannot carry authentication identity"
864                            .to_string(),
865                    );
866                }
867                if !self.mutation_effects.is_empty() {
868                    return Err(
869                        "observation operation scopes cannot declare mutation effects".to_string(),
870                    );
871                }
872            }
873            (
874                "http_request",
875                ToolCallOperation::Get | ToolCallOperation::Head | ToolCallOperation::Options,
876                MandateOperationKind::Observation,
877            ) => {
878                if !self.mutation_effects.is_empty() {
879                    return Err(
880                        "observation operation scopes cannot declare mutation effects".to_string(),
881                    );
882                }
883            }
884            (
885                "http_request",
886                ToolCallOperation::Post | ToolCallOperation::Put | ToolCallOperation::Patch,
887                MandateOperationKind::Mutation,
888            ) => {
889                let expected = BTreeSet::from([
890                    "external_delivery".to_string(),
891                    "remote_mutation".to_string(),
892                ]);
893                if self
894                    .mutation_effects
895                    .iter()
896                    .cloned()
897                    .collect::<BTreeSet<_>>()
898                    != expected
899                {
900                    return Err(
901                        "body-bearing HTTP mutation scopes require exactly remote_mutation and external_delivery effects"
902                            .to_string(),
903                    );
904                }
905            }
906            ("http_request", ToolCallOperation::Delete, MandateOperationKind::Mutation) => {
907                if self.mutation_effects.as_slice() != ["remote_mutation"] {
908                    return Err(
909                        "HTTP DELETE mutation scopes require exactly the remote_mutation effect"
910                            .to_string(),
911                    );
912                }
913            }
914            _ => {
915                return Err(
916                    "operation scope kind/operation is not supported by the selected delegable adapter"
917                        .to_string(),
918                );
919            }
920        }
921        if self.kind != MandateOperationKind::Observation && !self.allowed_query_params.is_empty() {
922            return Err(
923                "dynamic query parameters are supported only for observation operation scopes"
924                    .to_string(),
925            );
926        }
927        Ok(())
928    }
929}
930
931impl MandateSuspension {
932    pub fn new(kind: MandateSuspensionKind, reason_code: Option<String>) -> Self {
933        Self {
934            kind,
935            reason_code,
936            decision_cycle_id: None,
937            goal_run_id: None,
938            created_at: chrono::Utc::now().to_rfc3339(),
939        }
940    }
941
942    pub fn validate(&self) -> Result<(), String> {
943        if self
944            .reason_code
945            .as_deref()
946            .is_some_and(|value| !canonical_text_within(value, 256))
947            || self
948                .decision_cycle_id
949                .as_deref()
950                .is_some_and(|value| !canonical_text_within(value, 256))
951            || self
952                .goal_run_id
953                .as_deref()
954                .is_some_and(|value| !canonical_text_within(value, 256))
955        {
956            return Err("mandate suspension identifiers exceed their canonical bounds".to_string());
957        }
958        chrono::DateTime::parse_from_rfc3339(&self.created_at)
959            .map_err(|_| "mandate suspension created_at must be RFC3339".to_string())?;
960        Ok(())
961    }
962}
963
964/// Deterministic action policy attached to a mandate.
965///
966/// `allowed_tools` applies to both observations and mutations so a mandate
967/// cannot read unrelated private state and then exfiltrate it through an
968/// otherwise-authorized output tool. Patterns are exact names or a scoped
969/// exact v1 data-tool names only; wildcard authority is rejected so a future
970/// adapter cannot silently inherit an old delegation.
971/// V1 rejects MCP tools until their manifests and effect semantics can be
972/// owner-pinned instead of trusted from a live server advertisement.
973#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
974pub struct MandateAuthority {
975    #[serde(default = "default_allow_observations")]
976    pub allow_observations: bool,
977    #[serde(default)]
978    pub allowed_tools: Vec<String>,
979    #[serde(default)]
980    pub allowed_mutation_effects: Vec<String>,
981    #[serde(default)]
982    pub allowed_target_prefixes: Vec<String>,
983    /// V2 non-combinable operation tuples. When present, the runtime matches a
984    /// call against one complete tuple and never authorizes from the aggregate
985    /// compatibility lists above.
986    #[serde(default, skip_serializing_if = "Vec::is_empty")]
987    pub operation_scopes: Vec<MandateOperationScope>,
988    #[serde(default)]
989    pub max_mutating_actions_per_cycle: u32,
990    /// Cross-cycle dispatch ceiling. Every claimed mutation attempt, including
991    /// a failed or ambiguous one, consumes one slot for a rolling 24-hour
992    /// window; a reservation abandoned before the final I/O claim does not.
993    #[serde(default)]
994    pub max_mutating_actions_per_rolling_24h: u32,
995    /// Minimum wall-clock separation between two claimed mutation dispatches
996    /// for this mandate. Observation cycles are deliberately unaffected.
997    #[serde(default)]
998    pub min_seconds_between_mutations: u32,
999    /// The owner asked to be told what the mandate finds ("tell me when it
1000    /// is down"). It lets a WAIT carry one owner alert
1001    /// ([`MandateDecisionCycle::owner_alert`]); it grants no tool, target or
1002    /// effect. Absent in policies written before it existed, which keeps
1003    /// their confirmed hashes unchanged.
1004    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1005    pub owner_alerts: bool,
1006}
1007
1008fn default_allow_observations() -> bool {
1009    true
1010}
1011
1012impl Default for MandateAuthority {
1013    fn default() -> Self {
1014        Self {
1015            allow_observations: true,
1016            allowed_tools: Vec::new(),
1017            allowed_mutation_effects: Vec::new(),
1018            allowed_target_prefixes: Vec::new(),
1019            operation_scopes: Vec::new(),
1020            max_mutating_actions_per_cycle: 0,
1021            max_mutating_actions_per_rolling_24h: 0,
1022            min_seconds_between_mutations: 0,
1023            owner_alerts: false,
1024        }
1025    }
1026}
1027
1028impl MandateAuthority {
1029    /// V1 delegates only directly governed network data adapters. Protocol
1030    /// controls are classified separately and never gain authority merely by
1031    /// appearing in this list.
1032    pub const DELEGABLE_DATA_TOOLS: &'static [&'static str] = &["http_request", "web_fetch"];
1033    /// Adapters that can execute an opaque nested action loop. Their inner
1034    /// reads and writes cannot be target-scoped or metered one-by-one by the
1035    /// mandate gate, so they are never delegable as a single allowed tool.
1036    pub const NON_DELEGABLE_TOOLS: &'static [&'static str] = &[
1037        "cli_agent",
1038        "terminal",
1039        "browser",
1040        "computer_use",
1041        "health_probe",
1042        "manage_automations",
1043        "schedule_task",
1044        "read_file",
1045        "write_file",
1046        "edit_file",
1047        "search_files",
1048        "send_file",
1049        "check_environment",
1050    ];
1051
1052    pub const EFFECT_NAMES: &'static [&'static str] = &[
1053        "local_source_write",
1054        "local_workspace_write",
1055        "local_derived_write",
1056        "repository_write",
1057        "remote_mutation",
1058        "remote_deploy",
1059        "external_delivery",
1060        "process_state",
1061        "configuration",
1062        "destructive",
1063        "unspecified",
1064    ];
1065
1066    pub fn from_operation_scopes(
1067        allow_observations: bool,
1068        operation_scopes: Vec<MandateOperationScope>,
1069        max_mutating_actions_per_cycle: u32,
1070        max_mutating_actions_per_rolling_24h: u32,
1071        min_seconds_between_mutations: u32,
1072    ) -> Self {
1073        let allowed_tools = operation_scopes
1074            .iter()
1075            .map(|scope| scope.tool.clone())
1076            .collect::<BTreeSet<_>>()
1077            .into_iter()
1078            .collect();
1079        let allowed_mutation_effects = operation_scopes
1080            .iter()
1081            .flat_map(|scope| scope.mutation_effects.iter().cloned())
1082            .collect::<BTreeSet<_>>()
1083            .into_iter()
1084            .collect();
1085        let allowed_target_prefixes = operation_scopes
1086            .iter()
1087            .flat_map(|scope| scope.target_prefixes.iter().cloned())
1088            .collect::<BTreeSet<_>>()
1089            .into_iter()
1090            .collect();
1091        Self {
1092            allow_observations,
1093            allowed_tools,
1094            allowed_mutation_effects,
1095            allowed_target_prefixes,
1096            operation_scopes,
1097            max_mutating_actions_per_cycle,
1098            max_mutating_actions_per_rolling_24h,
1099            min_seconds_between_mutations,
1100            owner_alerts: false,
1101        }
1102    }
1103
1104    /// The same policy, with or without the owner-alert grant.
1105    pub fn with_owner_alerts(mut self, owner_alerts: bool) -> Self {
1106        self.owner_alerts = owner_alerts;
1107        self
1108    }
1109
1110    pub fn uses_operation_scopes(&self) -> bool {
1111        !self.operation_scopes.is_empty()
1112    }
1113
1114    pub fn validate(&self) -> Result<(), String> {
1115        if self.operation_scopes.len() > 64 {
1116            return Err("mandate operation scopes exceed their bounded size".to_string());
1117        }
1118        for (index, scope) in self.operation_scopes.iter().enumerate() {
1119            scope.validate()?;
1120            if self.operation_scopes[..index]
1121                .iter()
1122                .any(|seen| seen == scope)
1123            {
1124                return Err("mandate operation scopes must be unique".to_string());
1125            }
1126        }
1127        if self.uses_operation_scopes() {
1128            let derived = Self::from_operation_scopes(
1129                self.allow_observations,
1130                self.operation_scopes.clone(),
1131                self.max_mutating_actions_per_cycle,
1132                self.max_mutating_actions_per_rolling_24h,
1133                self.min_seconds_between_mutations,
1134            );
1135            if self.allowed_tools.iter().collect::<BTreeSet<_>>()
1136                != derived.allowed_tools.iter().collect::<BTreeSet<_>>()
1137                || self
1138                    .allowed_mutation_effects
1139                    .iter()
1140                    .collect::<BTreeSet<_>>()
1141                    != derived
1142                        .allowed_mutation_effects
1143                        .iter()
1144                        .collect::<BTreeSet<_>>()
1145                || self.allowed_target_prefixes.iter().collect::<BTreeSet<_>>()
1146                    != derived
1147                        .allowed_target_prefixes
1148                        .iter()
1149                        .collect::<BTreeSet<_>>()
1150            {
1151                return Err(
1152                    "mandate aggregate authority lists must exactly match the operation scope projection"
1153                        .to_string(),
1154                );
1155            }
1156            if !self.allow_observations
1157                && self
1158                    .operation_scopes
1159                    .iter()
1160                    .any(|scope| scope.kind == MandateOperationKind::Observation)
1161            {
1162                return Err(
1163                    "observation operation scopes require allow_observations=true".to_string(),
1164                );
1165            }
1166            let has_mutation = self
1167                .operation_scopes
1168                .iter()
1169                .any(|scope| scope.kind == MandateOperationKind::Mutation);
1170            if has_mutation != (self.max_mutating_actions_per_cycle > 0) {
1171                return Err(
1172                    "operation scopes and per-cycle mutation budget must agree on whether mutations are delegated"
1173                        .to_string(),
1174                );
1175            }
1176        }
1177        let authority_text = self
1178            .allowed_tools
1179            .iter()
1180            .chain(&self.allowed_mutation_effects)
1181            .chain(&self.allowed_target_prefixes);
1182        let authority_text_chars = authority_text
1183            .clone()
1184            .map(|value| value.chars().count())
1185            .sum::<usize>();
1186        let authority_text_bytes = authority_text.map(String::len).sum::<usize>();
1187        if authority_text_chars > MAX_MANDATE_AUTHORITY_JSON
1188            || authority_text_bytes > MAX_MANDATE_AUTHORITY_JSON
1189        {
1190            return Err(
1191                "mandate authority exceeds its total 16 KiB text character/byte bound".to_string(),
1192            );
1193        }
1194        let serialized = serde_json::to_string(self)
1195            .map_err(|error| format!("mandate authority cannot be serialized: {error}"))?;
1196        if !text_within(&serialized, MAX_MANDATE_AUTHORITY_JSON) {
1197            return Err(
1198                "mandate authority exceeds its total serialized 16 KiB character/byte bound"
1199                    .to_string(),
1200            );
1201        }
1202        if self.allowed_tools.len() > 64
1203            || self.allowed_target_prefixes.len() > 64
1204            || self.allowed_mutation_effects.len() > Self::EFFECT_NAMES.len()
1205        {
1206            return Err("mandate authority lists exceed their bounded size".to_string());
1207        }
1208        for (index, pattern) in self.allowed_tools.iter().enumerate() {
1209            let trimmed = pattern.trim();
1210            let wildcard_count = trimmed.bytes().filter(|byte| *byte == b'*').count();
1211            if trimmed.is_empty() || trimmed != pattern || wildcard_count != 0 {
1212                return Err(
1213                    "allowed_tools must use canonical exact names; wildcards are not allowed"
1214                        .to_string(),
1215                );
1216            }
1217            if !text_within(pattern, 256)
1218                || self.allowed_tools[..index]
1219                    .iter()
1220                    .any(|seen| seen == pattern)
1221            {
1222                return Err(
1223                    "allowed_tools must be unique and at most 256 characters and bytes each"
1224                        .to_string(),
1225                );
1226            }
1227            if trimmed.starts_with("mcp__") {
1228                return Err(
1229                    "MCP tools cannot be delegated by a v1 mandate because server-advertised safety hints are not owner-pinned authority facts; use a directly governed adapter such as http_request"
1230                        .to_string(),
1231                );
1232            }
1233            if !Self::DELEGABLE_DATA_TOOLS.contains(&trimmed) {
1234                return Err(format!(
1235                    "{trimmed} is not a directly governed v1 mandate data tool"
1236                ));
1237            }
1238            let covered_non_delegable = Self::NON_DELEGABLE_TOOLS.iter().find(|tool_name| {
1239                trimmed == **tool_name
1240                    || trimmed
1241                        .strip_suffix('*')
1242                        .is_some_and(|prefix| tool_name.starts_with(prefix))
1243            });
1244            if let Some(tool_name) = covered_non_delegable {
1245                return Err(format!(
1246                    "{tool_name} cannot be delegated by a mandate because its nested actions cannot be target-scoped and metered individually"
1247                ));
1248            }
1249        }
1250        if let Some(invalid) = self.allowed_mutation_effects.iter().find(|effect| {
1251            effect.trim() != effect.as_str() || !Self::EFFECT_NAMES.contains(&effect.as_str())
1252        }) {
1253            return Err(format!(
1254                "unknown mutation effect `{invalid}`; valid effects: {}",
1255                Self::EFFECT_NAMES.join(", ")
1256            ));
1257        }
1258        if self
1259            .allowed_mutation_effects
1260            .iter()
1261            .enumerate()
1262            .any(|(index, effect)| {
1263                self.allowed_mutation_effects[..index]
1264                    .iter()
1265                    .any(|seen| seen == effect)
1266            })
1267        {
1268            return Err("allowed_mutation_effects must be unique".to_string());
1269        }
1270        if self.max_mutating_actions_per_cycle > 0 && self.allowed_tools.is_empty() {
1271            return Err(
1272                "max_mutating_actions_per_cycle is non-zero but no mutation tools are allowed"
1273                    .to_string(),
1274            );
1275        }
1276        if self.max_mutating_actions_per_cycle > 0 && self.allowed_mutation_effects.is_empty() {
1277            return Err(
1278                "max_mutating_actions_per_cycle is non-zero but no mutation effects are allowed"
1279                    .to_string(),
1280            );
1281        }
1282        if self.max_mutating_actions_per_cycle > 0 && self.allowed_target_prefixes.is_empty() {
1283            return Err(
1284                "mutation-enabled mandates require explicit typed target prefixes".to_string(),
1285            );
1286        }
1287        if !self.allowed_tools.is_empty() && self.allowed_target_prefixes.is_empty() {
1288            return Err(
1289                "delegated observations require explicit typed target prefixes".to_string(),
1290            );
1291        }
1292        if self.max_mutating_actions_per_cycle == 0 {
1293            if self.max_mutating_actions_per_rolling_24h != 0
1294                || self.min_seconds_between_mutations != 0
1295            {
1296                return Err(
1297                    "rolling mutation quota and cooldown require a positive per-cycle mutation budget"
1298                        .to_string(),
1299                );
1300            }
1301        } else {
1302            if self.max_mutating_actions_per_rolling_24h == 0 {
1303                return Err(
1304                    "mutation-enabled mandates require max_mutating_actions_per_rolling_24h"
1305                        .to_string(),
1306                );
1307            }
1308            if self.max_mutating_actions_per_rolling_24h > 24 {
1309                return Err(
1310                    "max_mutating_actions_per_rolling_24h cannot exceed the hard ceiling of 24"
1311                        .to_string(),
1312                );
1313            }
1314            if self.max_mutating_actions_per_rolling_24h < self.max_mutating_actions_per_cycle {
1315                return Err(
1316                    "max_mutating_actions_per_rolling_24h must be at least the per-cycle mutation budget"
1317                        .to_string(),
1318                );
1319            }
1320            if self.min_seconds_between_mutations < 900 {
1321                return Err(
1322                    "mutation-enabled mandates require at least 900 seconds between mutations"
1323                        .to_string(),
1324                );
1325            }
1326        }
1327        for (index, prefix) in self.allowed_target_prefixes.iter().enumerate() {
1328            if prefix.trim().is_empty()
1329                || prefix.trim() != prefix
1330                || !text_within(prefix, 2_048)
1331                || self.allowed_target_prefixes[..index]
1332                    .iter()
1333                    .any(|seen| seen == prefix)
1334            {
1335                return Err(
1336                    "allowed_target_prefixes must be unique non-empty canonical prefixes of at most 2048 characters and bytes"
1337                        .to_string(),
1338                );
1339            }
1340            validate_mandate_target_prefix(prefix)?;
1341        }
1342        Ok(())
1343    }
1344
1345    pub fn allows_tool(&self, tool_name: &str) -> bool {
1346        self.allowed_tools.iter().any(|raw| raw == tool_name)
1347    }
1348
1349    pub fn allows_effect(&self, effect: &str) -> bool {
1350        self.allowed_mutation_effects
1351            .iter()
1352            .any(|allowed| allowed.trim() == effect)
1353    }
1354}
1355
1356fn validate_mandate_target_prefix(prefix: &str) -> Result<(), String> {
1357    if prefix.contains("://") {
1358        let url = reqwest::Url::parse(prefix)
1359            .map_err(|_| "URL target prefixes must be canonical URLs".to_string())?;
1360        let well_formed = matches!(url.scheme(), "http" | "https")
1361            && url.host_str().is_some()
1362            && url.username().is_empty()
1363            && url.password().is_none()
1364            && url.fragment().is_none();
1365        // A target covers everything below it, so the site root would grant
1366        // the whole site. Refuse it, and say how to name what is meant.
1367        if well_formed && matches!(url.path(), "" | "/") {
1368            let origin = url.origin().ascii_serialization();
1369            return Err(format!(
1370                "URL target {prefix} is the site root, which would cover the whole site. Name the exact page or path to check instead, as {origin}/<page> (for the front page, the page the site serves there, such as {origin}/index.html), and confirm that path with the owner."
1371            ));
1372        }
1373        if !well_formed || matches!(url.path(), "" | "/") {
1374            return Err(
1375                "URL target prefixes require an http(s) origin plus a non-root path and cannot contain userinfo or fragments"
1376                    .to_string(),
1377            );
1378        }
1379    } else {
1380        let suffix = prefix
1381            .strip_prefix("auth_profile:")
1382            .or_else(|| prefix.strip_prefix("account:"));
1383        if !suffix.is_some_and(canonical_scoped_resource_suffix) {
1384            return Err(
1385                "v1 resource targets must be exact auth_profile: or account: identifiers with a non-empty canonical suffix"
1386                    .to_string(),
1387            );
1388        }
1389    }
1390    Ok(())
1391}
1392
1393#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1394#[serde(rename_all = "snake_case")]
1395pub enum MandateDecisionOutcome {
1396    Act,
1397    Wait,
1398    Ask,
1399    Stop,
1400}
1401
1402/// Typed signal describing how quickly the mandate should look again.
1403///
1404/// This affects only the next wake time inside the owner's confirmed review
1405/// bounds. It never changes tools, targets, quotas, or any other authority.
1406#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
1407#[serde(rename_all = "snake_case")]
1408pub enum MandateActivityLevel {
1409    #[default]
1410    Quiet,
1411    Active,
1412    Urgent,
1413}
1414
1415impl MandateActivityLevel {
1416    pub const fn as_str(self) -> &'static str {
1417        match self {
1418            Self::Quiet => "quiet",
1419            Self::Active => "active",
1420            Self::Urgent => "urgent",
1421        }
1422    }
1423
1424    pub fn parse(value: &str) -> Option<Self> {
1425        match value {
1426            "quiet" => Some(Self::Quiet),
1427            "active" => Some(Self::Active),
1428            "urgent" => Some(Self::Urgent),
1429            _ => None,
1430        }
1431    }
1432}
1433
1434/// Who wrote a decision. Only the deliberator's own `record_decision` writes
1435/// `Deliberator`; every decision the runtime records on its behalf (it
1436/// exited, failed or ran out of budget without one) is `RuntimeFallback`,
1437/// which finalization closes as a failed review that is retried with
1438/// backoff and surfaced to the owner.
1439#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1440#[serde(rename_all = "snake_case")]
1441pub enum MandateDecisionOrigin {
1442    #[default]
1443    Deliberator,
1444    RuntimeFallback,
1445}
1446
1447impl MandateDecisionOrigin {
1448    pub fn as_str(self) -> &'static str {
1449        match self {
1450            Self::Deliberator => "deliberator",
1451            Self::RuntimeFallback => "runtime_fallback",
1452        }
1453    }
1454
1455    pub fn parse(value: &str) -> Option<Self> {
1456        match value {
1457            "deliberator" => Some(Self::Deliberator),
1458            "runtime_fallback" => Some(Self::RuntimeFallback),
1459            _ => None,
1460        }
1461    }
1462}
1463
1464/// Whether the owner hears about a failed review: the first failure of a
1465/// streak, then each time the streak doubles (1, 2, 4, 8, …). A streak ends
1466/// with the next review that succeeds. The mandate retries either way; a
1467/// provider outage no longer sends one critical notice per review.
1468pub fn review_failure_is_notified(consecutive_failures: i64) -> bool {
1469    consecutive_failures > 0 && (consecutive_failures as u64).is_power_of_two()
1470}
1471
1472/// Rationale of the WAIT the runtime records when a mandate deliberator exits
1473/// without committing a decision. Display text only: what makes it a
1474/// fallback is its [`MandateDecisionOrigin::RuntimeFallback`].
1475pub const SAFE_FALLBACK_WAIT_RATIONALE: &str = "The deliberator returned without committing an explicit decision; the runtime safely defaulted this cycle to WAIT.";
1476
1477/// Why a STOP decision may close a mandate. Evidence-dependent reasons must
1478/// cite one or more current-run structured tool receipts.
1479#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1480#[serde(rename_all = "snake_case")]
1481pub enum MandateTerminationKind {
1482    SuccessCriteriaSatisfied,
1483    StopConditionMet,
1484    SafetyTermination,
1485}
1486
1487impl MandateTerminationKind {
1488    pub const fn as_str(self) -> &'static str {
1489        match self {
1490            Self::SuccessCriteriaSatisfied => "success_criteria_satisfied",
1491            Self::StopConditionMet => "stop_condition_met",
1492            Self::SafetyTermination => "safety_termination",
1493        }
1494    }
1495
1496    pub fn parse(value: &str) -> Option<Self> {
1497        match value {
1498            "success_criteria_satisfied" => Some(Self::SuccessCriteriaSatisfied),
1499            "stop_condition_met" => Some(Self::StopConditionMet),
1500            "safety_termination" => Some(Self::SafetyTermination),
1501            _ => None,
1502        }
1503    }
1504
1505    pub const fn requires_receipt_evidence(self) -> bool {
1506        matches!(
1507            self,
1508            Self::SuccessCriteriaSatisfied | Self::StopConditionMet
1509        )
1510    }
1511}
1512
1513impl MandateDecisionOutcome {
1514    pub fn as_str(self) -> &'static str {
1515        match self {
1516            Self::Act => "act",
1517            Self::Wait => "wait",
1518            Self::Ask => "ask",
1519            Self::Stop => "stop",
1520        }
1521    }
1522
1523    pub fn parse(value: &str) -> Option<Self> {
1524        match value {
1525            "act" => Some(Self::Act),
1526            "wait" => Some(Self::Wait),
1527            "ask" => Some(Self::Ask),
1528            "stop" => Some(Self::Stop),
1529            _ => None,
1530        }
1531    }
1532}
1533
1534/// One durable deliberation result for one goal run.
1535#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1536pub struct MandateDecisionCycle {
1537    pub id: String,
1538    pub mandate_id: String,
1539    pub goal_run_id: String,
1540    /// Owner-policy revision observed when this decision was committed.
1541    pub mandate_version: i64,
1542    pub outcome: MandateDecisionOutcome,
1543    #[serde(default)]
1544    pub origin: MandateDecisionOrigin,
1545    #[serde(default)]
1546    pub activity_level: MandateActivityLevel,
1547    pub rationale: String,
1548    /// Sourced observations used by the deliberator, serialized as JSON.
1549    pub belief_snapshot: Option<String>,
1550    /// Exact current-run tool-call receipts that support the belief or STOP
1551    /// decision. These identifiers are verified against durable events before
1552    /// the decision is committed.
1553    #[serde(default)]
1554    pub evidence_receipt_ids: Vec<String>,
1555    pub question: Option<String>,
1556    /// WAIT only, and only when the policy grants `owner_alerts`: one
1557    /// finding the owner asked to be told about. Sent to the owner when the
1558    /// review closes; the mandate keeps running.
1559    #[serde(default, skip_serializing_if = "Option::is_none")]
1560    pub owner_alert: Option<String>,
1561    #[serde(default, skip_serializing_if = "Option::is_none")]
1562    pub termination_kind: Option<MandateTerminationKind>,
1563    /// Exact owner-authored success/stop entry matched by a STOP decision.
1564    #[serde(default, skip_serializing_if = "Option::is_none")]
1565    pub termination_match: Option<String>,
1566    pub reconsider_at: Option<String>,
1567    /// Number of mutation attempts authorized during this cycle.
1568    pub action_attempts: i64,
1569    pub created_at: String,
1570    pub updated_at: String,
1571}
1572
1573impl MandateDecisionCycle {
1574    /// The durable summary a committed non-action decision (WAIT, ASK,
1575    /// STOP) closes its review with; `None` for ACT, whose review goes on.
1576    pub fn non_action_summary(&self) -> Option<String> {
1577        match self.outcome {
1578            MandateDecisionOutcome::Act => None,
1579            MandateDecisionOutcome::Wait => Some(format!(
1580                "WAIT recorded: {} Review again at {}.",
1581                self.rationale,
1582                self.reconsider_at
1583                    .as_deref()
1584                    .unwrap_or("the bounded default")
1585            )),
1586            MandateDecisionOutcome::Ask => Some(format!(
1587                "ASK recorded: {}",
1588                self.question.as_deref().unwrap_or(&self.rationale)
1589            )),
1590            MandateDecisionOutcome::Stop => Some(format!("STOP recorded: {}", self.rationale)),
1591        }
1592    }
1593
1594    pub fn new(
1595        mandate_id: &str,
1596        goal_run_id: &str,
1597        outcome: MandateDecisionOutcome,
1598        rationale: &str,
1599        mandate_version: i64,
1600    ) -> Self {
1601        let now = chrono::Utc::now().to_rfc3339();
1602        Self {
1603            id: uuid::Uuid::new_v4().to_string(),
1604            mandate_id: mandate_id.to_string(),
1605            goal_run_id: goal_run_id.to_string(),
1606            mandate_version,
1607            outcome,
1608            origin: MandateDecisionOrigin::Deliberator,
1609            activity_level: MandateActivityLevel::Quiet,
1610            rationale: rationale.trim().to_string(),
1611            belief_snapshot: None,
1612            evidence_receipt_ids: Vec::new(),
1613            question: None,
1614            owner_alert: None,
1615            termination_kind: None,
1616            termination_match: None,
1617            reconsider_at: None,
1618            action_attempts: 0,
1619            created_at: now.clone(),
1620            updated_at: now,
1621        }
1622    }
1623
1624    /// The least-privilege decision the runtime records when a deliberator
1625    /// exits without committing one. It grants no authority, cites no
1626    /// evidence, and is recognized by finalization as a retriable review
1627    /// failure rather than a successful WAIT.
1628    pub fn runtime_fallback_wait(
1629        mandate: &Mandate,
1630        goal_run_id: &str,
1631        now: chrono::DateTime<chrono::Utc>,
1632    ) -> Self {
1633        let mut decision = Self::new(
1634            &mandate.id,
1635            goal_run_id,
1636            MandateDecisionOutcome::Wait,
1637            SAFE_FALLBACK_WAIT_RATIONALE,
1638            mandate.version,
1639        );
1640        decision.origin = MandateDecisionOrigin::RuntimeFallback;
1641        decision.reconsider_at = Some(mandate.bounded_next_review_at(None, now));
1642        decision
1643    }
1644
1645    /// True when the runtime recorded this decision on the deliberator's
1646    /// behalf rather than the deliberator committing it.
1647    pub fn is_runtime_fallback(&self) -> bool {
1648        self.origin == MandateDecisionOrigin::RuntimeFallback
1649    }
1650
1651    pub fn validate_content_bounds(&self) -> Result<(), String> {
1652        if !canonical_text_within(&self.rationale, MAX_DECISION_RATIONALE_TEXT) {
1653            return Err(
1654                "decision rationale must be canonical non-empty text of at most 2 KiB in both characters and bytes"
1655                    .to_string(),
1656            );
1657        }
1658        if let Some(snapshot) = self.belief_snapshot.as_deref() {
1659            if !text_within(snapshot, MAX_DECISION_OBSERVATIONS_JSON) {
1660                return Err(
1661                    "decision observations exceed their serialized 6 KiB character/byte bound"
1662                        .to_string(),
1663                );
1664            }
1665            let observations: Vec<String> = serde_json::from_str(snapshot)
1666                .map_err(|_| "decision observations must be a JSON string array".to_string())?;
1667            if observations.len() > MAX_DECISION_OBSERVATIONS {
1668                return Err("decision observations cannot exceed 8 entries".to_string());
1669            }
1670            if observations
1671                .iter()
1672                .any(|value| !canonical_text_within(value, MAX_DECISION_OBSERVATION_TEXT))
1673            {
1674                return Err(
1675                    "each decision observation must be canonical non-empty text of at most 750 characters and bytes"
1676                        .to_string(),
1677                );
1678            }
1679        }
1680        if let Some(question) = self.question.as_deref()
1681            && !canonical_text_within(question, MAX_DECISION_QUESTION_TEXT)
1682        {
1683            return Err(
1684                    "decision question must be canonical non-empty text of at most 500 characters and bytes"
1685                        .to_string(),
1686                );
1687        }
1688        if self.evidence_receipt_ids.len() > MAX_MANDATE_EVIDENCE_REFS
1689            || self.evidence_receipt_ids.iter().any(|value| {
1690                !canonical_text_within(value, 256)
1691                    || !value.bytes().all(|byte| {
1692                        byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b':' | b'.')
1693                    })
1694            })
1695        {
1696            return Err("decision evidence receipt IDs exceed their canonical bounds".to_string());
1697        }
1698        if let Some(matched) = self.termination_match.as_deref()
1699            && !canonical_text_within(matched, MAX_MANDATE_POLICY_ENTRY_TEXT)
1700        {
1701            return Err("decision termination match exceeds its canonical bound".to_string());
1702        }
1703        Ok(())
1704    }
1705}
1706
1707#[derive(Debug, Clone, Default)]
1708pub struct MandateOperatingUpdates {
1709    pub learning_note: Option<MandateLearningNote>,
1710    /// Observed counts for resources earlier succeeded mutations created.
1711    /// The store accepts each only for a succeeded mutation of this mandate.
1712    pub action_outcomes: Vec<MandateActionOutcome>,
1713}
1714
1715/// One observation of how a published resource did, recorded by a later
1716/// review from a receipt that read it. Only ids and counts: the format key
1717/// is copied by the store from the intention whose mutation created the
1718/// resource, never from the model.
1719#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1720pub struct MandateActionOutcome {
1721    pub id: String,
1722    pub mandate_id: String,
1723    pub mandate_version: i64,
1724    pub decision_cycle_id: String,
1725    pub external_resource_id: String,
1726    #[serde(default, skip_serializing_if = "Option::is_none")]
1727    pub format_key: Option<String>,
1728    pub engagements_micros: i64,
1729    #[serde(default, skip_serializing_if = "Option::is_none")]
1730    pub impressions: Option<i64>,
1731    pub evidence_receipt_ids: Vec<String>,
1732    pub observed_at: String,
1733    pub created_at: String,
1734}
1735
1736impl MandateActionOutcome {
1737    #[allow(clippy::too_many_arguments)]
1738    pub fn new(
1739        mandate_id: &str,
1740        mandate_version: i64,
1741        decision_cycle_id: &str,
1742        external_resource_id: &str,
1743        engagements_micros: i64,
1744        impressions: Option<i64>,
1745        evidence_receipt_ids: Vec<String>,
1746        observed_at: &str,
1747    ) -> Self {
1748        Self {
1749            id: uuid::Uuid::new_v4().to_string(),
1750            mandate_id: mandate_id.to_string(),
1751            mandate_version,
1752            decision_cycle_id: decision_cycle_id.to_string(),
1753            external_resource_id: external_resource_id.to_string(),
1754            format_key: None,
1755            engagements_micros,
1756            impressions,
1757            evidence_receipt_ids,
1758            observed_at: observed_at.to_string(),
1759            created_at: chrono::Utc::now().to_rfc3339(),
1760        }
1761    }
1762
1763    pub fn validate(&self) -> Result<(), String> {
1764        if !canonical_text_within(&self.id, 256)
1765            || !canonical_text_within(&self.mandate_id, 256)
1766            || self.mandate_version <= 0
1767            || !canonical_text_within(&self.decision_cycle_id, 256)
1768        {
1769            return Err("action outcome identifiers are invalid".to_string());
1770        }
1771        if !is_canonical_resource_id(&self.external_resource_id) {
1772            return Err(
1773                "action outcome external_resource_id must be 1 to 64 characters of A-Z, a-z, 0-9, _ or -"
1774                    .to_string(),
1775            );
1776        }
1777        if self
1778            .format_key
1779            .as_deref()
1780            .is_some_and(|key| !is_canonical_format_key(key))
1781        {
1782            return Err("action outcome format_key is not canonical".to_string());
1783        }
1784        if self.engagements_micros < 0 || self.impressions.is_some_and(|value| value < 0) {
1785            return Err("action outcome counts must not be negative".to_string());
1786        }
1787        if self.evidence_receipt_ids.is_empty()
1788            || self.evidence_receipt_ids.len() > MAX_MANDATE_EVIDENCE_REFS
1789            || self
1790                .evidence_receipt_ids
1791                .iter()
1792                .any(|value| !canonical_text_within(value, 256))
1793        {
1794            return Err("action outcome must cite 1 to 16 evidence receipts".to_string());
1795        }
1796        for (name, value) in [
1797            ("observed_at", self.observed_at.as_str()),
1798            ("created_at", self.created_at.as_str()),
1799        ] {
1800            chrono::DateTime::parse_from_rfc3339(value)
1801                .map_err(|_| format!("action outcome {name} must be RFC3339"))?;
1802        }
1803        Ok(())
1804    }
1805}
1806
1807/// Content-free external signal that may accelerate a matching Autopilot
1808/// mandate. Matching uses exact typed account identity and URL scope only.
1809#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1810pub struct MandateWakeSignal {
1811    pub kind: MandateWakeSignalKind,
1812    pub source: String,
1813    pub target_url: String,
1814    #[serde(default, skip_serializing_if = "Option::is_none")]
1815    pub account_id: Option<String>,
1816    pub dedupe_key: String,
1817    pub occurred_at: String,
1818}
1819
1820#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1821#[serde(rename_all = "snake_case")]
1822pub enum MandateWakeSignalKind {
1823    Mention,
1824    Reply,
1825    Reaction,
1826    MetricChange,
1827    DeliveryFailure,
1828    ExternalChange,
1829}
1830
1831impl MandateWakeSignal {
1832    pub fn validate(&self) -> Result<(), String> {
1833        let canonical_token = |value: &str, max: usize| {
1834            !value.is_empty()
1835                && value.len() <= max
1836                && value.bytes().all(|byte| {
1837                    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':')
1838                })
1839        };
1840        if !canonical_token(&self.source, 128)
1841            || !canonical_token(&self.dedupe_key, 256)
1842            || self
1843                .account_id
1844                .as_deref()
1845                .is_some_and(|value| !value.starts_with("account:") || !canonical_token(value, 256))
1846        {
1847            return Err("invalid canonical mandate wake signal identifiers".to_string());
1848        }
1849        let target = reqwest::Url::parse(&self.target_url)
1850            .map_err(|_| "mandate wake target_url must be an absolute URL".to_string())?;
1851        if !matches!(target.scheme(), "http" | "https")
1852            || target.host_str().is_none()
1853            || !target.username().is_empty()
1854            || target.password().is_some()
1855            || target.fragment().is_some()
1856        {
1857            return Err("mandate wake target_url is not a safe HTTP(S) URL".to_string());
1858        }
1859        chrono::DateTime::parse_from_rfc3339(&self.occurred_at)
1860            .map_err(|_| "mandate wake occurred_at must be RFC3339".to_string())?;
1861        Ok(())
1862    }
1863}
1864
1865impl MandateWakeSignalKind {
1866    pub const fn as_str(self) -> &'static str {
1867        match self {
1868            Self::Mention => "mention",
1869            Self::Reply => "reply",
1870            Self::Reaction => "reaction",
1871            Self::MetricChange => "metric_change",
1872            Self::DeliveryFailure => "delivery_failure",
1873            Self::ExternalChange => "external_change",
1874        }
1875    }
1876}
1877
1878/// Bounded, mandate-local strategy learning. Notes are advisory continuity,
1879/// never authority, and every note must cite durable evidence from this same
1880/// mandate.
1881#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1882pub struct MandateLearningNote {
1883    pub id: String,
1884    pub mandate_id: String,
1885    pub mandate_version: i64,
1886    pub learned_in_decision_cycle_id: String,
1887    pub summary: String,
1888    pub evidence_receipt_ids: Vec<String>,
1889    pub created_at: String,
1890}
1891
1892impl MandateLearningNote {
1893    pub fn new(
1894        mandate_id: &str,
1895        mandate_version: i64,
1896        decision_cycle_id: &str,
1897        summary: &str,
1898        evidence_receipt_ids: Vec<String>,
1899    ) -> Self {
1900        Self {
1901            id: uuid::Uuid::new_v4().to_string(),
1902            mandate_id: mandate_id.to_string(),
1903            mandate_version,
1904            learned_in_decision_cycle_id: decision_cycle_id.to_string(),
1905            summary: summary.trim().to_string(),
1906            evidence_receipt_ids,
1907            created_at: chrono::Utc::now().to_rfc3339(),
1908        }
1909    }
1910
1911    pub fn validate(&self) -> Result<(), String> {
1912        if !canonical_text_within(&self.id, 256)
1913            || !canonical_text_within(&self.mandate_id, 256)
1914            || self.mandate_version <= 0
1915            || !canonical_text_within(&self.learned_in_decision_cycle_id, 256)
1916            || !canonical_text_within(&self.summary, MAX_MANDATE_LEARNING_NOTE_TEXT)
1917            || self.evidence_receipt_ids.is_empty()
1918            || self.evidence_receipt_ids.len() > MAX_MANDATE_EVIDENCE_REFS
1919            || self
1920                .evidence_receipt_ids
1921                .iter()
1922                .any(|value| !canonical_text_within(value, 256))
1923        {
1924            return Err("invalid bounded mandate learning note".to_string());
1925        }
1926        chrono::DateTime::parse_from_rfc3339(&self.created_at)
1927            .map_err(|_| "mandate learning note created_at must be RFC3339".to_string())?;
1928        Ok(())
1929    }
1930}
1931
1932#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1933#[serde(rename_all = "snake_case")]
1934pub enum MandateReconciliationResolution {
1935    ConfirmedEffectOccurred,
1936    ConfirmedNoEffect,
1937    AbandonAttempt,
1938}
1939
1940impl MandateReconciliationResolution {
1941    pub const fn as_str(self) -> &'static str {
1942        match self {
1943            Self::ConfirmedEffectOccurred => "confirmed_effect_occurred",
1944            Self::ConfirmedNoEffect => "confirmed_no_effect",
1945            Self::AbandonAttempt => "abandon_attempt",
1946        }
1947    }
1948
1949    pub fn parse(value: &str) -> Option<Self> {
1950        match value {
1951            "confirmed_effect_occurred" => Some(Self::ConfirmedEffectOccurred),
1952            "confirmed_no_effect" => Some(Self::ConfirmedNoEffect),
1953            "abandon_attempt" => Some(Self::AbandonAttempt),
1954            _ => None,
1955        }
1956    }
1957}
1958
1959/// Agent-selected, revocable commitment made under an owner mandate.
1960#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1961#[serde(rename_all = "snake_case")]
1962pub enum IntentionStatus {
1963    Committed,
1964    Satisfied,
1965    Failed,
1966    Suspended,
1967    Abandoned,
1968}
1969
1970impl IntentionStatus {
1971    pub const fn as_str(self) -> &'static str {
1972        match self {
1973            Self::Committed => "committed",
1974            Self::Satisfied => "satisfied",
1975            Self::Failed => "failed",
1976            Self::Suspended => "suspended",
1977            Self::Abandoned => "abandoned",
1978        }
1979    }
1980
1981    pub fn parse(value: &str) -> Option<Self> {
1982        match value {
1983            "committed" => Some(Self::Committed),
1984            "satisfied" => Some(Self::Satisfied),
1985            "failed" => Some(Self::Failed),
1986            "suspended" => Some(Self::Suspended),
1987            "abandoned" => Some(Self::Abandoned),
1988            _ => None,
1989        }
1990    }
1991
1992    /// An intention belongs to one decision cycle. Once its commitment ends,
1993    /// a later cycle must create a fresh intention rather than resurrecting it.
1994    pub const fn can_transition_to(self, next: Self) -> bool {
1995        matches!(
1996            (self, next),
1997            (
1998                Self::Committed,
1999                Self::Satisfied | Self::Failed | Self::Suspended | Self::Abandoned
2000            )
2001        )
2002    }
2003}
2004
2005impl std::fmt::Display for IntentionStatus {
2006    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2007        formatter.write_str(self.as_str())
2008    }
2009}
2010
2011#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2012pub struct Intention {
2013    pub id: String,
2014    pub mandate_id: String,
2015    pub decision_cycle_id: String,
2016    pub goal_run_id: String,
2017    pub description: String,
2018    pub rationale: String,
2019    /// Exact owner-authored success criterion this one-cycle commitment is
2020    /// intended to advance. `None` is retained only for pre-value-contract
2021    /// records created before this field existed.
2022    #[serde(default, skip_serializing_if = "Option::is_none")]
2023    pub value_criterion: Option<String>,
2024    pub expected_benefit: Option<String>,
2025    pub risk: Option<String>,
2026    pub invalidation_criteria: Option<String>,
2027    /// The canonical format this ACT tries (`[a-z0-9_-]{1,64}`), so later
2028    /// outcomes can be grouped by format. `None` is "untagged".
2029    #[serde(default, skip_serializing_if = "Option::is_none")]
2030    pub format_key: Option<String>,
2031    pub status: IntentionStatus,
2032    pub created_at: String,
2033    pub updated_at: String,
2034    pub completed_at: Option<String>,
2035}
2036
2037impl Intention {
2038    pub fn new(
2039        mandate_id: &str,
2040        decision_cycle_id: &str,
2041        goal_run_id: &str,
2042        description: &str,
2043        rationale: &str,
2044    ) -> Self {
2045        let now = chrono::Utc::now().to_rfc3339();
2046        Self {
2047            id: uuid::Uuid::new_v4().to_string(),
2048            mandate_id: mandate_id.to_string(),
2049            decision_cycle_id: decision_cycle_id.to_string(),
2050            goal_run_id: goal_run_id.to_string(),
2051            description: description.trim().to_string(),
2052            rationale: rationale.trim().to_string(),
2053            value_criterion: None,
2054            expected_benefit: None,
2055            risk: None,
2056            invalidation_criteria: None,
2057            format_key: None,
2058            status: IntentionStatus::Committed,
2059            created_at: now.clone(),
2060            updated_at: now,
2061            completed_at: None,
2062        }
2063    }
2064
2065    pub fn validate_content_bounds(&self) -> Result<(), String> {
2066        if self
2067            .format_key
2068            .as_deref()
2069            .is_some_and(|key| !is_canonical_format_key(key))
2070        {
2071            return Err(
2072                "intention format_key must be 1 to 64 characters of a-z, 0-9, _ or -".to_string(),
2073            );
2074        }
2075        if !canonical_text_within(&self.description, MAX_INTENTION_DESCRIPTION_TEXT) {
2076            return Err(
2077                "intention description must be canonical non-empty text of at most 1 KiB in both characters and bytes"
2078                    .to_string(),
2079            );
2080        }
2081        if !canonical_text_within(&self.rationale, MAX_DECISION_RATIONALE_TEXT) {
2082            return Err(
2083                "intention rationale must be canonical non-empty text of at most 2 KiB in both characters and bytes"
2084                    .to_string(),
2085            );
2086        }
2087        let mut metadata_chars = 0usize;
2088        let mut metadata_bytes = 0usize;
2089        for value in [
2090            self.value_criterion.as_deref(),
2091            self.expected_benefit.as_deref(),
2092            self.risk.as_deref(),
2093            self.invalidation_criteria.as_deref(),
2094        ]
2095        .into_iter()
2096        .flatten()
2097        {
2098            if value.is_empty() || value.trim() != value {
2099                return Err("intention metadata must be canonical non-empty text".to_string());
2100            }
2101            metadata_chars = metadata_chars.saturating_add(value.chars().count());
2102            metadata_bytes = metadata_bytes.saturating_add(value.len());
2103        }
2104        if metadata_chars > MAX_INTENTION_METADATA_TEXT
2105            || metadata_bytes > MAX_INTENTION_METADATA_TEXT
2106        {
2107            return Err(
2108                "intention metadata exceeds its combined 4 KiB character/byte bound".to_string(),
2109            );
2110        }
2111        Ok(())
2112    }
2113
2114    /// Validate the typed value judgment required before an ACT may be
2115    /// persisted for a value-contract mandate. The criterion is matched by the
2116    /// state store against immutable owner policy; this method owns the
2117    /// content-presence half of that contract.
2118    /// The whole value contract against the owner's policy: when the
2119    /// mandate names success criteria, the intention carries a complete
2120    /// value contract whose criterion is one of them, word for word.
2121    pub fn validate_value_against(&self, mandate: &Mandate) -> Result<(), String> {
2122        if mandate.success_criteria.is_empty() {
2123            return Ok(());
2124        }
2125        self.validate_value_contract()?;
2126        let value_criterion = self.value_criterion.as_deref().unwrap_or_default();
2127        if mandate
2128            .success_criteria
2129            .iter()
2130            .any(|criterion| criterion == value_criterion)
2131        {
2132            Ok(())
2133        } else {
2134            Err("ACT value_criterion is not an exact owner-authored success criterion".to_string())
2135        }
2136    }
2137
2138    pub fn validate_value_contract(&self) -> Result<(), String> {
2139        if !self
2140            .value_criterion
2141            .as_deref()
2142            .is_some_and(|value| canonical_text_within(value, MAX_MANDATE_OBJECTIVE_TEXT))
2143        {
2144            return Err(
2145                "ACT intention requires a canonical non-empty value_criterion within the mandate objective bound"
2146                    .to_string(),
2147            );
2148        }
2149        for (name, value) in [
2150            ("expected_benefit", self.expected_benefit.as_deref()),
2151            ("risk", self.risk.as_deref()),
2152            (
2153                "invalidation_criteria",
2154                self.invalidation_criteria.as_deref(),
2155            ),
2156        ] {
2157            if !value.is_some_and(|value| canonical_text_within(value, MAX_INTENTION_METADATA_TEXT))
2158            {
2159                return Err(format!(
2160                    "ACT intention requires canonical non-empty {name} within the mandate policy entry bound"
2161                ));
2162            }
2163        }
2164        Ok(())
2165    }
2166}
2167
2168/// Content-safe target identifier persisted for one governed mutation. Raw
2169/// arguments, request bodies, query strings, responses, and credentials never
2170/// enter the mandate mutation ledger.
2171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
2172pub struct MandateMutationTarget {
2173    /// `url` or `resource_id` in v1.
2174    pub kind: String,
2175    /// Canonical audit identifier. URL query/fragment/userinfo are removed;
2176    /// resource identifiers outside the small account/profile vocabulary are
2177    /// represented by a digest.
2178    pub identifier: String,
2179}
2180
2181/// Rust-only request to reserve one exact governed mutation. All authority
2182/// fields derive from a grant already issued by the deterministic policy gate.
2183#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2184pub struct MandateMutationReservation {
2185    pub grant: MandateAuthorityGrant,
2186    pub goal_run_id: String,
2187    pub root_task_id: String,
2188    pub root_task_attempt_id: String,
2189    pub task_id: String,
2190    pub task_attempt_id: String,
2191    pub tool_call_id: String,
2192    pub tool_name: String,
2193    pub mutation_effects: Vec<String>,
2194    pub targets: Vec<MandateMutationTarget>,
2195    pub account_identifiers: Vec<String>,
2196    /// Caller-supplied clock solely for deterministic state tests. Production
2197    /// callers always use `Utc::now()` and the store validates RFC3339.
2198    pub reserved_at: String,
2199}
2200
2201/// Rust-only exact one-use claim made at the last common dispatcher before
2202/// adapter I/O. The store atomically binds this claim to the still-reserved
2203/// ledger row and every live task/run/authority fence.
2204#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2205pub struct MandateMutationDispatchClaim {
2206    pub grant: MandateAuthorityGrant,
2207    pub goal_run_id: String,
2208    pub root_task_id: String,
2209    pub root_task_attempt_id: String,
2210    pub task_id: String,
2211    pub task_attempt_id: String,
2212    pub tool_call_id: String,
2213    pub tool_name: String,
2214    pub claimed_at: String,
2215}
2216
2217/// Durable state of a mutation attempt. `reserved` is intentionally not a
2218/// success: a crash before strict receipt projection remains ambiguous.
2219#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2220#[serde(rename_all = "snake_case")]
2221pub enum MandateMutationAttemptStatus {
2222    Reserved,
2223    /// The action slot was reserved, but the final dispatcher never claimed it
2224    /// before the run or authority epoch was invalidated. This is terminal and
2225    /// explicitly distinct from an externally ambiguous dispatch.
2226    NeverDispatched,
2227    Succeeded,
2228    Failed,
2229    Ambiguous,
2230}
2231
2232impl MandateMutationAttemptStatus {
2233    pub fn parse(value: &str) -> Option<Self> {
2234        match value {
2235            "reserved" => Some(Self::Reserved),
2236            "never_dispatched" => Some(Self::NeverDispatched),
2237            "succeeded" => Some(Self::Succeeded),
2238            "failed" => Some(Self::Failed),
2239            "ambiguous" => Some(Self::Ambiguous),
2240            _ => None,
2241        }
2242    }
2243}
2244
2245#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2246#[serde(rename_all = "snake_case")]
2247pub enum MandateMutationEvidence {
2248    ToolReported,
2249    StructuredMetadata,
2250}
2251
2252impl MandateMutationEvidence {
2253    pub fn parse(value: &str) -> Option<Self> {
2254        match value {
2255            "tool_reported" => Some(Self::ToolReported),
2256            "structured_metadata" => Some(Self::StructuredMetadata),
2257            _ => None,
2258        }
2259    }
2260}
2261
2262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2263pub struct MandateMutationAttempt {
2264    pub id: String,
2265    pub mandate_id: String,
2266    pub mandate_version: i64,
2267    pub decision_cycle_id: String,
2268    pub goal_run_id: String,
2269    pub intention_id: String,
2270    pub root_task_id: String,
2271    pub root_task_attempt_id: String,
2272    pub task_id: String,
2273    pub task_attempt_id: String,
2274    pub reserved_action_attempt: i64,
2275    pub action_digest: String,
2276    pub tool_call_id: String,
2277    pub tool_name: String,
2278    pub mutation_effects: Vec<String>,
2279    pub targets: Vec<MandateMutationTarget>,
2280    pub account_identifiers: Vec<String>,
2281    pub status: MandateMutationAttemptStatus,
2282    pub outcome_evidence: Option<MandateMutationEvidence>,
2283    pub http_status: Option<u16>,
2284    pub exit_code: Option<i32>,
2285    /// Canonical id of the resource this mutation created, projected from
2286    /// its strictly successful receipt.
2287    #[serde(default, skip_serializing_if = "Option::is_none")]
2288    pub external_resource_id: Option<String>,
2289    pub reserved_at: String,
2290    pub completed_at: Option<String>,
2291}
2292
2293#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2294#[serde(rename_all = "snake_case")]
2295pub enum MandateMutationQuotaBlockReason {
2296    MutationDisabled,
2297    Rolling24hExhausted,
2298    Cooldown,
2299}
2300
2301#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2302pub struct MandateMutationQuotaState {
2303    pub mandate_id: String,
2304    pub as_of: String,
2305    pub max_mutating_actions_per_rolling_24h: u32,
2306    pub min_seconds_between_mutations: u32,
2307    pub reserved_in_rolling_24h: u32,
2308    pub remaining_in_rolling_24h: u32,
2309    pub last_reserved_at: Option<String>,
2310    pub available_now: bool,
2311    pub block_reason: Option<MandateMutationQuotaBlockReason>,
2312    /// Earliest instant at which both the rolling quota and cooldown can admit
2313    /// another reservation. None means mutation is disabled or available now.
2314    pub earliest_next_slot_at: Option<String>,
2315}
2316
2317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2318pub struct MandateRunFinalizationRequest {
2319    pub mandate_id: String,
2320    pub expected_mandate_version: i64,
2321    pub goal_run_id: String,
2322    pub finalized_at: String,
2323}
2324
2325#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
2326pub struct MandateRunProofCounts {
2327    pub non_root_tasks: u32,
2328    pub completed_tasks: u32,
2329    pub incomplete_tasks: u32,
2330    pub failed_or_blocked_tasks: u32,
2331    pub mutation_reservations: u32,
2332    pub succeeded_mutations: u32,
2333    pub failed_mutations: u32,
2334    pub never_dispatched_mutations: u32,
2335    pub ambiguous_or_reserved_mutations: u32,
2336}
2337
2338/// The gate that refused a mandate worker's mutation before dispatch, read
2339/// from the typed denial on the worker's receipt.
2340#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2341#[serde(rename_all = "snake_case")]
2342pub enum MandateDispatchGate {
2343    UntrustedContentCheck,
2344    MandateAuthority,
2345    OwnerDeclined,
2346    SecretScan,
2347    Other,
2348}
2349
2350impl MandateDispatchGate {
2351    /// The gate named by a receipt's `access_denial.reason_code`.
2352    pub fn from_reason_code(code: &str) -> Self {
2353        match code {
2354            "untrusted_egress_denied" => Self::UntrustedContentCheck,
2355            "authority_hook_denied" => Self::MandateAuthority,
2356            aidaemon_events::OWNER_APPROVAL_DECLINED => Self::OwnerDeclined,
2357            "egress_secret_blocked" => Self::SecretScan,
2358            _ => Self::Other,
2359        }
2360    }
2361
2362    pub fn owner_label(self) -> &'static str {
2363        match self {
2364            Self::UntrustedContentCheck => "the untrusted-content safety check",
2365            Self::MandateAuthority => "the limits of this mandate",
2366            Self::OwnerDeclined => "an earlier decline of yours",
2367            Self::SecretScan => "the outbound secret scan",
2368            Self::Other => "a safety gate",
2369        }
2370    }
2371}
2372
2373#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2374#[serde(rename_all = "snake_case")]
2375pub enum MandateReconciliationReason {
2376    RootTaskNotSuccessful,
2377    ActMissingIntention,
2378    ActMissingWorkTask,
2379    /// A gate refused the worker's mutation before dispatch, and the run
2380    /// reserved nothing: no external change exists to reconcile.
2381    ActBlockedBeforeDispatch {
2382        gate: MandateDispatchGate,
2383    },
2384    WorkTasksIncomplete,
2385    ActMissingVerifiedMutation,
2386    ActionLedgerMismatch,
2387    MutationOutcomeFailed,
2388    MutationOutcomeAmbiguous,
2389    NonActionCreatedWork,
2390    NonActionReservedMutation,
2391}
2392
2393impl MandateReconciliationReason {
2394    /// Why the mandate paused, as a clause the owner reads after "paused for
2395    /// safety:". Never an internal code.
2396    pub fn owner_sentence(self) -> String {
2397        match self {
2398            Self::RootTaskNotSuccessful => "its last review did not finish its work".to_string(),
2399            Self::ActMissingIntention => {
2400                "it decided to act but did not record what it meant to do".to_string()
2401            }
2402            Self::ActMissingWorkTask => "it decided to act but never started the work".to_string(),
2403            Self::ActBlockedBeforeDispatch { gate } => format!(
2404                "it decided to act, but {} refused the action before it ran",
2405                gate.owner_label()
2406            ),
2407            Self::WorkTasksIncomplete => "some of its work did not finish".to_string(),
2408            Self::ActMissingVerifiedMutation => {
2409                "it decided to act but could not confirm the change happened".to_string()
2410            }
2411            Self::ActionLedgerMismatch => {
2412                "its record of changes does not match what it reported".to_string()
2413            }
2414            Self::MutationOutcomeFailed => "a change it tried failed".to_string(),
2415            Self::MutationOutcomeAmbiguous => {
2416                "it cannot tell whether a change it tried went through".to_string()
2417            }
2418            Self::NonActionCreatedWork => {
2419                "it started work during a review that was not meant to act".to_string()
2420            }
2421            Self::NonActionReservedMutation => {
2422                "it prepared a change during a review that was not meant to act".to_string()
2423            }
2424        }
2425    }
2426
2427    pub fn as_str(self) -> &'static str {
2428        match self {
2429            Self::RootTaskNotSuccessful => "root_task_not_successful",
2430            Self::ActMissingIntention => "act_missing_intention",
2431            Self::ActMissingWorkTask => "act_missing_work_task",
2432            Self::ActBlockedBeforeDispatch { gate } => match gate {
2433                MandateDispatchGate::UntrustedContentCheck => {
2434                    "act_blocked_before_dispatch:untrusted_content_check"
2435                }
2436                MandateDispatchGate::MandateAuthority => {
2437                    "act_blocked_before_dispatch:mandate_authority"
2438                }
2439                MandateDispatchGate::OwnerDeclined => "act_blocked_before_dispatch:owner_declined",
2440                MandateDispatchGate::SecretScan => "act_blocked_before_dispatch:secret_scan",
2441                MandateDispatchGate::Other => "act_blocked_before_dispatch:other",
2442            },
2443            Self::WorkTasksIncomplete => "work_tasks_incomplete",
2444            Self::ActMissingVerifiedMutation => "act_missing_verified_mutation",
2445            Self::ActionLedgerMismatch => "action_ledger_mismatch",
2446            Self::MutationOutcomeFailed => "mutation_outcome_failed",
2447            Self::MutationOutcomeAmbiguous => "mutation_outcome_ambiguous",
2448            Self::NonActionCreatedWork => "non_action_created_work",
2449            Self::NonActionReservedMutation => "non_action_reserved_mutation",
2450        }
2451    }
2452
2453    /// What went wrong, in the owner's words: no internal stage or
2454    /// component names.
2455    pub fn owner_text(self) -> &'static str {
2456        match self {
2457            Self::RootTaskNotSuccessful => "the review did not finish",
2458            Self::ActMissingIntention => "it decided to act but did not record what it meant to do",
2459            Self::ActMissingWorkTask => "it decided to act but started no work",
2460            Self::ActBlockedBeforeDispatch { .. } => "an action was refused before it ran",
2461            Self::WorkTasksIncomplete => "some of its work did not finish",
2462            Self::ActMissingVerifiedMutation => {
2463                "it decided to act but no change could be confirmed"
2464            }
2465            Self::ActionLedgerMismatch => "its record of what it did does not match what ran",
2466            Self::MutationOutcomeFailed => "an action it took failed",
2467            Self::MutationOutcomeAmbiguous => {
2468                "it can't tell whether an action it took went through"
2469            }
2470            Self::NonActionCreatedWork => "it decided not to act but started work anyway",
2471            Self::NonActionReservedMutation => "it decided not to act but prepared a change anyway",
2472        }
2473    }
2474}
2475
2476#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2477#[serde(rename_all = "snake_case")]
2478pub enum MandateFinalizationStaleReason {
2479    MandateMissingOrVersionChanged,
2480    RunNotCurrent,
2481    DecisionVersionChanged,
2482}
2483
2484#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2485#[serde(rename_all = "snake_case")]
2486pub enum MandateFinalizationRejectReason {
2487    InvalidRequest,
2488    DecisionMissing,
2489    InvalidDecisionState,
2490    DeliberatorFailed,
2491    /// An orphaned ACT review with no reserved mutation or dispatch claim.
2492    /// The review was interrupted after deciding, before any external action
2493    /// could run; it is safe to suspend the intention and retry.
2494    ActInterruptedBeforeDispatch,
2495    /// An ACT review whose action ledger proves nothing reached the outside
2496    /// world: no mutation succeeded, none has an unknown outcome. Retried
2497    /// with backoff; the owner has nothing to reconcile.
2498    ActChangedNothing,
2499}
2500
2501impl MandateFinalizationRejectReason {
2502    /// What happened to the review, as the owner reads it after "a review".
2503    pub fn owner_sentence(self) -> &'static str {
2504        match self {
2505            Self::InvalidRequest | Self::InvalidDecisionState => {
2506                "could not be checked, so nothing was done"
2507            }
2508            Self::DecisionMissing => "was interrupted before it decided anything. Nothing was done",
2509            Self::DeliberatorFailed => "stopped before it finished",
2510            Self::ActInterruptedBeforeDispatch => {
2511                "decided to act but was interrupted before any action was dispatched. Nothing was done"
2512            }
2513            Self::ActChangedNothing => {
2514                "decided to act, but the action did not go through, so nothing changed"
2515            }
2516        }
2517    }
2518
2519    /// Whether the mandate retries on its own after this failure.
2520    pub fn retries_automatically(self) -> bool {
2521        matches!(
2522            self,
2523            Self::DecisionMissing
2524                | Self::DeliberatorFailed
2525                | Self::ActInterruptedBeforeDispatch
2526                | Self::ActChangedNothing
2527        )
2528    }
2529
2530    /// The reason [`Self::as_str`] wrote (a run's
2531    /// `mandate_review_failed:<reason>`).
2532    pub fn from_code(code: &str) -> Option<Self> {
2533        [
2534            Self::InvalidRequest,
2535            Self::DecisionMissing,
2536            Self::InvalidDecisionState,
2537            Self::DeliberatorFailed,
2538            Self::ActInterruptedBeforeDispatch,
2539            Self::ActChangedNothing,
2540        ]
2541        .into_iter()
2542        .find(|reason| reason.as_str() == code)
2543    }
2544
2545    pub fn as_str(self) -> &'static str {
2546        match self {
2547            Self::InvalidRequest => "invalid_request",
2548            Self::DecisionMissing => "decision_missing",
2549            Self::InvalidDecisionState => "invalid_decision_state",
2550            Self::DeliberatorFailed => "deliberator_failed",
2551            Self::ActInterruptedBeforeDispatch => "act_interrupted_before_dispatch",
2552            Self::ActChangedNothing => "act_changed_nothing",
2553        }
2554    }
2555
2556    /// What went wrong, in the owner's words: no internal stage or
2557    /// component names.
2558    pub fn owner_text(self) -> &'static str {
2559        match self {
2560            Self::InvalidRequest => "the review could not be checked",
2561            Self::DecisionMissing => "it was interrupted before it decided anything",
2562            Self::InvalidDecisionState => "its decision could not be confirmed",
2563            Self::DeliberatorFailed => "it could not finish",
2564            Self::ActInterruptedBeforeDispatch => {
2565                "it was interrupted after deciding to act, before any action was dispatched"
2566            }
2567            Self::ActChangedNothing => "the action it decided on did not go through",
2568        }
2569    }
2570}
2571
2572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2573#[serde(tag = "result", rename_all = "snake_case")]
2574pub enum MandateRunFinalizationResult {
2575    ActSatisfied {
2576        counts: MandateRunProofCounts,
2577    },
2578    NonActionSatisfied {
2579        outcome: MandateDecisionOutcome,
2580        counts: MandateRunProofCounts,
2581    },
2582    ReconciliationRequired {
2583        reason: MandateReconciliationReason,
2584        counts: MandateRunProofCounts,
2585    },
2586    Stale {
2587        reason: MandateFinalizationStaleReason,
2588    },
2589    Rejected {
2590        reason: MandateFinalizationRejectReason,
2591    },
2592}
2593
2594/// Typed, content-free owner notice committed with a mandate run's terminal
2595/// proof state. No model-authored rationale, question, task, tool, response, or
2596/// error text can enter this structure or its rendered notification.
2597#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2598#[serde(tag = "kind", rename_all = "snake_case")]
2599pub enum MandateRunNotificationKind {
2600    ActSatisfied,
2601    Ask,
2602    /// A WAIT that carried the owner alert its policy grants.
2603    Alert,
2604    Stopped,
2605    ReconciliationRequired {
2606        reason: MandateReconciliationReason,
2607    },
2608    ReviewFailed {
2609        reason: MandateFinalizationRejectReason,
2610    },
2611    ExecutionLeaseLost,
2612    AuthorityRevokedWithUnresolvedMutation,
2613}
2614
2615impl MandateRunNotificationKind {
2616    pub fn notification_type(&self) -> &'static str {
2617        match self {
2618            Self::ActSatisfied => "mandate_action",
2619            Self::Ask => "mandate_ask",
2620            Self::Alert => "mandate_alert",
2621            Self::Stopped => "mandate_stopped",
2622            Self::ReconciliationRequired { .. }
2623            | Self::ExecutionLeaseLost
2624            | Self::AuthorityRevokedWithUnresolvedMutation => "mandate_reconciliation_required",
2625            Self::ReviewFailed { .. } => "mandate_review_failed",
2626        }
2627    }
2628}
2629
2630#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2631pub struct MandateRunNotification {
2632    pub mandate_id: String,
2633    pub mandate_version: i64,
2634    pub goal_id: String,
2635    pub goal_run_id: String,
2636    pub owner_session_id: String,
2637    pub kind: MandateRunNotificationKind,
2638    pub counts: MandateRunProofCounts,
2639    pub created_at: String,
2640    /// The deliberator's ASK question, shown to the owner so they can
2641    /// answer from chat. Rendered through [`owner_question_excerpt`].
2642    #[serde(default, skip_serializing_if = "Option::is_none")]
2643    pub owner_question: Option<String>,
2644    /// The WAIT's owner alert, rendered through [`owner_question_excerpt`]
2645    /// (the same bounding, quoted and attributed).
2646    #[serde(default, skip_serializing_if = "Option::is_none")]
2647    pub owner_alert: Option<String>,
2648    /// The owner-confirmed objective, so the notice names the automation the
2649    /// owner recognizes instead of an opaque id. Rendered through
2650    /// [`mandate_owner_label`].
2651    #[serde(default, skip_serializing_if = "Option::is_none")]
2652    pub objective: Option<String>,
2653    /// The short name the owner gave the mandate, which the notice uses
2654    /// before the objective.
2655    #[serde(default, skip_serializing_if = "Option::is_none")]
2656    pub name: Option<String>,
2657    /// Links to what this run published, built by
2658    /// [`canonical_published_link`] from the receipts' canonical ids.
2659    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2660    pub published_links: Vec<String>,
2661    /// The measured objective's latest credible reading.
2662    #[serde(default, skip_serializing_if = "Option::is_none")]
2663    pub objective_summary: Option<MandateObjectiveNoticeSummary>,
2664}
2665
2666/// The measured objective as an owner notice states it: owner-confirmed
2667/// metric name and unit, and numbers. No model prose.
2668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2669pub struct MandateObjectiveNoticeSummary {
2670    pub metric_name: String,
2671    pub unit: String,
2672    pub current_micros: i64,
2673    pub target_micros: i64,
2674    /// Consecutive latest credible readings that neither reached the target
2675    /// nor improved.
2676    pub flat_streak: usize,
2677}
2678
2679impl MandateObjectiveNoticeSummary {
2680    pub fn validate(&self) -> Result<(), String> {
2681        for (value, max) in [(&self.metric_name, 128), (&self.unit, 64)] {
2682            if !canonical_text_within(value, max)
2683                || value.chars().any(char::is_control)
2684                || value.contains('"')
2685            {
2686                return Err("invalid mandate notification objective summary".to_string());
2687            }
2688        }
2689        Ok(())
2690    }
2691
2692    fn readout(&self) -> String {
2693        let mut text = format!(
2694            "{}: {}/{} {}",
2695            self.metric_name,
2696            format_micros(self.current_micros),
2697            format_micros(self.target_micros),
2698            self.unit
2699        );
2700        if self.flat_streak >= 3 {
2701            text.push_str(&format!(", flat for {} readings", self.flat_streak));
2702        }
2703        text
2704    }
2705}
2706
2707/// Micro-units as a compact decimal: `1000000` is `1`, `1500000` is `1.5`.
2708fn format_micros(value: i64) -> String {
2709    let sign = if value < 0 { "-" } else { "" };
2710    let magnitude = value.unsigned_abs();
2711    let whole = magnitude / 1_000_000;
2712    let fraction = magnitude % 1_000_000;
2713    if fraction == 0 {
2714        format!("{sign}{whole}")
2715    } else {
2716        let digits = format!("{fraction:06}");
2717        format!("{sign}{whole}.{}", digits.trim_end_matches('0'))
2718    }
2719}
2720
2721/// How owner-facing notices name a mandate: its owner-confirmed objective,
2722/// flattened and capped at a word boundary so it reads as a title.
2723pub fn mandate_owner_label(objective: Option<&str>) -> String {
2724    mandate_named_label(None, objective)
2725}
2726
2727/// How owner-facing notices name a mandate: the name the owner gave it, else
2728/// its objective, flattened and capped at a word boundary so it reads as a
2729/// title.
2730pub fn mandate_named_label(name: Option<&str>, objective: Option<&str>) -> String {
2731    const MAX_CHARS: usize = 72;
2732    let flattened = name
2733        .filter(|name| !name.trim().is_empty())
2734        .or(objective)
2735        .unwrap_or_default()
2736        .split_whitespace()
2737        .collect::<Vec<_>>()
2738        .join(" ")
2739        .replace('"', "'");
2740    let flattened = flattened.trim_end_matches(['.', ' ']);
2741    if flattened.is_empty() {
2742        return "Your automation".to_string();
2743    }
2744    let title = if flattened.chars().count() <= MAX_CHARS {
2745        flattened.to_string()
2746    } else {
2747        let cut = flattened.chars().take(MAX_CHARS).collect::<String>();
2748        let cut = cut.rsplit_once(' ').map_or(cut.as_str(), |(head, _)| head);
2749        format!("{}…", cut.trim_end_matches([',', ';', ':']))
2750    };
2751    format!("Your automation \"{title}\"")
2752}
2753
2754fn plural(count: impl Into<u64>, one: &str, many: &str) -> String {
2755    let count = count.into();
2756    format!("{count} {}", if count == 1 { one } else { many })
2757}
2758
2759/// Bounded, single-line rendering of a model-generated owner question. The
2760/// question is derived from untrusted observations, so it is flattened,
2761/// stripped of control characters, capped, and always presented quoted and
2762/// attributed rather than as the assistant's own words.
2763pub fn owner_question_excerpt(question: &str) -> Option<String> {
2764    const MAX_CHARS: usize = 500;
2765    let flattened = question
2766        .chars()
2767        .map(|c| if c.is_control() { ' ' } else { c })
2768        .collect::<String>()
2769        .split_whitespace()
2770        .collect::<Vec<_>>()
2771        .join(" ")
2772        .replace('"', "'");
2773    if flattened.is_empty() {
2774        return None;
2775    }
2776    let mut excerpt = flattened.chars().take(MAX_CHARS).collect::<String>();
2777    if flattened.chars().count() > MAX_CHARS {
2778        excerpt.push('…');
2779    }
2780    Some(excerpt)
2781}
2782
2783impl MandateRunNotification {
2784    #[allow(clippy::too_many_arguments)]
2785    pub fn new(
2786        mandate_id: &str,
2787        mandate_version: i64,
2788        goal_id: &str,
2789        goal_run_id: &str,
2790        owner_session_id: &str,
2791        kind: MandateRunNotificationKind,
2792        counts: MandateRunProofCounts,
2793        created_at: &str,
2794    ) -> Self {
2795        Self {
2796            mandate_id: mandate_id.to_string(),
2797            mandate_version,
2798            goal_id: goal_id.to_string(),
2799            goal_run_id: goal_run_id.to_string(),
2800            owner_session_id: owner_session_id.to_string(),
2801            kind,
2802            counts,
2803            created_at: created_at.to_string(),
2804            owner_question: None,
2805            owner_alert: None,
2806            objective: None,
2807            name: None,
2808            published_links: Vec::new(),
2809            objective_summary: None,
2810        }
2811    }
2812
2813    /// Keeps only canonical links, at most [`MAX_NOTICE_PUBLISHED_LINKS`].
2814    pub fn with_published_links(mut self, links: Vec<String>) -> Self {
2815        self.published_links = links
2816            .into_iter()
2817            .filter(|link| is_canonical_published_link(link))
2818            .take(MAX_NOTICE_PUBLISHED_LINKS)
2819            .collect();
2820        self
2821    }
2822
2823    pub fn with_objective_summary(
2824        mut self,
2825        summary: Option<MandateObjectiveNoticeSummary>,
2826    ) -> Self {
2827        self.objective_summary = summary;
2828        self
2829    }
2830
2831    pub fn with_objective(mut self, objective: Option<&str>) -> Self {
2832        self.objective = objective.map(str::to_string);
2833        self
2834    }
2835
2836    pub fn with_name(mut self, name: Option<&str>) -> Self {
2837        self.name = name.map(str::to_string);
2838        self
2839    }
2840
2841    pub fn with_owner_question(mut self, question: Option<&str>) -> Self {
2842        self.owner_question = question.and_then(owner_question_excerpt);
2843        self
2844    }
2845
2846    pub fn with_owner_alert(mut self, alert: Option<&str>) -> Self {
2847        self.owner_alert = alert.and_then(owner_question_excerpt);
2848        self
2849    }
2850
2851    pub fn validate(&self) -> Result<(), String> {
2852        for (label, value) in [
2853            ("mandate id", self.mandate_id.as_str()),
2854            ("goal id", self.goal_id.as_str()),
2855            ("goal run id", self.goal_run_id.as_str()),
2856            ("owner session id", self.owner_session_id.as_str()),
2857        ] {
2858            if value.is_empty()
2859                || value.trim() != value
2860                || value.chars().count() > 256
2861                || value.len() > 256
2862                || value.chars().any(char::is_control)
2863            {
2864                return Err(format!("invalid mandate notification {label}"));
2865            }
2866        }
2867        if self.mandate_version <= 0 {
2868            return Err("invalid mandate notification version".to_string());
2869        }
2870        if self.published_links.len() > MAX_NOTICE_PUBLISHED_LINKS
2871            || self
2872                .published_links
2873                .iter()
2874                .any(|link| !is_canonical_published_link(link))
2875        {
2876            return Err("invalid mandate notification published link".to_string());
2877        }
2878        if let Some(summary) = &self.objective_summary {
2879            summary.validate()?;
2880        }
2881        chrono::DateTime::parse_from_rfc3339(&self.created_at)
2882            .map_err(|_| "invalid mandate notification timestamp".to_string())?;
2883        Ok(())
2884    }
2885
2886    /// Stable primary key: exactly one terminal owner notice can exist for a
2887    /// mandate run, even if finalization is retried after a crash.
2888    pub fn notification_id(&self) -> String {
2889        format!("mandate-run-notice:{}", self.goal_run_id)
2890    }
2891
2892    /// The notice as the owner reads it: the mandate by its name, what
2893    /// happened in plain words, and no internal codes or ids (the owner's
2894    /// next turn finds the mandate by name, or from the typed notice).
2895    pub fn message(&self) -> String {
2896        let label = mandate_named_label(self.name.as_deref(), self.objective.as_deref());
2897        let unresolved = self.counts.ambiguous_or_reserved_mutations;
2898        let check_target = format!(
2899            "{} may not have completed cleanly. Please check the account for a missing or duplicate action before resuming it.",
2900            plural(unresolved, "external change", "external changes"),
2901        );
2902        match self.kind {
2903            MandateRunNotificationKind::ActSatisfied => {
2904                let mut done = match self.counts.succeeded_mutations {
2905                    0 => "finished a review and completed its planned work".to_string(),
2906                    count => format!(
2907                        "completed {}",
2908                        plural(count, "verified action", "verified actions")
2909                    ),
2910                };
2911                if !self.published_links.is_empty() {
2912                    done.push_str(&format!(" ({})", self.published_links.join(", ")));
2913                }
2914                done.push('.');
2915                if let Some(summary) = &self.objective_summary {
2916                    done.push(' ');
2917                    done.push_str(&summary.readout());
2918                    done.push('.');
2919                }
2920                format!("{label} {done} It keeps running on its own.")
2921            }
2922            MandateRunNotificationKind::Ask => match self.owner_question.as_deref() {
2923                Some(question) => format!(
2924                    "{label} needs your input. It asked: \"{question}\"\n\nReply here to answer. Your answer guides it, but never gives it new permissions. If you don't reply, it continues on its own within its current limits at its next review."
2925                ),
2926                None => format!(
2927                    "{label} needs your input. Ask me what it wants to know. If you don't reply, it continues on its own within its current limits at its next review."
2928                ),
2929            },
2930            MandateRunNotificationKind::Alert => match self.owner_alert.as_deref() {
2931                Some(alert) => format!(
2932                    "{label} has something you asked to hear about. It reported: \"{alert}\"\n\nIt keeps running on its own; nothing new was allowed."
2933                ),
2934                None => format!(
2935                    "{label} has something you asked to hear about. Ask me what it found. It keeps running on its own."
2936                ),
2937            },
2938            MandateRunNotificationKind::Stopped => {
2939                format!("{label} has stopped. Ask me why if you want the details.")
2940            }
2941            MandateRunNotificationKind::ReconciliationRequired {
2942                reason: reason @ MandateReconciliationReason::ActBlockedBeforeDispatch { .. },
2943            } => format!(
2944                "{label} is paused: {}, so nothing was published or changed. Ask me for the details, then resume it when you're ready.",
2945                reason.owner_sentence(),
2946            ),
2947            MandateRunNotificationKind::ReconciliationRequired { reason } => {
2948                let detail = if unresolved > 0 {
2949                    format!(" {check_target}")
2950                } else {
2951                    " Ask me for the details, then resume it when you're ready.".to_string()
2952                };
2953                format!(
2954                    "{label} is paused for safety: {}.{detail}",
2955                    reason.owner_sentence(),
2956                )
2957            }
2958            // The deliberator may fail after committing an ACT and starting an
2959            // executor, so its notice claims neither "nothing decided" nor
2960            // "nothing done"; an unconfirmed external change takes the
2961            // reconciliation path instead.
2962            MandateRunNotificationKind::ReviewFailed { reason } => {
2963                let mut text = format!("{label}: a review {}.", reason.owner_sentence());
2964                if reason == MandateFinalizationRejectReason::DeliberatorFailed {
2965                    text.push_str(" Ask me what it got to if you want the details.");
2966                }
2967                if reason.retries_automatically() {
2968                    text.push_str(" It's still active and will retry automatically.");
2969                }
2970                text
2971            }
2972            MandateRunNotificationKind::ExecutionLeaseLost => format!(
2973                "{label} is paused for safety: a review was cut off before its results could be confirmed. {check_target}"
2974            ),
2975            MandateRunNotificationKind::AuthorityRevokedWithUnresolvedMutation => format!(
2976                "{label}: a review was cancelled after it had already started work outside aidaemon. {check_target}"
2977            ),
2978        }
2979    }
2980
2981    pub fn to_notification_entry(&self) -> crate::goals::NotificationEntry {
2982        let id = self.notification_id();
2983        crate::goals::NotificationEntry {
2984            id: id.clone(),
2985            goal_id: self.goal_id.clone(),
2986            session_id: self.owner_session_id.clone(),
2987            notification_type: self.kind.notification_type().to_string(),
2988            priority: "critical".to_string(),
2989            message: self.message(),
2990            created_at: self.created_at.clone(),
2991            delivered_at: None,
2992            attempts: 0,
2993            expires_at: None,
2994            task_id: None,
2995            action_token: Some(id),
2996            untrusted: false,
2997        }
2998    }
2999}
3000
3001#[cfg(test)]
3002mod tests {
3003
3004    #[test]
3005    fn a_site_root_target_is_refused_with_a_way_forward() {
3006        let refused = super::validate_mandate_target_prefix("https://status.example.test/")
3007            .expect_err("a root target would cover the whole site");
3008        assert!(refused.contains("whole site"), "{refused}");
3009        assert!(
3010            refused.contains("https://status.example.test/<page>"),
3011            "the refusal names how to scope it: {refused}"
3012        );
3013        assert!(super::validate_mandate_target_prefix("https://status.example.test").is_err());
3014        assert!(
3015            super::validate_mandate_target_prefix("https://status.example.test/health").is_ok()
3016        );
3017        let userinfo = super::validate_mandate_target_prefix("https://a:b@status.example.test/x")
3018            .expect_err("userinfo is refused");
3019        assert!(!userinfo.contains("whole site"), "{userinfo}");
3020    }
3021    use super::*;
3022
3023    #[test]
3024    fn deliberator_failure_notice_explains_safe_automatic_retry() {
3025        let notice = MandateRunNotification::new(
3026            "08012d3d-synthetic",
3027            1,
3028            "goal-synthetic",
3029            "566978b6-synthetic",
3030            "owner-synthetic",
3031            MandateRunNotificationKind::ReviewFailed {
3032                reason: MandateFinalizationRejectReason::DeliberatorFailed,
3033            },
3034            MandateRunProofCounts::default(),
3035            "2026-08-11T12:00:00Z",
3036        );
3037        let message = notice.message();
3038        // A deliberator can fail after committing an ACT and starting an
3039        // executor, so its notice claims neither "decided nothing" nor
3040        // "nothing was done".
3041        assert!(!message.contains("decided anything"), "{message}");
3042        assert!(!message.contains("Nothing was done"), "{message}");
3043        assert!(message.contains("still active"));
3044        assert!(message.contains("will retry automatically"));
3045
3046        let missing = MandateRunNotification::new(
3047            "08012d3d-synthetic",
3048            1,
3049            "goal-synthetic",
3050            "566978b6-synthetic",
3051            "owner-synthetic",
3052            MandateRunNotificationKind::ReviewFailed {
3053                reason: MandateFinalizationRejectReason::DecisionMissing,
3054            },
3055            MandateRunProofCounts::default(),
3056            "2026-08-11T12:00:00Z",
3057        )
3058        .message();
3059        assert!(missing.contains("before it decided anything"), "{missing}");
3060        assert!(missing.contains("Nothing was done"), "{missing}");
3061    }
3062
3063    fn review_notice(kind: MandateRunNotificationKind) -> MandateRunNotification {
3064        MandateRunNotification::new(
3065            "2561769c-0000-4000-8000-synthetic",
3066            2,
3067            "goal-synthetic",
3068            "run-synthetic",
3069            "owner-synthetic",
3070            kind,
3071            MandateRunProofCounts::default(),
3072            "2026-08-11T12:00:00Z",
3073        )
3074        .with_objective(Some("Every hour, check the synthetic status page"))
3075    }
3076
3077    fn act_notice() -> MandateRunNotification {
3078        MandateRunNotification::new(
3079            "mandate-synthetic",
3080            2,
3081            "goal-synthetic",
3082            "run-synthetic",
3083            "owner-synthetic",
3084            MandateRunNotificationKind::ActSatisfied,
3085            MandateRunProofCounts {
3086                succeeded_mutations: 1,
3087                ..Default::default()
3088            },
3089            "2026-08-11T12:00:00Z",
3090        )
3091        .with_name(Some("Synthetic posts"))
3092    }
3093
3094    #[test]
3095    fn an_act_notice_without_links_or_summary_is_unchanged() {
3096        assert_eq!(
3097            act_notice().message(),
3098            "Your automation \"Synthetic posts\" completed 1 verified action. It keeps running on its own."
3099        );
3100        assert_eq!(
3101            act_notice().with_published_links(Vec::new()).message(),
3102            act_notice().message()
3103        );
3104    }
3105
3106    #[test]
3107    fn an_act_notice_names_its_links_and_metric_readout() {
3108        let linked = act_notice().with_published_links(vec![
3109            "https://x.com/i/status/1000000000000000001".to_string(),
3110            "id:note_7".to_string(),
3111            "https://example.com/evil".to_string(),
3112            "id:two words".to_string(),
3113        ]);
3114        assert_eq!(
3115            linked.published_links,
3116            vec![
3117                "https://x.com/i/status/1000000000000000001".to_string(),
3118                "id:note_7".to_string()
3119            ],
3120            "non-canonical links are dropped"
3121        );
3122        assert!(linked.validate().is_ok());
3123        assert_eq!(
3124            linked.message(),
3125            "Your automation \"Synthetic posts\" completed 1 verified action \
3126             (https://x.com/i/status/1000000000000000001, id:note_7). It keeps running on its own."
3127        );
3128        let summary = MandateObjectiveNoticeSummary {
3129            metric_name: "weekly_engagements".to_string(),
3130            unit: "engagements".to_string(),
3131            current_micros: 1_500_000,
3132            target_micros: 100_000_000,
3133            flat_streak: 4,
3134        };
3135        let measured = act_notice().with_objective_summary(Some(summary.clone()));
3136        assert_eq!(
3137            measured.message(),
3138            "Your automation \"Synthetic posts\" completed 1 verified action. weekly_engagements: \
3139             1.5/100 engagements, flat for 4 readings. It keeps running on its own."
3140        );
3141        let short_streak =
3142            act_notice().with_objective_summary(Some(MandateObjectiveNoticeSummary {
3143                flat_streak: 2,
3144                current_micros: -2_000_000,
3145                ..summary.clone()
3146            }));
3147        assert!(
3148            short_streak
3149                .message()
3150                .ends_with("weekly_engagements: -2/100 engagements. It keeps running on its own."),
3151            "{}",
3152            short_streak.message()
3153        );
3154        let mut forged = act_notice();
3155        forged.published_links = vec!["javascript:alert(1)".to_string()];
3156        assert!(forged.validate().is_err());
3157        let mut prose = act_notice();
3158        prose.objective_summary = Some(MandateObjectiveNoticeSummary {
3159            metric_name: "say \"hi\"".to_string(),
3160            ..summary
3161        });
3162        assert!(prose.validate().is_err());
3163    }
3164
3165    #[test]
3166    fn published_links_come_only_from_typed_targets_and_canonical_ids() {
3167        let target = |url: &str| MandateMutationTarget {
3168            kind: "url".to_string(),
3169            identifier: url.to_string(),
3170        };
3171        let x = [target("https://api.x.com/2/tweets")];
3172        assert_eq!(
3173            canonical_published_link(&x, "1234567890").as_deref(),
3174            Some("https://x.com/i/status/1234567890")
3175        );
3176        assert_eq!(
3177            canonical_published_link(&[target("https://api.twitter.com/2/tweets")], "42")
3178                .as_deref(),
3179            Some("https://x.com/i/status/42")
3180        );
3181        assert_eq!(
3182            canonical_published_link(&x, "abc_1").as_deref(),
3183            Some("id:abc_1"),
3184            "a non-numeric id is never dressed as a status URL"
3185        );
3186        assert_eq!(
3187            canonical_published_link(&[target("https://api.example.com/notes")], "99").as_deref(),
3188            Some("id:99")
3189        );
3190        assert_eq!(canonical_published_link(&x, "1 2"), None);
3191        assert_eq!(canonical_published_link(&x, ""), None);
3192        assert_eq!(
3193            canonical_published_link(&x, &"1".repeat(33)).as_deref(),
3194            Some(&*format!("id:{}", "1".repeat(33)))
3195        );
3196        assert_eq!(canonical_published_link(&x, &"1".repeat(65)), None);
3197    }
3198
3199    #[test]
3200    fn format_keys_and_action_outcomes_are_canonical() {
3201        assert!(is_canonical_format_key("holiday-tip_2"));
3202        assert!(!is_canonical_format_key("Holiday"));
3203        assert!(!is_canonical_format_key(""));
3204        assert!(!is_canonical_format_key(&"a".repeat(65)));
3205        let mut intention = Intention::new("m", "d", "r", "describe", "because");
3206        intention.format_key = Some("Not Canonical".to_string());
3207        assert!(intention.validate_content_bounds().is_err());
3208        intention.format_key = Some("question_hook".to_string());
3209        assert!(intention.validate_content_bounds().is_ok());
3210
3211        let outcome = MandateActionOutcome::new(
3212            "mandate-synthetic",
3213            1,
3214            "cycle-synthetic",
3215            "1234567890",
3216            3_000_000,
3217            Some(120),
3218            vec!["receipt-synthetic".to_string()],
3219            "2026-08-11T12:00:00Z",
3220        );
3221        assert!(outcome.validate().is_ok());
3222        for broken in [
3223            MandateActionOutcome {
3224                external_resource_id: "https://x.com/1".to_string(),
3225                ..outcome.clone()
3226            },
3227            MandateActionOutcome {
3228                engagements_micros: -1,
3229                ..outcome.clone()
3230            },
3231            MandateActionOutcome {
3232                impressions: Some(-1),
3233                ..outcome.clone()
3234            },
3235            MandateActionOutcome {
3236                evidence_receipt_ids: Vec::new(),
3237                ..outcome.clone()
3238            },
3239            MandateActionOutcome {
3240                observed_at: "yesterday".to_string(),
3241                ..outcome.clone()
3242            },
3243        ] {
3244            assert!(broken.validate().is_err(), "{broken:?}");
3245        }
3246    }
3247
3248    #[test]
3249    fn notices_use_the_owner_given_name_and_plain_reasons() {
3250        let named = review_notice(MandateRunNotificationKind::ReviewFailed {
3251            reason: MandateFinalizationRejectReason::DeliberatorFailed,
3252        })
3253        .with_name(Some("Status watch"));
3254        assert_eq!(
3255            named.message(),
3256            "Your automation \"Status watch\": a review stopped before it finished. Ask me what \
3257             it got to if you want the details. It's still active and will retry automatically."
3258        );
3259        let unnamed = review_notice(MandateRunNotificationKind::Stopped);
3260        assert_eq!(
3261            unnamed.message(),
3262            "Your automation \"Every hour, check the synthetic status page\" has stopped. Ask me \
3263             why if you want the details."
3264        );
3265        let paused = review_notice(MandateRunNotificationKind::ReconciliationRequired {
3266            reason: MandateReconciliationReason::MutationOutcomeFailed,
3267        })
3268        .with_name(Some("Status watch"));
3269        assert_eq!(
3270            paused.message(),
3271            "Your automation \"Status watch\" is paused for safety: a change it tried failed. \
3272             Ask me for the details, then resume it when you're ready."
3273        );
3274    }
3275
3276    #[test]
3277    fn no_notice_shows_an_internal_code_or_id() {
3278        let mut kinds = vec![
3279            MandateRunNotificationKind::ActSatisfied,
3280            MandateRunNotificationKind::Ask,
3281            MandateRunNotificationKind::Alert,
3282            MandateRunNotificationKind::Stopped,
3283            MandateRunNotificationKind::ExecutionLeaseLost,
3284            MandateRunNotificationKind::AuthorityRevokedWithUnresolvedMutation,
3285        ];
3286        for reason in [
3287            MandateFinalizationRejectReason::InvalidRequest,
3288            MandateFinalizationRejectReason::DecisionMissing,
3289            MandateFinalizationRejectReason::InvalidDecisionState,
3290            MandateFinalizationRejectReason::DeliberatorFailed,
3291            MandateFinalizationRejectReason::ActChangedNothing,
3292        ] {
3293            kinds.push(MandateRunNotificationKind::ReviewFailed { reason });
3294        }
3295        for reason in [
3296            MandateReconciliationReason::RootTaskNotSuccessful,
3297            MandateReconciliationReason::ActMissingIntention,
3298            MandateReconciliationReason::ActMissingWorkTask,
3299            MandateReconciliationReason::ActBlockedBeforeDispatch {
3300                gate: MandateDispatchGate::MandateAuthority,
3301            },
3302            MandateReconciliationReason::WorkTasksIncomplete,
3303            MandateReconciliationReason::ActMissingVerifiedMutation,
3304            MandateReconciliationReason::ActionLedgerMismatch,
3305            MandateReconciliationReason::MutationOutcomeFailed,
3306            MandateReconciliationReason::MutationOutcomeAmbiguous,
3307            MandateReconciliationReason::NonActionCreatedWork,
3308            MandateReconciliationReason::NonActionReservedMutation,
3309        ] {
3310            kinds.push(MandateRunNotificationKind::ReconciliationRequired { reason });
3311        }
3312        for kind in kinds {
3313            let message = review_notice(kind).message();
3314            assert!(!message.contains("2561769c"), "{message}");
3315            assert!(!message.contains("(ref"), "{message}");
3316            assert!(!message.contains('_'), "{message}");
3317            assert!(!message.contains("deliberator"), "{message}");
3318        }
3319    }
3320
3321    #[test]
3322    fn owner_label_names_the_objective_and_caps_at_a_word() {
3323        assert_eq!(
3324            mandate_owner_label(Some("Grow the newsletter.")),
3325            "Your automation \"Grow the newsletter\""
3326        );
3327        assert_eq!(mandate_owner_label(None), "Your automation");
3328        assert_eq!(mandate_owner_label(Some("  \n ")), "Your automation");
3329        let long = mandate_owner_label(Some(
3330            "Increase authentic audience reach and engagement on the connected X account over the next year.",
3331        ));
3332        assert!(long.ends_with("…\""), "{long}");
3333        assert!(long.chars().count() < 100, "{long}");
3334        assert!(!long.contains("  "));
3335    }
3336
3337    #[test]
3338    fn mandate_status_legal_transition_matrix_is_explicit() {
3339        let statuses = [
3340            MandateStatus::Active,
3341            MandateStatus::Paused,
3342            MandateStatus::AwaitingInput,
3343            MandateStatus::Completed,
3344            MandateStatus::Cancelled,
3345        ];
3346        let legal = [
3347            (MandateStatus::Active, MandateStatus::Paused),
3348            (MandateStatus::Active, MandateStatus::AwaitingInput),
3349            (MandateStatus::Active, MandateStatus::Completed),
3350            (MandateStatus::Active, MandateStatus::Cancelled),
3351            (MandateStatus::Paused, MandateStatus::Active),
3352            (MandateStatus::Paused, MandateStatus::Cancelled),
3353            (MandateStatus::AwaitingInput, MandateStatus::Active),
3354            (MandateStatus::AwaitingInput, MandateStatus::Cancelled),
3355        ];
3356
3357        for from in statuses {
3358            for to in statuses {
3359                assert_eq!(
3360                    from.can_transition_to(to),
3361                    legal.contains(&(from, to)),
3362                    "unexpected mandate transition {from} -> {to}"
3363                );
3364            }
3365            assert_eq!(
3366                from.is_terminal(),
3367                matches!(from, MandateStatus::Completed | MandateStatus::Cancelled)
3368            );
3369        }
3370    }
3371
3372    #[test]
3373    fn intention_status_legal_transition_matrix_is_explicit() {
3374        let statuses = [
3375            IntentionStatus::Committed,
3376            IntentionStatus::Satisfied,
3377            IntentionStatus::Failed,
3378            IntentionStatus::Suspended,
3379            IntentionStatus::Abandoned,
3380        ];
3381        let legal = [
3382            (IntentionStatus::Committed, IntentionStatus::Satisfied),
3383            (IntentionStatus::Committed, IntentionStatus::Failed),
3384            (IntentionStatus::Committed, IntentionStatus::Suspended),
3385            (IntentionStatus::Committed, IntentionStatus::Abandoned),
3386        ];
3387
3388        for from in statuses {
3389            for to in statuses {
3390                assert_eq!(
3391                    from.can_transition_to(to),
3392                    legal.contains(&(from, to)),
3393                    "unexpected intention transition {from} -> {to}"
3394                );
3395            }
3396        }
3397    }
3398
3399    #[test]
3400    fn lifecycle_status_wire_values_remain_stable() {
3401        for status in [
3402            MandateStatus::Active,
3403            MandateStatus::Paused,
3404            MandateStatus::AwaitingInput,
3405            MandateStatus::Completed,
3406            MandateStatus::Cancelled,
3407        ] {
3408            let encoded = format!("\"{}\"", status.as_str());
3409            assert_eq!(serde_json::to_string(&status).unwrap(), encoded);
3410            assert_eq!(
3411                serde_json::from_str::<MandateStatus>(&encoded).unwrap(),
3412                status
3413            );
3414            assert_eq!(MandateStatus::parse(status.as_str()), Some(status));
3415        }
3416        for status in [
3417            IntentionStatus::Committed,
3418            IntentionStatus::Satisfied,
3419            IntentionStatus::Failed,
3420            IntentionStatus::Suspended,
3421            IntentionStatus::Abandoned,
3422        ] {
3423            let encoded = format!("\"{}\"", status.as_str());
3424            assert_eq!(serde_json::to_string(&status).unwrap(), encoded);
3425            assert_eq!(
3426                serde_json::from_str::<IntentionStatus>(&encoded).unwrap(),
3427                status
3428            );
3429            assert_eq!(IntentionStatus::parse(status.as_str()), Some(status));
3430        }
3431    }
3432
3433    #[test]
3434    fn authority_rejects_global_wildcard_and_unknown_effects() {
3435        let mut authority = MandateAuthority {
3436            allowed_tools: vec!["*".to_string()],
3437            max_mutating_actions_per_cycle: 1,
3438            ..MandateAuthority::default()
3439        };
3440        assert!(authority.validate().is_err());
3441
3442        authority.allowed_tools = vec!["mcp__x__*".to_string()];
3443        authority.allowed_mutation_effects = vec!["invented_effect".to_string()];
3444        assert!(authority.validate().is_err());
3445    }
3446
3447    #[test]
3448    fn only_exact_positive_list_data_tools_can_be_delegated() {
3449        let authority = MandateAuthority {
3450            allowed_tools: vec!["http_request".to_string(), "web_fetch".to_string()],
3451            allowed_target_prefixes: vec!["https://api.x.com/2/".to_string()],
3452            ..MandateAuthority::default()
3453        };
3454        assert!(authority.validate().is_ok());
3455        assert!(authority.allows_tool("http_request"));
3456        assert!(!authority.allows_tool("http_request_admin"));
3457        assert!(!authority.allows_tool("terminal"));
3458
3459        let mut wildcard = authority.clone();
3460        wildcard.allowed_tools = vec!["http_*".to_string()];
3461        assert!(wildcard.validate().is_err());
3462        let mut private_read = authority;
3463        private_read.allowed_tools = vec!["search_history".to_string()];
3464        assert!(private_read.validate().is_err());
3465    }
3466
3467    #[test]
3468    fn observation_data_tools_require_explicit_typed_target_scopes() {
3469        let mut authority = MandateAuthority {
3470            allowed_tools: vec!["http_request".to_string()],
3471            ..MandateAuthority::default()
3472        };
3473        assert!(authority.validate().is_err());
3474        authority.allowed_target_prefixes = vec!["https://api.x.com/2/users/me".to_string()];
3475        assert!(authority.validate().is_ok());
3476        authority.allowed_target_prefixes = vec!["/private/history".to_string()];
3477        assert!(authority.validate().is_err());
3478        for invalid_resource in ["account:", "auth_profile:", "account:123:"] {
3479            authority.allowed_target_prefixes = vec![invalid_resource.to_string()];
3480            assert!(authority.validate().is_err(), "scope={invalid_resource}");
3481        }
3482    }
3483
3484    #[test]
3485    fn opaque_nested_action_tools_cannot_be_delegated() {
3486        for pattern in [
3487            "cli_agent",
3488            "cli_*",
3489            "terminal",
3490            "term*",
3491            "browser",
3492            "brow*",
3493            "computer_use",
3494            "computer_*",
3495            "health_probe",
3496            "health_*",
3497            "manage_automations",
3498            "schedule_task",
3499            "schedule_*",
3500            "read_file",
3501            "read_*",
3502            "write_file",
3503            "write_*",
3504            "edit_file",
3505            "edit_*",
3506            "search_files",
3507            "search_*",
3508            "send_file",
3509            "send_*",
3510            "check_environment",
3511            "check_*",
3512            "mcp__x__post",
3513            "mcp__x__*",
3514        ] {
3515            let authority = MandateAuthority {
3516                allowed_tools: vec![pattern.to_string()],
3517                ..MandateAuthority::default()
3518            };
3519            assert!(authority.validate().is_err(), "pattern {pattern:?}");
3520        }
3521    }
3522
3523    #[test]
3524    fn mutation_authority_requires_bounded_daily_quota_cooldown_and_non_root_target() {
3525        let mut authority = MandateAuthority {
3526            allowed_tools: vec!["http_request".to_string()],
3527            allowed_mutation_effects: vec!["external_delivery".to_string()],
3528            max_mutating_actions_per_cycle: 1,
3529            max_mutating_actions_per_rolling_24h: 1,
3530            min_seconds_between_mutations: 900,
3531            ..MandateAuthority::default()
3532        };
3533        assert!(
3534            authority.validate().is_err(),
3535            "empty targets must fail closed"
3536        );
3537
3538        authority.allowed_target_prefixes = vec!["https://api.x.com/".to_string()];
3539        assert!(
3540            authority.validate().is_err(),
3541            "origin-wide scope is too broad"
3542        );
3543
3544        authority.allowed_target_prefixes = vec![
3545            "https://api.x.com/2/tweets".to_string(),
3546            "auth_profile:Twitter%20Prod%2Faccount".to_string(),
3547        ];
3548        assert!(authority.validate().is_ok());
3549
3550        authority.min_seconds_between_mutations = 899;
3551        assert!(authority.validate().is_err());
3552        authority.min_seconds_between_mutations = 900;
3553        authority.max_mutating_actions_per_rolling_24h = 25;
3554        assert!(authority.validate().is_err());
3555        authority.max_mutating_actions_per_rolling_24h = 1;
3556        authority.max_mutating_actions_per_cycle = 2;
3557        assert!(authority.validate().is_err());
3558    }
3559
3560    #[test]
3561    fn operation_scopes_project_exact_authority_and_validate_executable_http_shapes() {
3562        let read = MandateOperationScope {
3563            tool: "web_fetch".to_string(),
3564            operation: ToolCallOperation::Get,
3565            kind: MandateOperationKind::Observation,
3566            target_prefixes: vec!["https://blog.aidaemon.ai/posts/".to_string()],
3567            allowed_query_params: Vec::new(),
3568            mutation_effects: Vec::new(),
3569        };
3570        let post = MandateOperationScope {
3571            tool: "http_request".to_string(),
3572            operation: ToolCallOperation::Post,
3573            kind: MandateOperationKind::Mutation,
3574            target_prefixes: vec![
3575                "https://api.x.com/2/tweets".to_string(),
3576                "auth_profile:twitter".to_string(),
3577                "account:12345".to_string(),
3578            ],
3579            allowed_query_params: Vec::new(),
3580            mutation_effects: vec![
3581                "remote_mutation".to_string(),
3582                "external_delivery".to_string(),
3583            ],
3584        };
3585        let authority =
3586            MandateAuthority::from_operation_scopes(true, vec![read, post.clone()], 1, 1, 900);
3587        assert!(authority.validate().is_ok());
3588        assert_eq!(
3589            authority.allowed_tools,
3590            vec!["http_request".to_string(), "web_fetch".to_string()]
3591        );
3592        assert!(
3593            authority
3594                .allowed_target_prefixes
3595                .contains(&"account:12345".to_string())
3596        );
3597
3598        let mut missing_delivery = post.clone();
3599        missing_delivery.mutation_effects = vec!["remote_mutation".to_string()];
3600        assert!(missing_delivery.validate().is_err());
3601
3602        let mut missing_account = post;
3603        missing_account
3604            .target_prefixes
3605            .retain(|target| !target.starts_with("account:"));
3606        assert!(missing_account.validate().is_err());
3607    }
3608
3609    #[test]
3610    fn x_api_operation_scopes_require_bound_profile_and_account_identity() {
3611        let unbound = MandateOperationScope {
3612            tool: "http_request".to_string(),
3613            operation: ToolCallOperation::Get,
3614            kind: MandateOperationKind::Observation,
3615            target_prefixes: vec!["https://api.x.com/2/users/me".to_string()],
3616            allowed_query_params: Vec::new(),
3617            mutation_effects: Vec::new(),
3618        };
3619        let error = unbound.validate().unwrap_err();
3620        assert!(error.contains("X API operation scopes require exact auth_profile"));
3621
3622        let mut bound = unbound;
3623        bound
3624            .target_prefixes
3625            .push("auth_profile:twitter".to_string());
3626        bound.target_prefixes.push("account:12345".to_string());
3627        assert!(bound.validate().is_ok());
3628
3629        let public_api = MandateOperationScope {
3630            tool: "http_request".to_string(),
3631            operation: ToolCallOperation::Get,
3632            kind: MandateOperationKind::Observation,
3633            target_prefixes: vec!["https://api.example.test/v1/status".to_string()],
3634            allowed_query_params: Vec::new(),
3635            mutation_effects: Vec::new(),
3636        };
3637        assert!(public_api.validate().is_ok());
3638    }
3639
3640    #[test]
3641    fn dynamic_query_authority_is_bounded_to_observation_parameter_names() {
3642        let mut observation = MandateOperationScope {
3643            tool: "http_request".to_string(),
3644            operation: ToolCallOperation::Get,
3645            kind: MandateOperationKind::Observation,
3646            target_prefixes: vec!["https://api.example.test/v1/search".to_string()],
3647            allowed_query_params: vec!["query".to_string()],
3648            mutation_effects: Vec::new(),
3649        };
3650        assert!(observation.validate().is_ok());
3651
3652        observation.allowed_query_params = vec!["query=value".to_string()];
3653        assert!(observation.validate().is_err());
3654
3655        observation.allowed_query_params = vec!["query".to_string()];
3656        observation.target_prefixes[0] =
3657            "https://api.example.test/v1/search?query=exact".to_string();
3658        assert!(observation.validate().is_err());
3659
3660        let mutation = MandateOperationScope {
3661            tool: "http_request".to_string(),
3662            operation: ToolCallOperation::Post,
3663            kind: MandateOperationKind::Mutation,
3664            target_prefixes: vec!["https://api.example.test/v1/items".to_string()],
3665            allowed_query_params: vec!["destination".to_string()],
3666            mutation_effects: vec![
3667                "remote_mutation".to_string(),
3668                "external_delivery".to_string(),
3669            ],
3670        };
3671        assert!(mutation.validate().is_err());
3672    }
3673
3674    #[test]
3675    fn malformed_expiry_fails_closed() {
3676        let mut mandate = Mandate::new(
3677            "goal-id",
3678            None,
3679            "Test objective",
3680            "owner-session",
3681            MandateAuthority::default(),
3682            60,
3683            3_600,
3684            300,
3685        );
3686        mandate.expires_at = Some("not-a-timestamp".to_string());
3687        assert!(!mandate.is_active());
3688    }
3689
3690    #[test]
3691    fn next_review_is_capped_at_exact_expiry() {
3692        let now = chrono::DateTime::parse_from_rfc3339("2026-08-03T03:00:00Z")
3693            .unwrap()
3694            .with_timezone(&chrono::Utc);
3695        let mut mandate = Mandate::new(
3696            "goal-id",
3697            None,
3698            "Test expiry cap",
3699            "owner-session",
3700            MandateAuthority::default(),
3701            60,
3702            3_600,
3703            600,
3704        );
3705        let expiry = now + chrono::Duration::seconds(120);
3706        mandate.expires_at = Some(expiry.to_rfc3339());
3707
3708        assert_eq!(
3709            mandate.bounded_next_review_at(None, now),
3710            expiry.to_rfc3339()
3711        );
3712    }
3713
3714    #[test]
3715    fn typed_activity_edges_adjust_cadence_only_inside_confirmed_bounds() {
3716        let mandate = Mandate::new(
3717            "goal-id",
3718            None,
3719            "Adapt review cadence",
3720            "owner-session",
3721            MandateAuthority::default(),
3722            15 * 60,
3723            24 * 60 * 60,
3724            3 * 60 * 60,
3725        );
3726        assert_eq!(
3727            mandate.review_secs_for_activity(MandateActivityLevel::Quiet),
3728            3 * 60 * 60
3729        );
3730        assert_eq!(
3731            mandate.review_secs_for_activity(MandateActivityLevel::Active),
3732            60 * 60
3733        );
3734        assert_eq!(
3735            mandate.review_secs_for_activity(MandateActivityLevel::Urgent),
3736            15 * 60
3737        );
3738    }
3739
3740    #[test]
3741    fn objective_control_reads_legacy_rows_and_enforces_cadence_and_target() {
3742        // A row confirmed before the trim still carries experiment and
3743        // stagnation settings; they are ignored, not refused.
3744        let control: MandateObjectiveControl = serde_json::from_str(
3745            r#"{"schema_version":1,"metric_name":"weekly_engagements","unit":"engagements",
3746                "baseline_micros":5000000,"target_micros":8000000,"direction":"at_least",
3747                "measurement_source":"metric_source:synthetic-analytics",
3748                "measurement_cadence_secs":3600,"experiment_cohort":"synthetic-cohort-a",
3749                "experiment_window_secs":86400,"minimum_effect_micros":500000,
3750                "max_stagnant_measurements":3,"run_failure_budget":3,
3751                "baseline_observed_at":"2026-08-15T00:00:00Z"}"#,
3752        )
3753        .unwrap();
3754        assert!(control.validate().is_ok());
3755        assert!(!control.target_reached(7_999_999));
3756        assert!(control.target_reached(8_000_000));
3757        // Next measurement anchors on the latest observation, else the
3758        // baseline; either way it is exactly one cadence later.
3759        assert_eq!(
3760            control.next_measurement_at(None).as_deref(),
3761            Some("2026-08-15T01:00:00Z")
3762        );
3763        assert_eq!(
3764            control
3765                .next_measurement_at(Some("2026-08-16T12:30:00+02:00"))
3766                .as_deref(),
3767            Some("2026-08-16T11:30:00Z")
3768        );
3769        assert_eq!(
3770            control.next_measurement_at(Some("not a time")).as_deref(),
3771            Some("2026-08-15T01:00:00Z")
3772        );
3773
3774        let mut cadence = control.clone();
3775        cadence.measurement_cadence_secs = 59;
3776        assert!(
3777            cadence
3778                .validate()
3779                .unwrap_err()
3780                .starts_with("measurement_cadence_secs is 59")
3781        );
3782        let mut when = control.clone();
3783        when.baseline_observed_at = "yesterday".to_string();
3784        assert!(
3785            when.validate()
3786                .unwrap_err()
3787                .starts_with("baseline_observed_at is \"yesterday\"")
3788        );
3789    }
3790
3791    #[test]
3792    fn mandate_content_bounds_reject_utf8_byte_overflow_entry_overflow_and_combined_policy() {
3793        let mut mandate = Mandate::new(
3794            "goal-id",
3795            None,
3796            "bounded objective",
3797            "owner-session",
3798            MandateAuthority::default(),
3799            60,
3800            3_600,
3801            300,
3802        );
3803        assert!(mandate.validate_content_bounds().is_ok());
3804
3805        mandate.objective = "é".repeat(1_025);
3806        assert!(mandate.validate_content_bounds().is_err());
3807        mandate.objective = "bounded objective".to_string();
3808
3809        mandate.constraints = (0..17).map(|index| format!("constraint {index}")).collect();
3810        assert!(mandate.validate_content_bounds().is_err());
3811
3812        mandate.constraints = vec!["c".repeat(500); 6];
3813        mandate.success_criteria = vec!["s".repeat(500); 6];
3814        mandate.stop_conditions = vec!["x".repeat(500); 6];
3815        assert!(mandate.validate_content_bounds().is_err());
3816    }
3817
3818    #[test]
3819    fn authority_rejects_aggregate_serialized_size_and_utf8_byte_overflow() {
3820        let mut authority = MandateAuthority {
3821            allowed_tools: vec!["é".repeat(129)],
3822            ..MandateAuthority::default()
3823        };
3824        assert!(authority.validate().is_err());
3825
3826        authority.allowed_tools = vec!["web_fetch".to_string()];
3827        authority.allowed_target_prefixes = (0..16)
3828            .map(|index| format!("account:{index}-{}", "x".repeat(1_020)))
3829            .collect();
3830        assert!(authority.validate().is_err());
3831    }
3832
3833    #[test]
3834    fn decision_and_intention_bounds_validate_shape_bytes_and_combined_metadata() {
3835        let mut decision = MandateDecisionCycle::new(
3836            "mandate-id",
3837            "run-id",
3838            MandateDecisionOutcome::Wait,
3839            "bounded rationale",
3840            1,
3841        );
3842        decision.rationale = "é".repeat(1_025);
3843        assert!(decision.validate_content_bounds().is_err());
3844        decision.rationale = "bounded rationale".to_string();
3845        decision.belief_snapshot = Some(serde_json::json!({"not": "an array"}).to_string());
3846        assert!(decision.validate_content_bounds().is_err());
3847        decision.belief_snapshot = Some(serde_json::to_string(&vec!["observation"; 9]).unwrap());
3848        assert!(decision.validate_content_bounds().is_err());
3849        decision.belief_snapshot = Some(serde_json::to_string(&vec!["\"".repeat(750); 8]).unwrap());
3850        assert!(decision.validate_content_bounds().is_err());
3851        decision.belief_snapshot =
3852            Some(serde_json::to_string(&vec!["sourced observation"]).unwrap());
3853        decision.question = Some("é".repeat(251));
3854        assert!(decision.validate_content_bounds().is_err());
3855
3856        let mut intention = Intention::new(
3857            "mandate-id",
3858            &decision.id,
3859            "run-id",
3860            "bounded intention",
3861            "bounded rationale",
3862        );
3863        assert!(intention.validate_value_contract().is_err());
3864        intention.value_criterion = Some("Produce a verified useful outcome".to_string());
3865        intention.expected_benefit = Some("Advance the confirmed outcome".to_string());
3866        intention.risk = Some("No material downside after bounded checks".to_string());
3867        intention.invalidation_criteria =
3868            Some("New evidence shows the intervention would not help".to_string());
3869        assert!(intention.validate_value_contract().is_ok());
3870        intention.description = "é".repeat(513);
3871        assert!(intention.validate_content_bounds().is_err());
3872        intention.description = "bounded intention".to_string();
3873        intention.expected_benefit = Some("b".repeat(2_000));
3874        intention.risk = Some("r".repeat(2_000));
3875        intention.invalidation_criteria = Some("i".repeat(97));
3876        assert!(intention.validate_content_bounds().is_err());
3877    }
3878
3879    #[test]
3880    fn failed_reviews_notify_at_the_start_and_each_doubling_of_a_streak() {
3881        let notified: Vec<i64> = (0..=20)
3882            .filter(|failures| super::review_failure_is_notified(*failures))
3883            .collect();
3884        assert_eq!(notified, vec![1, 2, 4, 8, 16]);
3885    }
3886}