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