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    pub fn as_str(self) -> &'static str {
2531        match self {
2532            Self::InvalidRequest => "invalid_request",
2533            Self::DecisionMissing => "decision_missing",
2534            Self::InvalidDecisionState => "invalid_decision_state",
2535            Self::DeliberatorFailed => "deliberator_failed",
2536            Self::ActInterruptedBeforeDispatch => "act_interrupted_before_dispatch",
2537            Self::ActChangedNothing => "act_changed_nothing",
2538        }
2539    }
2540
2541    /// What went wrong, in the owner's words: no internal stage or
2542    /// component names.
2543    pub fn owner_text(self) -> &'static str {
2544        match self {
2545            Self::InvalidRequest => "the review could not be checked",
2546            Self::DecisionMissing => "it was interrupted before it decided anything",
2547            Self::InvalidDecisionState => "its decision could not be confirmed",
2548            Self::DeliberatorFailed => "it could not finish",
2549            Self::ActInterruptedBeforeDispatch => {
2550                "it was interrupted after deciding to act, before any action was dispatched"
2551            }
2552            Self::ActChangedNothing => "the action it decided on did not go through",
2553        }
2554    }
2555}
2556
2557#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2558#[serde(tag = "result", rename_all = "snake_case")]
2559pub enum MandateRunFinalizationResult {
2560    ActSatisfied {
2561        counts: MandateRunProofCounts,
2562    },
2563    NonActionSatisfied {
2564        outcome: MandateDecisionOutcome,
2565        counts: MandateRunProofCounts,
2566    },
2567    ReconciliationRequired {
2568        reason: MandateReconciliationReason,
2569        counts: MandateRunProofCounts,
2570    },
2571    Stale {
2572        reason: MandateFinalizationStaleReason,
2573    },
2574    Rejected {
2575        reason: MandateFinalizationRejectReason,
2576    },
2577}
2578
2579/// Typed, content-free owner notice committed with a mandate run's terminal
2580/// proof state. No model-authored rationale, question, task, tool, response, or
2581/// error text can enter this structure or its rendered notification.
2582#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2583#[serde(tag = "kind", rename_all = "snake_case")]
2584pub enum MandateRunNotificationKind {
2585    ActSatisfied,
2586    Ask,
2587    /// A WAIT that carried the owner alert its policy grants.
2588    Alert,
2589    Stopped,
2590    ReconciliationRequired {
2591        reason: MandateReconciliationReason,
2592    },
2593    ReviewFailed {
2594        reason: MandateFinalizationRejectReason,
2595    },
2596    ExecutionLeaseLost,
2597    AuthorityRevokedWithUnresolvedMutation,
2598}
2599
2600impl MandateRunNotificationKind {
2601    pub fn notification_type(&self) -> &'static str {
2602        match self {
2603            Self::ActSatisfied => "mandate_action",
2604            Self::Ask => "mandate_ask",
2605            Self::Alert => "mandate_alert",
2606            Self::Stopped => "mandate_stopped",
2607            Self::ReconciliationRequired { .. }
2608            | Self::ExecutionLeaseLost
2609            | Self::AuthorityRevokedWithUnresolvedMutation => "mandate_reconciliation_required",
2610            Self::ReviewFailed { .. } => "mandate_review_failed",
2611        }
2612    }
2613}
2614
2615#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2616pub struct MandateRunNotification {
2617    pub mandate_id: String,
2618    pub mandate_version: i64,
2619    pub goal_id: String,
2620    pub goal_run_id: String,
2621    pub owner_session_id: String,
2622    pub kind: MandateRunNotificationKind,
2623    pub counts: MandateRunProofCounts,
2624    pub created_at: String,
2625    /// The deliberator's ASK question, shown to the owner so they can
2626    /// answer from chat. Rendered through [`owner_question_excerpt`].
2627    #[serde(default, skip_serializing_if = "Option::is_none")]
2628    pub owner_question: Option<String>,
2629    /// The WAIT's owner alert, rendered through [`owner_question_excerpt`]
2630    /// (the same bounding, quoted and attributed).
2631    #[serde(default, skip_serializing_if = "Option::is_none")]
2632    pub owner_alert: Option<String>,
2633    /// The owner-confirmed objective, so the notice names the automation the
2634    /// owner recognizes instead of an opaque id. Rendered through
2635    /// [`mandate_owner_label`].
2636    #[serde(default, skip_serializing_if = "Option::is_none")]
2637    pub objective: Option<String>,
2638    /// The short name the owner gave the mandate, which the notice uses
2639    /// before the objective.
2640    #[serde(default, skip_serializing_if = "Option::is_none")]
2641    pub name: Option<String>,
2642    /// Links to what this run published, built by
2643    /// [`canonical_published_link`] from the receipts' canonical ids.
2644    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2645    pub published_links: Vec<String>,
2646    /// The measured objective's latest credible reading.
2647    #[serde(default, skip_serializing_if = "Option::is_none")]
2648    pub objective_summary: Option<MandateObjectiveNoticeSummary>,
2649}
2650
2651/// The measured objective as an owner notice states it: owner-confirmed
2652/// metric name and unit, and numbers. No model prose.
2653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2654pub struct MandateObjectiveNoticeSummary {
2655    pub metric_name: String,
2656    pub unit: String,
2657    pub current_micros: i64,
2658    pub target_micros: i64,
2659    /// Consecutive latest credible readings that neither reached the target
2660    /// nor improved.
2661    pub flat_streak: usize,
2662}
2663
2664impl MandateObjectiveNoticeSummary {
2665    pub fn validate(&self) -> Result<(), String> {
2666        for (value, max) in [(&self.metric_name, 128), (&self.unit, 64)] {
2667            if !canonical_text_within(value, max)
2668                || value.chars().any(char::is_control)
2669                || value.contains('"')
2670            {
2671                return Err("invalid mandate notification objective summary".to_string());
2672            }
2673        }
2674        Ok(())
2675    }
2676
2677    fn readout(&self) -> String {
2678        let mut text = format!(
2679            "{}: {}/{} {}",
2680            self.metric_name,
2681            format_micros(self.current_micros),
2682            format_micros(self.target_micros),
2683            self.unit
2684        );
2685        if self.flat_streak >= 3 {
2686            text.push_str(&format!(", flat for {} readings", self.flat_streak));
2687        }
2688        text
2689    }
2690}
2691
2692/// Micro-units as a compact decimal: `1000000` is `1`, `1500000` is `1.5`.
2693fn format_micros(value: i64) -> String {
2694    let sign = if value < 0 { "-" } else { "" };
2695    let magnitude = value.unsigned_abs();
2696    let whole = magnitude / 1_000_000;
2697    let fraction = magnitude % 1_000_000;
2698    if fraction == 0 {
2699        format!("{sign}{whole}")
2700    } else {
2701        let digits = format!("{fraction:06}");
2702        format!("{sign}{whole}.{}", digits.trim_end_matches('0'))
2703    }
2704}
2705
2706/// How owner-facing notices name a mandate: its owner-confirmed objective,
2707/// flattened and capped at a word boundary so it reads as a title.
2708pub fn mandate_owner_label(objective: Option<&str>) -> String {
2709    mandate_named_label(None, objective)
2710}
2711
2712/// How owner-facing notices name a mandate: the name the owner gave it, else
2713/// its objective, flattened and capped at a word boundary so it reads as a
2714/// title.
2715pub fn mandate_named_label(name: Option<&str>, objective: Option<&str>) -> String {
2716    const MAX_CHARS: usize = 72;
2717    let flattened = name
2718        .filter(|name| !name.trim().is_empty())
2719        .or(objective)
2720        .unwrap_or_default()
2721        .split_whitespace()
2722        .collect::<Vec<_>>()
2723        .join(" ")
2724        .replace('"', "'");
2725    let flattened = flattened.trim_end_matches(['.', ' ']);
2726    if flattened.is_empty() {
2727        return "Your automation".to_string();
2728    }
2729    let title = if flattened.chars().count() <= MAX_CHARS {
2730        flattened.to_string()
2731    } else {
2732        let cut = flattened.chars().take(MAX_CHARS).collect::<String>();
2733        let cut = cut.rsplit_once(' ').map_or(cut.as_str(), |(head, _)| head);
2734        format!("{}…", cut.trim_end_matches([',', ';', ':']))
2735    };
2736    format!("Your automation \"{title}\"")
2737}
2738
2739fn plural(count: impl Into<u64>, one: &str, many: &str) -> String {
2740    let count = count.into();
2741    format!("{count} {}", if count == 1 { one } else { many })
2742}
2743
2744/// Bounded, single-line rendering of a model-generated owner question. The
2745/// question is derived from untrusted observations, so it is flattened,
2746/// stripped of control characters, capped, and always presented quoted and
2747/// attributed rather than as the assistant's own words.
2748pub fn owner_question_excerpt(question: &str) -> Option<String> {
2749    const MAX_CHARS: usize = 500;
2750    let flattened = question
2751        .chars()
2752        .map(|c| if c.is_control() { ' ' } else { c })
2753        .collect::<String>()
2754        .split_whitespace()
2755        .collect::<Vec<_>>()
2756        .join(" ")
2757        .replace('"', "'");
2758    if flattened.is_empty() {
2759        return None;
2760    }
2761    let mut excerpt = flattened.chars().take(MAX_CHARS).collect::<String>();
2762    if flattened.chars().count() > MAX_CHARS {
2763        excerpt.push('…');
2764    }
2765    Some(excerpt)
2766}
2767
2768impl MandateRunNotification {
2769    #[allow(clippy::too_many_arguments)]
2770    pub fn new(
2771        mandate_id: &str,
2772        mandate_version: i64,
2773        goal_id: &str,
2774        goal_run_id: &str,
2775        owner_session_id: &str,
2776        kind: MandateRunNotificationKind,
2777        counts: MandateRunProofCounts,
2778        created_at: &str,
2779    ) -> Self {
2780        Self {
2781            mandate_id: mandate_id.to_string(),
2782            mandate_version,
2783            goal_id: goal_id.to_string(),
2784            goal_run_id: goal_run_id.to_string(),
2785            owner_session_id: owner_session_id.to_string(),
2786            kind,
2787            counts,
2788            created_at: created_at.to_string(),
2789            owner_question: None,
2790            owner_alert: None,
2791            objective: None,
2792            name: None,
2793            published_links: Vec::new(),
2794            objective_summary: None,
2795        }
2796    }
2797
2798    /// Keeps only canonical links, at most [`MAX_NOTICE_PUBLISHED_LINKS`].
2799    pub fn with_published_links(mut self, links: Vec<String>) -> Self {
2800        self.published_links = links
2801            .into_iter()
2802            .filter(|link| is_canonical_published_link(link))
2803            .take(MAX_NOTICE_PUBLISHED_LINKS)
2804            .collect();
2805        self
2806    }
2807
2808    pub fn with_objective_summary(
2809        mut self,
2810        summary: Option<MandateObjectiveNoticeSummary>,
2811    ) -> Self {
2812        self.objective_summary = summary;
2813        self
2814    }
2815
2816    pub fn with_objective(mut self, objective: Option<&str>) -> Self {
2817        self.objective = objective.map(str::to_string);
2818        self
2819    }
2820
2821    pub fn with_name(mut self, name: Option<&str>) -> Self {
2822        self.name = name.map(str::to_string);
2823        self
2824    }
2825
2826    pub fn with_owner_question(mut self, question: Option<&str>) -> Self {
2827        self.owner_question = question.and_then(owner_question_excerpt);
2828        self
2829    }
2830
2831    pub fn with_owner_alert(mut self, alert: Option<&str>) -> Self {
2832        self.owner_alert = alert.and_then(owner_question_excerpt);
2833        self
2834    }
2835
2836    pub fn validate(&self) -> Result<(), String> {
2837        for (label, value) in [
2838            ("mandate id", self.mandate_id.as_str()),
2839            ("goal id", self.goal_id.as_str()),
2840            ("goal run id", self.goal_run_id.as_str()),
2841            ("owner session id", self.owner_session_id.as_str()),
2842        ] {
2843            if value.is_empty()
2844                || value.trim() != value
2845                || value.chars().count() > 256
2846                || value.len() > 256
2847                || value.chars().any(char::is_control)
2848            {
2849                return Err(format!("invalid mandate notification {label}"));
2850            }
2851        }
2852        if self.mandate_version <= 0 {
2853            return Err("invalid mandate notification version".to_string());
2854        }
2855        if self.published_links.len() > MAX_NOTICE_PUBLISHED_LINKS
2856            || self
2857                .published_links
2858                .iter()
2859                .any(|link| !is_canonical_published_link(link))
2860        {
2861            return Err("invalid mandate notification published link".to_string());
2862        }
2863        if let Some(summary) = &self.objective_summary {
2864            summary.validate()?;
2865        }
2866        chrono::DateTime::parse_from_rfc3339(&self.created_at)
2867            .map_err(|_| "invalid mandate notification timestamp".to_string())?;
2868        Ok(())
2869    }
2870
2871    /// Stable primary key: exactly one terminal owner notice can exist for a
2872    /// mandate run, even if finalization is retried after a crash.
2873    pub fn notification_id(&self) -> String {
2874        format!("mandate-run-notice:{}", self.goal_run_id)
2875    }
2876
2877    /// The notice as the owner reads it: the mandate by its name, what
2878    /// happened in plain words, and no internal codes or ids (the owner's
2879    /// next turn finds the mandate by name, or from the typed notice).
2880    pub fn message(&self) -> String {
2881        let label = mandate_named_label(self.name.as_deref(), self.objective.as_deref());
2882        let unresolved = self.counts.ambiguous_or_reserved_mutations;
2883        let check_target = format!(
2884            "{} may not have completed cleanly. Please check the account for a missing or duplicate action before resuming it.",
2885            plural(unresolved, "external change", "external changes"),
2886        );
2887        match self.kind {
2888            MandateRunNotificationKind::ActSatisfied => {
2889                let mut done = match self.counts.succeeded_mutations {
2890                    0 => "finished a review and completed its planned work".to_string(),
2891                    count => format!(
2892                        "completed {}",
2893                        plural(count, "verified action", "verified actions")
2894                    ),
2895                };
2896                if !self.published_links.is_empty() {
2897                    done.push_str(&format!(" ({})", self.published_links.join(", ")));
2898                }
2899                done.push('.');
2900                if let Some(summary) = &self.objective_summary {
2901                    done.push(' ');
2902                    done.push_str(&summary.readout());
2903                    done.push('.');
2904                }
2905                format!("{label} {done} It keeps running on its own.")
2906            }
2907            MandateRunNotificationKind::Ask => match self.owner_question.as_deref() {
2908                Some(question) => format!(
2909                    "{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."
2910                ),
2911                None => format!(
2912                    "{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."
2913                ),
2914            },
2915            MandateRunNotificationKind::Alert => match self.owner_alert.as_deref() {
2916                Some(alert) => format!(
2917                    "{label} has something you asked to hear about. It reported: \"{alert}\"\n\nIt keeps running on its own; nothing new was allowed."
2918                ),
2919                None => format!(
2920                    "{label} has something you asked to hear about. Ask me what it found. It keeps running on its own."
2921                ),
2922            },
2923            MandateRunNotificationKind::Stopped => {
2924                format!("{label} has stopped. Ask me why if you want the details.")
2925            }
2926            MandateRunNotificationKind::ReconciliationRequired {
2927                reason: reason @ MandateReconciliationReason::ActBlockedBeforeDispatch { .. },
2928            } => format!(
2929                "{label} is paused: {}, so nothing was published or changed. Ask me for the details, then resume it when you're ready.",
2930                reason.owner_sentence(),
2931            ),
2932            MandateRunNotificationKind::ReconciliationRequired { reason } => {
2933                let detail = if unresolved > 0 {
2934                    format!(" {check_target}")
2935                } else {
2936                    " Ask me for the details, then resume it when you're ready.".to_string()
2937                };
2938                format!(
2939                    "{label} is paused for safety: {}.{detail}",
2940                    reason.owner_sentence(),
2941                )
2942            }
2943            // The deliberator may fail after committing an ACT and starting an
2944            // executor, so its notice claims neither "nothing decided" nor
2945            // "nothing done"; an unconfirmed external change takes the
2946            // reconciliation path instead.
2947            MandateRunNotificationKind::ReviewFailed { reason } => {
2948                let mut text = format!("{label}: a review {}.", reason.owner_sentence());
2949                if reason == MandateFinalizationRejectReason::DeliberatorFailed {
2950                    text.push_str(" Ask me what it got to if you want the details.");
2951                }
2952                if reason.retries_automatically() {
2953                    text.push_str(" It's still active and will retry automatically.");
2954                }
2955                text
2956            }
2957            MandateRunNotificationKind::ExecutionLeaseLost => format!(
2958                "{label} is paused for safety: a review was cut off before its results could be confirmed. {check_target}"
2959            ),
2960            MandateRunNotificationKind::AuthorityRevokedWithUnresolvedMutation => format!(
2961                "{label}: a review was cancelled after it had already started work outside aidaemon. {check_target}"
2962            ),
2963        }
2964    }
2965
2966    pub fn to_notification_entry(&self) -> crate::goals::NotificationEntry {
2967        let id = self.notification_id();
2968        crate::goals::NotificationEntry {
2969            id: id.clone(),
2970            goal_id: self.goal_id.clone(),
2971            session_id: self.owner_session_id.clone(),
2972            notification_type: self.kind.notification_type().to_string(),
2973            priority: "critical".to_string(),
2974            message: self.message(),
2975            created_at: self.created_at.clone(),
2976            delivered_at: None,
2977            attempts: 0,
2978            expires_at: None,
2979            task_id: None,
2980            action_token: Some(id),
2981            untrusted: false,
2982        }
2983    }
2984}
2985
2986#[cfg(test)]
2987mod tests {
2988
2989    #[test]
2990    fn a_site_root_target_is_refused_with_a_way_forward() {
2991        let refused = super::validate_mandate_target_prefix("https://status.example.test/")
2992            .expect_err("a root target would cover the whole site");
2993        assert!(refused.contains("whole site"), "{refused}");
2994        assert!(
2995            refused.contains("https://status.example.test/<page>"),
2996            "the refusal names how to scope it: {refused}"
2997        );
2998        assert!(super::validate_mandate_target_prefix("https://status.example.test").is_err());
2999        assert!(
3000            super::validate_mandate_target_prefix("https://status.example.test/health").is_ok()
3001        );
3002        let userinfo = super::validate_mandate_target_prefix("https://a:b@status.example.test/x")
3003            .expect_err("userinfo is refused");
3004        assert!(!userinfo.contains("whole site"), "{userinfo}");
3005    }
3006    use super::*;
3007
3008    #[test]
3009    fn deliberator_failure_notice_explains_safe_automatic_retry() {
3010        let notice = MandateRunNotification::new(
3011            "08012d3d-synthetic",
3012            1,
3013            "goal-synthetic",
3014            "566978b6-synthetic",
3015            "owner-synthetic",
3016            MandateRunNotificationKind::ReviewFailed {
3017                reason: MandateFinalizationRejectReason::DeliberatorFailed,
3018            },
3019            MandateRunProofCounts::default(),
3020            "2026-08-11T12:00:00Z",
3021        );
3022        let message = notice.message();
3023        // A deliberator can fail after committing an ACT and starting an
3024        // executor, so its notice claims neither "decided nothing" nor
3025        // "nothing was done".
3026        assert!(!message.contains("decided anything"), "{message}");
3027        assert!(!message.contains("Nothing was done"), "{message}");
3028        assert!(message.contains("still active"));
3029        assert!(message.contains("will retry automatically"));
3030
3031        let missing = MandateRunNotification::new(
3032            "08012d3d-synthetic",
3033            1,
3034            "goal-synthetic",
3035            "566978b6-synthetic",
3036            "owner-synthetic",
3037            MandateRunNotificationKind::ReviewFailed {
3038                reason: MandateFinalizationRejectReason::DecisionMissing,
3039            },
3040            MandateRunProofCounts::default(),
3041            "2026-08-11T12:00:00Z",
3042        )
3043        .message();
3044        assert!(missing.contains("before it decided anything"), "{missing}");
3045        assert!(missing.contains("Nothing was done"), "{missing}");
3046    }
3047
3048    fn review_notice(kind: MandateRunNotificationKind) -> MandateRunNotification {
3049        MandateRunNotification::new(
3050            "2561769c-0000-4000-8000-synthetic",
3051            2,
3052            "goal-synthetic",
3053            "run-synthetic",
3054            "owner-synthetic",
3055            kind,
3056            MandateRunProofCounts::default(),
3057            "2026-08-11T12:00:00Z",
3058        )
3059        .with_objective(Some("Every hour, check the synthetic status page"))
3060    }
3061
3062    fn act_notice() -> MandateRunNotification {
3063        MandateRunNotification::new(
3064            "mandate-synthetic",
3065            2,
3066            "goal-synthetic",
3067            "run-synthetic",
3068            "owner-synthetic",
3069            MandateRunNotificationKind::ActSatisfied,
3070            MandateRunProofCounts {
3071                succeeded_mutations: 1,
3072                ..Default::default()
3073            },
3074            "2026-08-11T12:00:00Z",
3075        )
3076        .with_name(Some("Synthetic posts"))
3077    }
3078
3079    #[test]
3080    fn an_act_notice_without_links_or_summary_is_unchanged() {
3081        assert_eq!(
3082            act_notice().message(),
3083            "Your automation \"Synthetic posts\" completed 1 verified action. It keeps running on its own."
3084        );
3085        assert_eq!(
3086            act_notice().with_published_links(Vec::new()).message(),
3087            act_notice().message()
3088        );
3089    }
3090
3091    #[test]
3092    fn an_act_notice_names_its_links_and_metric_readout() {
3093        let linked = act_notice().with_published_links(vec![
3094            "https://x.com/i/status/1000000000000000001".to_string(),
3095            "id:note_7".to_string(),
3096            "https://example.com/evil".to_string(),
3097            "id:two words".to_string(),
3098        ]);
3099        assert_eq!(
3100            linked.published_links,
3101            vec![
3102                "https://x.com/i/status/1000000000000000001".to_string(),
3103                "id:note_7".to_string()
3104            ],
3105            "non-canonical links are dropped"
3106        );
3107        assert!(linked.validate().is_ok());
3108        assert_eq!(
3109            linked.message(),
3110            "Your automation \"Synthetic posts\" completed 1 verified action \
3111             (https://x.com/i/status/1000000000000000001, id:note_7). It keeps running on its own."
3112        );
3113        let summary = MandateObjectiveNoticeSummary {
3114            metric_name: "weekly_engagements".to_string(),
3115            unit: "engagements".to_string(),
3116            current_micros: 1_500_000,
3117            target_micros: 100_000_000,
3118            flat_streak: 4,
3119        };
3120        let measured = act_notice().with_objective_summary(Some(summary.clone()));
3121        assert_eq!(
3122            measured.message(),
3123            "Your automation \"Synthetic posts\" completed 1 verified action. weekly_engagements: \
3124             1.5/100 engagements, flat for 4 readings. It keeps running on its own."
3125        );
3126        let short_streak =
3127            act_notice().with_objective_summary(Some(MandateObjectiveNoticeSummary {
3128                flat_streak: 2,
3129                current_micros: -2_000_000,
3130                ..summary.clone()
3131            }));
3132        assert!(
3133            short_streak
3134                .message()
3135                .ends_with("weekly_engagements: -2/100 engagements. It keeps running on its own."),
3136            "{}",
3137            short_streak.message()
3138        );
3139        let mut forged = act_notice();
3140        forged.published_links = vec!["javascript:alert(1)".to_string()];
3141        assert!(forged.validate().is_err());
3142        let mut prose = act_notice();
3143        prose.objective_summary = Some(MandateObjectiveNoticeSummary {
3144            metric_name: "say \"hi\"".to_string(),
3145            ..summary
3146        });
3147        assert!(prose.validate().is_err());
3148    }
3149
3150    #[test]
3151    fn published_links_come_only_from_typed_targets_and_canonical_ids() {
3152        let target = |url: &str| MandateMutationTarget {
3153            kind: "url".to_string(),
3154            identifier: url.to_string(),
3155        };
3156        let x = [target("https://api.x.com/2/tweets")];
3157        assert_eq!(
3158            canonical_published_link(&x, "1234567890").as_deref(),
3159            Some("https://x.com/i/status/1234567890")
3160        );
3161        assert_eq!(
3162            canonical_published_link(&[target("https://api.twitter.com/2/tweets")], "42")
3163                .as_deref(),
3164            Some("https://x.com/i/status/42")
3165        );
3166        assert_eq!(
3167            canonical_published_link(&x, "abc_1").as_deref(),
3168            Some("id:abc_1"),
3169            "a non-numeric id is never dressed as a status URL"
3170        );
3171        assert_eq!(
3172            canonical_published_link(&[target("https://api.example.com/notes")], "99").as_deref(),
3173            Some("id:99")
3174        );
3175        assert_eq!(canonical_published_link(&x, "1 2"), None);
3176        assert_eq!(canonical_published_link(&x, ""), None);
3177        assert_eq!(
3178            canonical_published_link(&x, &"1".repeat(33)).as_deref(),
3179            Some(&*format!("id:{}", "1".repeat(33)))
3180        );
3181        assert_eq!(canonical_published_link(&x, &"1".repeat(65)), None);
3182    }
3183
3184    #[test]
3185    fn format_keys_and_action_outcomes_are_canonical() {
3186        assert!(is_canonical_format_key("holiday-tip_2"));
3187        assert!(!is_canonical_format_key("Holiday"));
3188        assert!(!is_canonical_format_key(""));
3189        assert!(!is_canonical_format_key(&"a".repeat(65)));
3190        let mut intention = Intention::new("m", "d", "r", "describe", "because");
3191        intention.format_key = Some("Not Canonical".to_string());
3192        assert!(intention.validate_content_bounds().is_err());
3193        intention.format_key = Some("question_hook".to_string());
3194        assert!(intention.validate_content_bounds().is_ok());
3195
3196        let outcome = MandateActionOutcome::new(
3197            "mandate-synthetic",
3198            1,
3199            "cycle-synthetic",
3200            "1234567890",
3201            3_000_000,
3202            Some(120),
3203            vec!["receipt-synthetic".to_string()],
3204            "2026-08-11T12:00:00Z",
3205        );
3206        assert!(outcome.validate().is_ok());
3207        for broken in [
3208            MandateActionOutcome {
3209                external_resource_id: "https://x.com/1".to_string(),
3210                ..outcome.clone()
3211            },
3212            MandateActionOutcome {
3213                engagements_micros: -1,
3214                ..outcome.clone()
3215            },
3216            MandateActionOutcome {
3217                impressions: Some(-1),
3218                ..outcome.clone()
3219            },
3220            MandateActionOutcome {
3221                evidence_receipt_ids: Vec::new(),
3222                ..outcome.clone()
3223            },
3224            MandateActionOutcome {
3225                observed_at: "yesterday".to_string(),
3226                ..outcome.clone()
3227            },
3228        ] {
3229            assert!(broken.validate().is_err(), "{broken:?}");
3230        }
3231    }
3232
3233    #[test]
3234    fn notices_use_the_owner_given_name_and_plain_reasons() {
3235        let named = review_notice(MandateRunNotificationKind::ReviewFailed {
3236            reason: MandateFinalizationRejectReason::DeliberatorFailed,
3237        })
3238        .with_name(Some("Status watch"));
3239        assert_eq!(
3240            named.message(),
3241            "Your automation \"Status watch\": a review stopped before it finished. Ask me what \
3242             it got to if you want the details. It's still active and will retry automatically."
3243        );
3244        let unnamed = review_notice(MandateRunNotificationKind::Stopped);
3245        assert_eq!(
3246            unnamed.message(),
3247            "Your automation \"Every hour, check the synthetic status page\" has stopped. Ask me \
3248             why if you want the details."
3249        );
3250        let paused = review_notice(MandateRunNotificationKind::ReconciliationRequired {
3251            reason: MandateReconciliationReason::MutationOutcomeFailed,
3252        })
3253        .with_name(Some("Status watch"));
3254        assert_eq!(
3255            paused.message(),
3256            "Your automation \"Status watch\" is paused for safety: a change it tried failed. \
3257             Ask me for the details, then resume it when you're ready."
3258        );
3259    }
3260
3261    #[test]
3262    fn no_notice_shows_an_internal_code_or_id() {
3263        let mut kinds = vec![
3264            MandateRunNotificationKind::ActSatisfied,
3265            MandateRunNotificationKind::Ask,
3266            MandateRunNotificationKind::Alert,
3267            MandateRunNotificationKind::Stopped,
3268            MandateRunNotificationKind::ExecutionLeaseLost,
3269            MandateRunNotificationKind::AuthorityRevokedWithUnresolvedMutation,
3270        ];
3271        for reason in [
3272            MandateFinalizationRejectReason::InvalidRequest,
3273            MandateFinalizationRejectReason::DecisionMissing,
3274            MandateFinalizationRejectReason::InvalidDecisionState,
3275            MandateFinalizationRejectReason::DeliberatorFailed,
3276            MandateFinalizationRejectReason::ActChangedNothing,
3277        ] {
3278            kinds.push(MandateRunNotificationKind::ReviewFailed { reason });
3279        }
3280        for reason in [
3281            MandateReconciliationReason::RootTaskNotSuccessful,
3282            MandateReconciliationReason::ActMissingIntention,
3283            MandateReconciliationReason::ActMissingWorkTask,
3284            MandateReconciliationReason::ActBlockedBeforeDispatch {
3285                gate: MandateDispatchGate::MandateAuthority,
3286            },
3287            MandateReconciliationReason::WorkTasksIncomplete,
3288            MandateReconciliationReason::ActMissingVerifiedMutation,
3289            MandateReconciliationReason::ActionLedgerMismatch,
3290            MandateReconciliationReason::MutationOutcomeFailed,
3291            MandateReconciliationReason::MutationOutcomeAmbiguous,
3292            MandateReconciliationReason::NonActionCreatedWork,
3293            MandateReconciliationReason::NonActionReservedMutation,
3294        ] {
3295            kinds.push(MandateRunNotificationKind::ReconciliationRequired { reason });
3296        }
3297        for kind in kinds {
3298            let message = review_notice(kind).message();
3299            assert!(!message.contains("2561769c"), "{message}");
3300            assert!(!message.contains("(ref"), "{message}");
3301            assert!(!message.contains('_'), "{message}");
3302            assert!(!message.contains("deliberator"), "{message}");
3303        }
3304    }
3305
3306    #[test]
3307    fn owner_label_names_the_objective_and_caps_at_a_word() {
3308        assert_eq!(
3309            mandate_owner_label(Some("Grow the newsletter.")),
3310            "Your automation \"Grow the newsletter\""
3311        );
3312        assert_eq!(mandate_owner_label(None), "Your automation");
3313        assert_eq!(mandate_owner_label(Some("  \n ")), "Your automation");
3314        let long = mandate_owner_label(Some(
3315            "Increase authentic audience reach and engagement on the connected X account over the next year.",
3316        ));
3317        assert!(long.ends_with("…\""), "{long}");
3318        assert!(long.chars().count() < 100, "{long}");
3319        assert!(!long.contains("  "));
3320    }
3321
3322    #[test]
3323    fn mandate_status_legal_transition_matrix_is_explicit() {
3324        let statuses = [
3325            MandateStatus::Active,
3326            MandateStatus::Paused,
3327            MandateStatus::AwaitingInput,
3328            MandateStatus::Completed,
3329            MandateStatus::Cancelled,
3330        ];
3331        let legal = [
3332            (MandateStatus::Active, MandateStatus::Paused),
3333            (MandateStatus::Active, MandateStatus::AwaitingInput),
3334            (MandateStatus::Active, MandateStatus::Completed),
3335            (MandateStatus::Active, MandateStatus::Cancelled),
3336            (MandateStatus::Paused, MandateStatus::Active),
3337            (MandateStatus::Paused, MandateStatus::Cancelled),
3338            (MandateStatus::AwaitingInput, MandateStatus::Active),
3339            (MandateStatus::AwaitingInput, MandateStatus::Cancelled),
3340        ];
3341
3342        for from in statuses {
3343            for to in statuses {
3344                assert_eq!(
3345                    from.can_transition_to(to),
3346                    legal.contains(&(from, to)),
3347                    "unexpected mandate transition {from} -> {to}"
3348                );
3349            }
3350            assert_eq!(
3351                from.is_terminal(),
3352                matches!(from, MandateStatus::Completed | MandateStatus::Cancelled)
3353            );
3354        }
3355    }
3356
3357    #[test]
3358    fn intention_status_legal_transition_matrix_is_explicit() {
3359        let statuses = [
3360            IntentionStatus::Committed,
3361            IntentionStatus::Satisfied,
3362            IntentionStatus::Failed,
3363            IntentionStatus::Suspended,
3364            IntentionStatus::Abandoned,
3365        ];
3366        let legal = [
3367            (IntentionStatus::Committed, IntentionStatus::Satisfied),
3368            (IntentionStatus::Committed, IntentionStatus::Failed),
3369            (IntentionStatus::Committed, IntentionStatus::Suspended),
3370            (IntentionStatus::Committed, IntentionStatus::Abandoned),
3371        ];
3372
3373        for from in statuses {
3374            for to in statuses {
3375                assert_eq!(
3376                    from.can_transition_to(to),
3377                    legal.contains(&(from, to)),
3378                    "unexpected intention transition {from} -> {to}"
3379                );
3380            }
3381        }
3382    }
3383
3384    #[test]
3385    fn lifecycle_status_wire_values_remain_stable() {
3386        for status in [
3387            MandateStatus::Active,
3388            MandateStatus::Paused,
3389            MandateStatus::AwaitingInput,
3390            MandateStatus::Completed,
3391            MandateStatus::Cancelled,
3392        ] {
3393            let encoded = format!("\"{}\"", status.as_str());
3394            assert_eq!(serde_json::to_string(&status).unwrap(), encoded);
3395            assert_eq!(
3396                serde_json::from_str::<MandateStatus>(&encoded).unwrap(),
3397                status
3398            );
3399            assert_eq!(MandateStatus::parse(status.as_str()), Some(status));
3400        }
3401        for status in [
3402            IntentionStatus::Committed,
3403            IntentionStatus::Satisfied,
3404            IntentionStatus::Failed,
3405            IntentionStatus::Suspended,
3406            IntentionStatus::Abandoned,
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::<IntentionStatus>(&encoded).unwrap(),
3412                status
3413            );
3414            assert_eq!(IntentionStatus::parse(status.as_str()), Some(status));
3415        }
3416    }
3417
3418    #[test]
3419    fn authority_rejects_global_wildcard_and_unknown_effects() {
3420        let mut authority = MandateAuthority {
3421            allowed_tools: vec!["*".to_string()],
3422            max_mutating_actions_per_cycle: 1,
3423            ..MandateAuthority::default()
3424        };
3425        assert!(authority.validate().is_err());
3426
3427        authority.allowed_tools = vec!["mcp__x__*".to_string()];
3428        authority.allowed_mutation_effects = vec!["invented_effect".to_string()];
3429        assert!(authority.validate().is_err());
3430    }
3431
3432    #[test]
3433    fn only_exact_positive_list_data_tools_can_be_delegated() {
3434        let authority = MandateAuthority {
3435            allowed_tools: vec!["http_request".to_string(), "web_fetch".to_string()],
3436            allowed_target_prefixes: vec!["https://api.x.com/2/".to_string()],
3437            ..MandateAuthority::default()
3438        };
3439        assert!(authority.validate().is_ok());
3440        assert!(authority.allows_tool("http_request"));
3441        assert!(!authority.allows_tool("http_request_admin"));
3442        assert!(!authority.allows_tool("terminal"));
3443
3444        let mut wildcard = authority.clone();
3445        wildcard.allowed_tools = vec!["http_*".to_string()];
3446        assert!(wildcard.validate().is_err());
3447        let mut private_read = authority;
3448        private_read.allowed_tools = vec!["search_history".to_string()];
3449        assert!(private_read.validate().is_err());
3450    }
3451
3452    #[test]
3453    fn observation_data_tools_require_explicit_typed_target_scopes() {
3454        let mut authority = MandateAuthority {
3455            allowed_tools: vec!["http_request".to_string()],
3456            ..MandateAuthority::default()
3457        };
3458        assert!(authority.validate().is_err());
3459        authority.allowed_target_prefixes = vec!["https://api.x.com/2/users/me".to_string()];
3460        assert!(authority.validate().is_ok());
3461        authority.allowed_target_prefixes = vec!["/private/history".to_string()];
3462        assert!(authority.validate().is_err());
3463        for invalid_resource in ["account:", "auth_profile:", "account:123:"] {
3464            authority.allowed_target_prefixes = vec![invalid_resource.to_string()];
3465            assert!(authority.validate().is_err(), "scope={invalid_resource}");
3466        }
3467    }
3468
3469    #[test]
3470    fn opaque_nested_action_tools_cannot_be_delegated() {
3471        for pattern in [
3472            "cli_agent",
3473            "cli_*",
3474            "terminal",
3475            "term*",
3476            "browser",
3477            "brow*",
3478            "computer_use",
3479            "computer_*",
3480            "health_probe",
3481            "health_*",
3482            "manage_automations",
3483            "schedule_task",
3484            "schedule_*",
3485            "read_file",
3486            "read_*",
3487            "write_file",
3488            "write_*",
3489            "edit_file",
3490            "edit_*",
3491            "search_files",
3492            "search_*",
3493            "send_file",
3494            "send_*",
3495            "check_environment",
3496            "check_*",
3497            "mcp__x__post",
3498            "mcp__x__*",
3499        ] {
3500            let authority = MandateAuthority {
3501                allowed_tools: vec![pattern.to_string()],
3502                ..MandateAuthority::default()
3503            };
3504            assert!(authority.validate().is_err(), "pattern {pattern:?}");
3505        }
3506    }
3507
3508    #[test]
3509    fn mutation_authority_requires_bounded_daily_quota_cooldown_and_non_root_target() {
3510        let mut authority = MandateAuthority {
3511            allowed_tools: vec!["http_request".to_string()],
3512            allowed_mutation_effects: vec!["external_delivery".to_string()],
3513            max_mutating_actions_per_cycle: 1,
3514            max_mutating_actions_per_rolling_24h: 1,
3515            min_seconds_between_mutations: 900,
3516            ..MandateAuthority::default()
3517        };
3518        assert!(
3519            authority.validate().is_err(),
3520            "empty targets must fail closed"
3521        );
3522
3523        authority.allowed_target_prefixes = vec!["https://api.x.com/".to_string()];
3524        assert!(
3525            authority.validate().is_err(),
3526            "origin-wide scope is too broad"
3527        );
3528
3529        authority.allowed_target_prefixes = vec![
3530            "https://api.x.com/2/tweets".to_string(),
3531            "auth_profile:Twitter%20Prod%2Faccount".to_string(),
3532        ];
3533        assert!(authority.validate().is_ok());
3534
3535        authority.min_seconds_between_mutations = 899;
3536        assert!(authority.validate().is_err());
3537        authority.min_seconds_between_mutations = 900;
3538        authority.max_mutating_actions_per_rolling_24h = 25;
3539        assert!(authority.validate().is_err());
3540        authority.max_mutating_actions_per_rolling_24h = 1;
3541        authority.max_mutating_actions_per_cycle = 2;
3542        assert!(authority.validate().is_err());
3543    }
3544
3545    #[test]
3546    fn operation_scopes_project_exact_authority_and_validate_executable_http_shapes() {
3547        let read = MandateOperationScope {
3548            tool: "web_fetch".to_string(),
3549            operation: ToolCallOperation::Get,
3550            kind: MandateOperationKind::Observation,
3551            target_prefixes: vec!["https://blog.aidaemon.ai/posts/".to_string()],
3552            allowed_query_params: Vec::new(),
3553            mutation_effects: Vec::new(),
3554        };
3555        let post = MandateOperationScope {
3556            tool: "http_request".to_string(),
3557            operation: ToolCallOperation::Post,
3558            kind: MandateOperationKind::Mutation,
3559            target_prefixes: vec![
3560                "https://api.x.com/2/tweets".to_string(),
3561                "auth_profile:twitter".to_string(),
3562                "account:12345".to_string(),
3563            ],
3564            allowed_query_params: Vec::new(),
3565            mutation_effects: vec![
3566                "remote_mutation".to_string(),
3567                "external_delivery".to_string(),
3568            ],
3569        };
3570        let authority =
3571            MandateAuthority::from_operation_scopes(true, vec![read, post.clone()], 1, 1, 900);
3572        assert!(authority.validate().is_ok());
3573        assert_eq!(
3574            authority.allowed_tools,
3575            vec!["http_request".to_string(), "web_fetch".to_string()]
3576        );
3577        assert!(
3578            authority
3579                .allowed_target_prefixes
3580                .contains(&"account:12345".to_string())
3581        );
3582
3583        let mut missing_delivery = post.clone();
3584        missing_delivery.mutation_effects = vec!["remote_mutation".to_string()];
3585        assert!(missing_delivery.validate().is_err());
3586
3587        let mut missing_account = post;
3588        missing_account
3589            .target_prefixes
3590            .retain(|target| !target.starts_with("account:"));
3591        assert!(missing_account.validate().is_err());
3592    }
3593
3594    #[test]
3595    fn x_api_operation_scopes_require_bound_profile_and_account_identity() {
3596        let unbound = MandateOperationScope {
3597            tool: "http_request".to_string(),
3598            operation: ToolCallOperation::Get,
3599            kind: MandateOperationKind::Observation,
3600            target_prefixes: vec!["https://api.x.com/2/users/me".to_string()],
3601            allowed_query_params: Vec::new(),
3602            mutation_effects: Vec::new(),
3603        };
3604        let error = unbound.validate().unwrap_err();
3605        assert!(error.contains("X API operation scopes require exact auth_profile"));
3606
3607        let mut bound = unbound;
3608        bound
3609            .target_prefixes
3610            .push("auth_profile:twitter".to_string());
3611        bound.target_prefixes.push("account:12345".to_string());
3612        assert!(bound.validate().is_ok());
3613
3614        let public_api = MandateOperationScope {
3615            tool: "http_request".to_string(),
3616            operation: ToolCallOperation::Get,
3617            kind: MandateOperationKind::Observation,
3618            target_prefixes: vec!["https://api.example.test/v1/status".to_string()],
3619            allowed_query_params: Vec::new(),
3620            mutation_effects: Vec::new(),
3621        };
3622        assert!(public_api.validate().is_ok());
3623    }
3624
3625    #[test]
3626    fn dynamic_query_authority_is_bounded_to_observation_parameter_names() {
3627        let mut observation = MandateOperationScope {
3628            tool: "http_request".to_string(),
3629            operation: ToolCallOperation::Get,
3630            kind: MandateOperationKind::Observation,
3631            target_prefixes: vec!["https://api.example.test/v1/search".to_string()],
3632            allowed_query_params: vec!["query".to_string()],
3633            mutation_effects: Vec::new(),
3634        };
3635        assert!(observation.validate().is_ok());
3636
3637        observation.allowed_query_params = vec!["query=value".to_string()];
3638        assert!(observation.validate().is_err());
3639
3640        observation.allowed_query_params = vec!["query".to_string()];
3641        observation.target_prefixes[0] =
3642            "https://api.example.test/v1/search?query=exact".to_string();
3643        assert!(observation.validate().is_err());
3644
3645        let mutation = MandateOperationScope {
3646            tool: "http_request".to_string(),
3647            operation: ToolCallOperation::Post,
3648            kind: MandateOperationKind::Mutation,
3649            target_prefixes: vec!["https://api.example.test/v1/items".to_string()],
3650            allowed_query_params: vec!["destination".to_string()],
3651            mutation_effects: vec![
3652                "remote_mutation".to_string(),
3653                "external_delivery".to_string(),
3654            ],
3655        };
3656        assert!(mutation.validate().is_err());
3657    }
3658
3659    #[test]
3660    fn malformed_expiry_fails_closed() {
3661        let mut mandate = Mandate::new(
3662            "goal-id",
3663            None,
3664            "Test objective",
3665            "owner-session",
3666            MandateAuthority::default(),
3667            60,
3668            3_600,
3669            300,
3670        );
3671        mandate.expires_at = Some("not-a-timestamp".to_string());
3672        assert!(!mandate.is_active());
3673    }
3674
3675    #[test]
3676    fn next_review_is_capped_at_exact_expiry() {
3677        let now = chrono::DateTime::parse_from_rfc3339("2026-08-03T03:00:00Z")
3678            .unwrap()
3679            .with_timezone(&chrono::Utc);
3680        let mut mandate = Mandate::new(
3681            "goal-id",
3682            None,
3683            "Test expiry cap",
3684            "owner-session",
3685            MandateAuthority::default(),
3686            60,
3687            3_600,
3688            600,
3689        );
3690        let expiry = now + chrono::Duration::seconds(120);
3691        mandate.expires_at = Some(expiry.to_rfc3339());
3692
3693        assert_eq!(
3694            mandate.bounded_next_review_at(None, now),
3695            expiry.to_rfc3339()
3696        );
3697    }
3698
3699    #[test]
3700    fn typed_activity_edges_adjust_cadence_only_inside_confirmed_bounds() {
3701        let mandate = Mandate::new(
3702            "goal-id",
3703            None,
3704            "Adapt review cadence",
3705            "owner-session",
3706            MandateAuthority::default(),
3707            15 * 60,
3708            24 * 60 * 60,
3709            3 * 60 * 60,
3710        );
3711        assert_eq!(
3712            mandate.review_secs_for_activity(MandateActivityLevel::Quiet),
3713            3 * 60 * 60
3714        );
3715        assert_eq!(
3716            mandate.review_secs_for_activity(MandateActivityLevel::Active),
3717            60 * 60
3718        );
3719        assert_eq!(
3720            mandate.review_secs_for_activity(MandateActivityLevel::Urgent),
3721            15 * 60
3722        );
3723    }
3724
3725    #[test]
3726    fn objective_control_reads_legacy_rows_and_enforces_cadence_and_target() {
3727        // A row confirmed before the trim still carries experiment and
3728        // stagnation settings; they are ignored, not refused.
3729        let control: MandateObjectiveControl = serde_json::from_str(
3730            r#"{"schema_version":1,"metric_name":"weekly_engagements","unit":"engagements",
3731                "baseline_micros":5000000,"target_micros":8000000,"direction":"at_least",
3732                "measurement_source":"metric_source:synthetic-analytics",
3733                "measurement_cadence_secs":3600,"experiment_cohort":"synthetic-cohort-a",
3734                "experiment_window_secs":86400,"minimum_effect_micros":500000,
3735                "max_stagnant_measurements":3,"run_failure_budget":3,
3736                "baseline_observed_at":"2026-08-15T00:00:00Z"}"#,
3737        )
3738        .unwrap();
3739        assert!(control.validate().is_ok());
3740        assert!(!control.target_reached(7_999_999));
3741        assert!(control.target_reached(8_000_000));
3742        // Next measurement anchors on the latest observation, else the
3743        // baseline; either way it is exactly one cadence later.
3744        assert_eq!(
3745            control.next_measurement_at(None).as_deref(),
3746            Some("2026-08-15T01:00:00Z")
3747        );
3748        assert_eq!(
3749            control
3750                .next_measurement_at(Some("2026-08-16T12:30:00+02:00"))
3751                .as_deref(),
3752            Some("2026-08-16T11:30:00Z")
3753        );
3754        assert_eq!(
3755            control.next_measurement_at(Some("not a time")).as_deref(),
3756            Some("2026-08-15T01:00:00Z")
3757        );
3758
3759        let mut cadence = control.clone();
3760        cadence.measurement_cadence_secs = 59;
3761        assert!(
3762            cadence
3763                .validate()
3764                .unwrap_err()
3765                .starts_with("measurement_cadence_secs is 59")
3766        );
3767        let mut when = control.clone();
3768        when.baseline_observed_at = "yesterday".to_string();
3769        assert!(
3770            when.validate()
3771                .unwrap_err()
3772                .starts_with("baseline_observed_at is \"yesterday\"")
3773        );
3774    }
3775
3776    #[test]
3777    fn mandate_content_bounds_reject_utf8_byte_overflow_entry_overflow_and_combined_policy() {
3778        let mut mandate = Mandate::new(
3779            "goal-id",
3780            None,
3781            "bounded objective",
3782            "owner-session",
3783            MandateAuthority::default(),
3784            60,
3785            3_600,
3786            300,
3787        );
3788        assert!(mandate.validate_content_bounds().is_ok());
3789
3790        mandate.objective = "é".repeat(1_025);
3791        assert!(mandate.validate_content_bounds().is_err());
3792        mandate.objective = "bounded objective".to_string();
3793
3794        mandate.constraints = (0..17).map(|index| format!("constraint {index}")).collect();
3795        assert!(mandate.validate_content_bounds().is_err());
3796
3797        mandate.constraints = vec!["c".repeat(500); 6];
3798        mandate.success_criteria = vec!["s".repeat(500); 6];
3799        mandate.stop_conditions = vec!["x".repeat(500); 6];
3800        assert!(mandate.validate_content_bounds().is_err());
3801    }
3802
3803    #[test]
3804    fn authority_rejects_aggregate_serialized_size_and_utf8_byte_overflow() {
3805        let mut authority = MandateAuthority {
3806            allowed_tools: vec!["é".repeat(129)],
3807            ..MandateAuthority::default()
3808        };
3809        assert!(authority.validate().is_err());
3810
3811        authority.allowed_tools = vec!["web_fetch".to_string()];
3812        authority.allowed_target_prefixes = (0..16)
3813            .map(|index| format!("account:{index}-{}", "x".repeat(1_020)))
3814            .collect();
3815        assert!(authority.validate().is_err());
3816    }
3817
3818    #[test]
3819    fn decision_and_intention_bounds_validate_shape_bytes_and_combined_metadata() {
3820        let mut decision = MandateDecisionCycle::new(
3821            "mandate-id",
3822            "run-id",
3823            MandateDecisionOutcome::Wait,
3824            "bounded rationale",
3825            1,
3826        );
3827        decision.rationale = "é".repeat(1_025);
3828        assert!(decision.validate_content_bounds().is_err());
3829        decision.rationale = "bounded rationale".to_string();
3830        decision.belief_snapshot = Some(serde_json::json!({"not": "an array"}).to_string());
3831        assert!(decision.validate_content_bounds().is_err());
3832        decision.belief_snapshot = Some(serde_json::to_string(&vec!["observation"; 9]).unwrap());
3833        assert!(decision.validate_content_bounds().is_err());
3834        decision.belief_snapshot = Some(serde_json::to_string(&vec!["\"".repeat(750); 8]).unwrap());
3835        assert!(decision.validate_content_bounds().is_err());
3836        decision.belief_snapshot =
3837            Some(serde_json::to_string(&vec!["sourced observation"]).unwrap());
3838        decision.question = Some("é".repeat(251));
3839        assert!(decision.validate_content_bounds().is_err());
3840
3841        let mut intention = Intention::new(
3842            "mandate-id",
3843            &decision.id,
3844            "run-id",
3845            "bounded intention",
3846            "bounded rationale",
3847        );
3848        assert!(intention.validate_value_contract().is_err());
3849        intention.value_criterion = Some("Produce a verified useful outcome".to_string());
3850        intention.expected_benefit = Some("Advance the confirmed outcome".to_string());
3851        intention.risk = Some("No material downside after bounded checks".to_string());
3852        intention.invalidation_criteria =
3853            Some("New evidence shows the intervention would not help".to_string());
3854        assert!(intention.validate_value_contract().is_ok());
3855        intention.description = "é".repeat(513);
3856        assert!(intention.validate_content_bounds().is_err());
3857        intention.description = "bounded intention".to_string();
3858        intention.expected_benefit = Some("b".repeat(2_000));
3859        intention.risk = Some("r".repeat(2_000));
3860        intention.invalidation_criteria = Some("i".repeat(97));
3861        assert!(intention.validate_content_bounds().is_err());
3862    }
3863
3864    #[test]
3865    fn failed_reviews_notify_at_the_start_and_each_doubling_of_a_streak() {
3866        let notified: Vec<i64> = (0..=20)
3867            .filter(|failures| super::review_failure_is_notified(*failures))
3868            .collect();
3869        assert_eq!(notified, vec![1, 2, 4, 8, 16]);
3870    }
3871}