Skip to main content

aidaemon_work/sqlite/
mandates.rs

1use super::*;
2use crate::traits::{
3    GoalRun, Intention, IntentionStatus, Mandate, MandateActivityLevel, MandateAuthority,
4    MandateAutonomyMode, MandateDecisionCycle, MandateDecisionOrigin, MandateDecisionOutcome,
5    MandateDispatchGate, MandateFinalizationRejectReason, MandateFinalizationStaleReason,
6    MandateLearningNote, MandateMutationAttempt, MandateMutationAttemptStatus,
7    MandateMutationDispatchClaim, MandateMutationEvidence, MandateMutationQuotaBlockReason,
8    MandateMutationQuotaState, MandateMutationReservation, MandateObjectiveMeasurement,
9    MandateOperatingUpdates, MandateReconciliationReason, MandateReconciliationResolution,
10    MandateRunFinalizationRequest, MandateRunFinalizationResult, MandateRunProofCounts,
11    MandateStatus, MandateStore, MandateSuspension, MandateSuspensionKind, MandateTerminationKind,
12    MandateWakeSignal, Task,
13};
14use sha2::{Digest, Sha256};
15
16const MANDATE_COLUMNS: &str = "id, goal_id, source_goal_id, name, objective, status, autonomy_mode, authority_json, strategy_json, \
17     objective_control_json, suspension_json, constraints_json, \
18     success_criteria_json, stop_conditions_json, min_review_secs, max_review_secs, \
19     default_review_secs, review_effort, next_review_at, review_lease_token, review_lease_expires_at, \
20     expires_at, confirmed_at, version, owner_principal_id, created_by_session, created_at, updated_at";
21
22const DECISION_COLUMNS: &str = "id, mandate_id, goal_run_id, mandate_version, outcome, origin, activity_level, rationale, belief_snapshot, \
23     evidence_receipt_ids_json, question, owner_alert, termination_kind, termination_match, \
24     reconsider_at, action_attempts, created_at, updated_at";
25
26const INTENTION_COLUMNS: &str = "id, mandate_id, decision_cycle_id, goal_run_id, description, rationale, \
27     value_criterion, expected_benefit, risk, invalidation_criteria, status, created_at, updated_at, completed_at";
28
29const LEARNING_NOTE_COLUMNS: &str = "id, mandate_id, mandate_version, learned_in_decision_cycle_id, summary, \
30     evidence_receipt_ids_json, created_at";
31
32const MUTATION_ATTEMPT_COLUMNS: &str = "id, mandate_id, mandate_version, decision_cycle_id, goal_run_id, intention_id, \
33     root_task_id, root_task_attempt_id, task_id, task_attempt_id, reserved_action_attempt, \
34     action_digest, tool_call_id, tool_name, mutation_effects_json, targets_json, \
35     account_identifiers_json, status, outcome_evidence, http_status, exit_code, \
36     reserved_at, completed_at";
37
38fn qualified_columns(alias: &str, columns: &str) -> String {
39    columns
40        .split(", ")
41        .map(|column| format!("{alias}.{column}"))
42        .collect::<Vec<_>>()
43        .join(", ")
44}
45
46fn mandate_from_row(row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<Mandate> {
47    let status_raw: String = row.get("status");
48    let status = MandateStatus::parse(&status_raw)
49        .ok_or_else(|| anyhow::anyhow!("invalid mandate status `{status_raw}`"))?;
50    Ok(Mandate {
51        id: row.get("id"),
52        goal_id: row.get("goal_id"),
53        source_goal_id: row.get("source_goal_id"),
54        name: row.get("name"),
55        objective: row.get("objective"),
56        status,
57        autonomy_mode: MandateAutonomyMode::parse(&row.get::<String, _>("autonomy_mode"))
58            .ok_or_else(|| anyhow::anyhow!("invalid mandate autonomy mode"))?,
59        authority: serde_json::from_str::<MandateAuthority>(
60            &row.get::<String, _>("authority_json"),
61        )?,
62        strategy: row
63            .get::<Option<String>, _>("strategy_json")
64            .map(|value| serde_json::from_str(&value))
65            .transpose()?,
66        objective_control: row
67            .get::<Option<String>, _>("objective_control_json")
68            .map(|value| serde_json::from_str(&value))
69            .transpose()?,
70        suspension: row
71            .get::<Option<String>, _>("suspension_json")
72            .map(|value| serde_json::from_str(&value))
73            .transpose()?,
74        constraints: serde_json::from_str(&row.get::<String, _>("constraints_json"))?,
75        success_criteria: serde_json::from_str(&row.get::<String, _>("success_criteria_json"))?,
76        stop_conditions: serde_json::from_str(&row.get::<String, _>("stop_conditions_json"))?,
77        min_review_secs: row.get("min_review_secs"),
78        max_review_secs: row.get("max_review_secs"),
79        default_review_secs: row.get("default_review_secs"),
80        review_effort: row.get("review_effort"),
81        next_review_at: row.get("next_review_at"),
82        review_lease_token: row.get("review_lease_token"),
83        review_lease_expires_at: row.get("review_lease_expires_at"),
84        expires_at: row.get("expires_at"),
85        confirmed_at: row.get("confirmed_at"),
86        version: row.get("version"),
87        owner_principal_id: row.get("owner_principal_id"),
88        created_by_session: row.get("created_by_session"),
89        created_at: row.get("created_at"),
90        updated_at: row.get("updated_at"),
91    })
92}
93
94fn decision_from_row(row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<MandateDecisionCycle> {
95    let outcome_raw: String = row.get("outcome");
96    let outcome = MandateDecisionOutcome::parse(&outcome_raw)
97        .ok_or_else(|| anyhow::anyhow!("invalid mandate decision outcome `{outcome_raw}`"))?;
98    Ok(MandateDecisionCycle {
99        id: row.get("id"),
100        mandate_id: row.get("mandate_id"),
101        goal_run_id: row.get("goal_run_id"),
102        mandate_version: row.get("mandate_version"),
103        outcome,
104        origin: MandateDecisionOrigin::parse(&row.get::<String, _>("origin"))
105            .ok_or_else(|| anyhow::anyhow!("invalid mandate decision origin"))?,
106        activity_level: MandateActivityLevel::parse(&row.get::<String, _>("activity_level"))
107            .ok_or_else(|| anyhow::anyhow!("invalid mandate activity level"))?,
108        rationale: row.get("rationale"),
109        belief_snapshot: row.get("belief_snapshot"),
110        evidence_receipt_ids: serde_json::from_str(
111            &row.get::<String, _>("evidence_receipt_ids_json"),
112        )?,
113        question: row.get("question"),
114        owner_alert: row.get("owner_alert"),
115        termination_kind: row
116            .get::<Option<String>, _>("termination_kind")
117            .map(|value| {
118                MandateTerminationKind::parse(&value)
119                    .ok_or_else(|| anyhow::anyhow!("invalid mandate termination kind `{value}`"))
120            })
121            .transpose()?,
122        termination_match: row.get("termination_match"),
123        reconsider_at: row.get("reconsider_at"),
124        action_attempts: row.get("action_attempts"),
125        created_at: row.get("created_at"),
126        updated_at: row.get("updated_at"),
127    })
128}
129
130fn objective_measurement_from_row(
131    row: &sqlx::sqlite::SqliteRow,
132) -> anyhow::Result<MandateObjectiveMeasurement> {
133    Ok(MandateObjectiveMeasurement {
134        id: row.get("id"),
135        mandate_id: row.get("mandate_id"),
136        mandate_version: row.get("mandate_version"),
137        goal_run_id: row.get("goal_run_id"),
138        value_micros: row.get("value_micros"),
139        confidence_bps: u16::try_from(row.get::<i64, _>("confidence_bps"))?,
140        evidence_receipt_ids: serde_json::from_str(
141            &row.get::<String, _>("evidence_receipt_ids_json"),
142        )?,
143        observed_at: row.get("observed_at"),
144        created_at: row.get("created_at"),
145    })
146}
147
148fn intention_from_row(row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<Intention> {
149    let status_raw: String = row.get("status");
150    let status = IntentionStatus::parse(&status_raw)
151        .ok_or_else(|| anyhow::anyhow!("invalid intention status `{status_raw}`"))?;
152    Ok(Intention {
153        id: row.get("id"),
154        mandate_id: row.get("mandate_id"),
155        decision_cycle_id: row.get("decision_cycle_id"),
156        goal_run_id: row.get("goal_run_id"),
157        description: row.get("description"),
158        rationale: row.get("rationale"),
159        value_criterion: row.get("value_criterion"),
160        expected_benefit: row.get("expected_benefit"),
161        risk: row.get("risk"),
162        invalidation_criteria: row.get("invalidation_criteria"),
163        status,
164        created_at: row.get("created_at"),
165        updated_at: row.get("updated_at"),
166        completed_at: row.get("completed_at"),
167    })
168}
169
170fn learning_note_from_row(row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<MandateLearningNote> {
171    Ok(MandateLearningNote {
172        id: row.get("id"),
173        mandate_id: row.get("mandate_id"),
174        mandate_version: row.get("mandate_version"),
175        learned_in_decision_cycle_id: row.get("learned_in_decision_cycle_id"),
176        summary: row.get("summary"),
177        evidence_receipt_ids: serde_json::from_str(
178            &row.get::<String, _>("evidence_receipt_ids_json"),
179        )?,
180        created_at: row.get("created_at"),
181    })
182}
183
184fn mutation_attempt_from_row(
185    row: &sqlx::sqlite::SqliteRow,
186) -> anyhow::Result<MandateMutationAttempt> {
187    let status_raw: String = row.get("status");
188    let status = MandateMutationAttemptStatus::parse(&status_raw)
189        .ok_or_else(|| anyhow::anyhow!("invalid mandate mutation status `{status_raw}`"))?;
190    let evidence_raw: Option<String> = row.get("outcome_evidence");
191    let outcome_evidence = evidence_raw
192        .as_deref()
193        .map(|value| {
194            MandateMutationEvidence::parse(value)
195                .ok_or_else(|| anyhow::anyhow!("invalid mandate mutation evidence `{value}`"))
196        })
197        .transpose()?;
198    let http_status = row
199        .get::<Option<i64>, _>("http_status")
200        .map(u16::try_from)
201        .transpose()
202        .map_err(|_| anyhow::anyhow!("invalid mandate mutation HTTP status"))?;
203    Ok(MandateMutationAttempt {
204        id: row.get("id"),
205        mandate_id: row.get("mandate_id"),
206        mandate_version: row.get("mandate_version"),
207        decision_cycle_id: row.get("decision_cycle_id"),
208        goal_run_id: row.get("goal_run_id"),
209        intention_id: row.get("intention_id"),
210        root_task_id: row.get("root_task_id"),
211        root_task_attempt_id: row.get("root_task_attempt_id"),
212        task_id: row.get("task_id"),
213        task_attempt_id: row.get("task_attempt_id"),
214        reserved_action_attempt: row.get("reserved_action_attempt"),
215        action_digest: row.get("action_digest"),
216        tool_call_id: row.get("tool_call_id"),
217        tool_name: row.get("tool_name"),
218        mutation_effects: serde_json::from_str(&row.get::<String, _>("mutation_effects_json"))?,
219        targets: serde_json::from_str(&row.get::<String, _>("targets_json"))?,
220        account_identifiers: serde_json::from_str(
221            &row.get::<String, _>("account_identifiers_json"),
222        )?,
223        status,
224        outcome_evidence,
225        http_status,
226        exit_code: row.get("exit_code"),
227        reserved_at: row.get("reserved_at"),
228        completed_at: row.get("completed_at"),
229    })
230}
231
232fn validate_timestamp(label: &str, value: &str) -> anyhow::Result<()> {
233    chrono::DateTime::parse_from_rfc3339(value)
234        .map(|_| ())
235        .map_err(|error| anyhow::anyhow!("invalid {label}: {error}"))
236}
237
238fn validate_mandate(mandate: &Mandate) -> anyhow::Result<()> {
239    anyhow::ensure!(!mandate.id.trim().is_empty(), "mandate id is required");
240    mandate
241        .validate_content_bounds()
242        .map_err(anyhow::Error::msg)?;
243    crate::authority::validate_objective_measurement_source(mandate).map_err(anyhow::Error::msg)?;
244    anyhow::ensure!(
245        !mandate.created_by_session.trim().is_empty(),
246        "mandate owner session is required"
247    );
248    anyhow::ensure!(
249        mandate.owner_principal_id.starts_with("principal:")
250            && mandate.owner_principal_id.len() <= 256
251            && !mandate.owner_principal_id.chars().any(char::is_control),
252        "mandate owner principal is invalid"
253    );
254    mandate.authority.validate().map_err(anyhow::Error::msg)?;
255    if let Some(control) = mandate.objective_control.as_ref() {
256        anyhow::ensure!(
257            control.measurement_cadence_secs >= mandate.min_review_secs
258                && control.measurement_cadence_secs <= mandate.max_review_secs,
259            "objective measurement cadence must fit inside the mandate review bounds"
260        );
261    }
262    anyhow::ensure!(
263        mandate.min_review_secs > 0
264            && mandate.min_review_secs <= mandate.default_review_secs
265            && mandate.default_review_secs <= mandate.max_review_secs,
266        "mandate review bounds must satisfy 0 < min <= default <= max"
267    );
268    anyhow::ensure!(mandate.version > 0, "mandate version must be positive");
269    validate_timestamp("next_review_at", &mandate.next_review_at)?;
270    if let Some(expires_at) = mandate.expires_at.as_deref() {
271        validate_timestamp("expires_at", expires_at)?;
272    }
273    if let Some(confirmed_at) = mandate.confirmed_at.as_deref() {
274        validate_timestamp("confirmed_at", confirmed_at)?;
275    }
276    anyhow::ensure!(
277        mandate.status != MandateStatus::Active || mandate.confirmed_at.is_some(),
278        "an active mandate requires durable owner confirmation"
279    );
280    anyhow::ensure!(
281        match mandate.status {
282            MandateStatus::Active | MandateStatus::Completed | MandateStatus::Cancelled => {
283                mandate.suspension.is_none()
284            }
285            MandateStatus::Paused if mandate.confirmed_at.is_none() => mandate.suspension.is_none(),
286            MandateStatus::Paused => mandate
287                .suspension
288                .as_ref()
289                .is_some_and(|value| value.kind == MandateSuspensionKind::OwnerPaused),
290            MandateStatus::AwaitingInput => mandate.suspension.is_some(),
291        },
292        "mandate lifecycle status and typed suspension disagree"
293    );
294    match (
295        mandate.review_lease_token.as_deref(),
296        mandate.review_lease_expires_at.as_deref(),
297    ) {
298        (None, None) => {}
299        (Some(token), Some(expires_at)) => {
300            anyhow::ensure!(!token.trim().is_empty(), "review lease token is empty");
301            validate_timestamp("review_lease_expires_at", expires_at)?;
302        }
303        _ => {
304            anyhow::bail!("review lease token and expiry must either both be set or both be empty")
305        }
306    }
307    Ok(())
308}
309
310fn validate_new_mandate(mandate: &Mandate) -> anyhow::Result<()> {
311    validate_mandate(mandate)?;
312    anyhow::ensure!(
313        mandate.version == 1,
314        "a new mandate must start at version 1"
315    );
316    anyhow::ensure!(
317        mandate.review_lease_token.is_none() && mandate.review_lease_expires_at.is_none(),
318        "a new mandate cannot start with a review lease"
319    );
320    Ok(())
321}
322
323fn controller_goal_status(mandate_status: MandateStatus) -> &'static str {
324    match mandate_status {
325        MandateStatus::Active => "active",
326        MandateStatus::Paused | MandateStatus::AwaitingInput => "paused",
327        MandateStatus::Completed => "completed",
328        MandateStatus::Cancelled => "cancelled",
329    }
330}
331
332fn intention_transition(
333    from: IntentionStatus,
334    to: IntentionStatus,
335) -> anyhow::Result<(&'static str, &'static str)> {
336    anyhow::ensure!(
337        from.can_transition_to(to),
338        "invalid intention status transition {from} -> {to}"
339    );
340    Ok((from.as_str(), to.as_str()))
341}
342
343fn clamped_next_review_at(
344    mandate: &Mandate,
345    requested: Option<&str>,
346    now: chrono::DateTime<chrono::Utc>,
347) -> anyhow::Result<String> {
348    let candidate = match requested {
349        Some(value) => chrono::DateTime::parse_from_rfc3339(value)
350            .map_err(|error| anyhow::anyhow!("invalid reconsider_at: {error}"))?
351            .with_timezone(&chrono::Utc),
352        None => now + chrono::Duration::seconds(mandate.default_review_secs),
353    };
354    let earliest = now + chrono::Duration::seconds(mandate.min_review_secs);
355    let latest = now + chrono::Duration::seconds(mandate.max_review_secs);
356    let candidate = candidate.clamp(earliest, latest);
357    Ok(mandate
358        .expires_at
359        .as_deref()
360        .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
361        .map(|expires| expires.with_timezone(&chrono::Utc))
362        .filter(|expires| *expires < candidate)
363        .unwrap_or(candidate)
364        .to_rfc3339())
365}
366
367async fn validate_current_run_receipt_refs(
368    connection: &mut sqlx::SqliteConnection,
369    goal_run_id: &str,
370    refs: &[String],
371) -> anyhow::Result<()> {
372    let mut unique = std::collections::HashSet::new();
373    for receipt_id in refs {
374        anyhow::ensure!(
375            unique.insert(receipt_id),
376            "duplicate mandate evidence receipt ID"
377        );
378        // A durable receipt has two canonical identities that the model can
379        // legitimately observe: the tool_call_id it issued and the result_id
380        // stamped on the receipt footer it read back. Either one names the
381        // same current-run structured success.
382        let found = sqlx::query_scalar::<_, i64>(
383            "SELECT 1
384             FROM events e
385             JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
386             WHERE e.event_type = 'tool_result'
387               AND t.goal_run_id = ?
388               AND (
389                   json_extract(e.data, '$.tool_call_id') = ?
390                   OR json_extract(e.data, '$.receipt.result_provenance.result_id') = ?
391               )
392               AND json_extract(e.data, '$.receipt.schema_version') = ?
393               AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
394               AND json_extract(e.data, '$.receipt.outcome_evidence')
395                   IN ('tool_reported', 'structured_metadata')
396             LIMIT 1",
397        )
398        .bind(goal_run_id)
399        .bind(receipt_id)
400        .bind(receipt_id)
401        .bind(i64::from(aidaemon_events::ToolReceiptV1::SCHEMA_VERSION))
402        .fetch_optional(&mut *connection)
403        .await?;
404        anyhow::ensure!(
405            found.is_some(),
406            "mandate evidence receipt `{receipt_id}` is not a current-run structured success"
407        );
408    }
409    Ok(())
410}
411
412fn validate_canonical_identifier(label: &str, value: &str, max_chars: usize) -> anyhow::Result<()> {
413    anyhow::ensure!(
414        !value.is_empty()
415            && value.trim() == value
416            && value.chars().count() <= max_chars
417            && !value.chars().any(char::is_control),
418        "invalid mandate mutation {label}"
419    );
420    Ok(())
421}
422
423fn validate_mutation_reservation(
424    reservation: &MandateMutationReservation,
425) -> anyhow::Result<chrono::DateTime<chrono::Utc>> {
426    let grant = &reservation.grant;
427    validate_canonical_identifier("mandate id", &grant.mandate_id, 256)?;
428    validate_canonical_identifier("owner principal id", &grant.owner_principal_id, 256)?;
429    anyhow::ensure!(
430        grant.owner_principal_id.starts_with("principal:"),
431        "invalid mandate owner principal"
432    );
433    validate_canonical_identifier("decision cycle id", &grant.decision_cycle_id, 256)?;
434    anyhow::ensure!(grant.mandate_version > 0, "invalid mandate version");
435    anyhow::ensure!(
436        grant.counts_toward_cycle_budget && grant.reserved_action_attempt > 0,
437        "mutation reservation requires a positive metered grant"
438    );
439    anyhow::ensure!(
440        grant.action_digest.len() == 64
441            && grant
442                .action_digest
443                .bytes()
444                .all(|byte| byte.is_ascii_hexdigit()),
445        "invalid mandate mutation action digest"
446    );
447    anyhow::ensure!(
448        grant.tool_call_id.as_deref() == Some(reservation.tool_call_id.as_str()),
449        "mutation reservation tool call does not match its bound grant"
450    );
451    for (label, value) in [
452        ("goal run id", reservation.goal_run_id.as_str()),
453        ("root task id", reservation.root_task_id.as_str()),
454        (
455            "root task attempt id",
456            reservation.root_task_attempt_id.as_str(),
457        ),
458        ("task id", reservation.task_id.as_str()),
459        ("task attempt id", reservation.task_attempt_id.as_str()),
460        ("tool call id", reservation.tool_call_id.as_str()),
461        ("tool name", reservation.tool_name.as_str()),
462    ] {
463        validate_canonical_identifier(label, value, 256)?;
464    }
465    anyhow::ensure!(
466        reservation.task_id != reservation.root_task_id,
467        "the mandate deliberator cannot reserve mutations"
468    );
469    anyhow::ensure!(
470        !reservation.mutation_effects.is_empty()
471            && reservation.mutation_effects.len() <= MandateAuthority::EFFECT_NAMES.len(),
472        "invalid mandate mutation effects"
473    );
474    let mut seen_effects = std::collections::HashSet::new();
475    for effect in &reservation.mutation_effects {
476        anyhow::ensure!(
477            MandateAuthority::EFFECT_NAMES.contains(&effect.as_str())
478                && seen_effects.insert(effect.as_str()),
479            "invalid or duplicate mandate mutation effect"
480        );
481    }
482    anyhow::ensure!(
483        !reservation.targets.is_empty() && reservation.targets.len() <= 16,
484        "mandate mutations require bounded typed targets"
485    );
486    let mut seen_targets = std::collections::HashSet::new();
487    for target in &reservation.targets {
488        anyhow::ensure!(
489            matches!(target.kind.as_str(), "url" | "resource_id"),
490            "unsupported mandate mutation target kind"
491        );
492        validate_canonical_identifier("target", &target.identifier, 2_048)?;
493        anyhow::ensure!(
494            seen_targets.insert((target.kind.as_str(), target.identifier.as_str())),
495            "duplicate mandate mutation target"
496        );
497        if target.kind == "url" {
498            let parsed = reqwest::Url::parse(&target.identifier)
499                .map_err(|_| anyhow::anyhow!("invalid mandate mutation URL target"))?;
500            anyhow::ensure!(
501                parsed.query().is_none()
502                    && parsed.fragment().is_none()
503                    && parsed.username().is_empty()
504                    && parsed.password().is_none(),
505                "mandate mutation audit URLs cannot contain query, fragment, or userinfo"
506            );
507        }
508    }
509    anyhow::ensure!(
510        reservation.account_identifiers.len() <= 8,
511        "too many mandate mutation account identifiers"
512    );
513    let resource_targets = reservation
514        .targets
515        .iter()
516        .filter(|target| target.kind == "resource_id")
517        .map(|target| target.identifier.as_str())
518        .collect::<std::collections::HashSet<_>>();
519    let mut seen_accounts = std::collections::HashSet::new();
520    for account in &reservation.account_identifiers {
521        validate_canonical_identifier("account identifier", account, 256)?;
522        anyhow::ensure!(
523            (account.starts_with("auth_profile:") || account.starts_with("account:"))
524                && resource_targets.contains(account.as_str())
525                && seen_accounts.insert(account.as_str()),
526            "invalid mandate mutation account identifier"
527        );
528    }
529    let reserved_at = chrono::DateTime::parse_from_rfc3339(&reservation.reserved_at)
530        .map_err(|_| anyhow::anyhow!("invalid mandate mutation reservation timestamp"))?
531        .with_timezone(&chrono::Utc);
532    Ok(reserved_at)
533}
534
535async fn mutation_quota_state_on_connection(
536    connection: &mut sqlx::SqliteConnection,
537    mandate_id: &str,
538    as_of_raw: &str,
539) -> anyhow::Result<Option<MandateMutationQuotaState>> {
540    let as_of = chrono::DateTime::parse_from_rfc3339(as_of_raw)
541        .map_err(|_| anyhow::anyhow!("invalid mutation quota timestamp"))?
542        .with_timezone(&chrono::Utc);
543    let authority_json =
544        sqlx::query_scalar::<_, String>("SELECT authority_json FROM mandates WHERE id = ?")
545            .bind(mandate_id)
546            .fetch_optional(&mut *connection)
547            .await?;
548    let Some(authority_json) = authority_json else {
549        return Ok(None);
550    };
551    let authority: MandateAuthority = serde_json::from_str(&authority_json)?;
552    authority.validate().map_err(anyhow::Error::msg)?;
553    let window_start = as_of - chrono::Duration::hours(24);
554    let rows = sqlx::query_scalar::<_, String>(
555        "SELECT reserved_at FROM mandate_mutation_attempts
556         WHERE mandate_id = ? AND julianday(reserved_at) > julianday(?)
557           AND status != 'never_dispatched'
558         ORDER BY julianday(reserved_at), id",
559    )
560    .bind(mandate_id)
561    .bind(window_start.to_rfc3339())
562    .fetch_all(&mut *connection)
563    .await?;
564    let mut reservations = Vec::with_capacity(rows.len());
565    for row in rows {
566        reservations.push(
567            chrono::DateTime::parse_from_rfc3339(&row)
568                .map_err(|_| anyhow::anyhow!("invalid persisted mutation reservation timestamp"))?
569                .with_timezone(&chrono::Utc),
570        );
571    }
572    let used = u32::try_from(reservations.len()).unwrap_or(u32::MAX);
573    let max = authority.max_mutating_actions_per_rolling_24h;
574    let remaining = max.saturating_sub(used);
575    let last = reservations.last().copied();
576    if authority.max_mutating_actions_per_cycle == 0 || max == 0 {
577        return Ok(Some(MandateMutationQuotaState {
578            mandate_id: mandate_id.to_string(),
579            as_of: as_of.to_rfc3339(),
580            max_mutating_actions_per_rolling_24h: max,
581            min_seconds_between_mutations: authority.min_seconds_between_mutations,
582            reserved_in_rolling_24h: used,
583            remaining_in_rolling_24h: remaining,
584            last_reserved_at: last.map(|value| value.to_rfc3339()),
585            available_now: false,
586            block_reason: Some(MandateMutationQuotaBlockReason::MutationDisabled),
587            earliest_next_slot_at: None,
588        }));
589    }
590
591    let quota_slot = (used >= max)
592        .then(|| reservations.first().copied())
593        .flatten()
594        .map(|oldest| oldest + chrono::Duration::hours(24));
595    let cooldown_slot = last.map(|last| {
596        last + chrono::Duration::seconds(i64::from(authority.min_seconds_between_mutations))
597    });
598    let earliest = match (quota_slot, cooldown_slot) {
599        (Some(left), Some(right)) => Some(left.max(right)),
600        (Some(value), None) | (None, Some(value)) => Some(value),
601        (None, None) => None,
602    };
603    let available_now = used < max && earliest.is_none_or(|slot| slot <= as_of);
604    let block_reason = if used >= max {
605        Some(MandateMutationQuotaBlockReason::Rolling24hExhausted)
606    } else if !available_now {
607        Some(MandateMutationQuotaBlockReason::Cooldown)
608    } else {
609        None
610    };
611    Ok(Some(MandateMutationQuotaState {
612        mandate_id: mandate_id.to_string(),
613        as_of: as_of.to_rfc3339(),
614        max_mutating_actions_per_rolling_24h: max,
615        min_seconds_between_mutations: authority.min_seconds_between_mutations,
616        reserved_in_rolling_24h: used,
617        remaining_in_rolling_24h: remaining,
618        last_reserved_at: last.map(|value| value.to_rfc3339()),
619        available_now,
620        block_reason,
621        earliest_next_slot_at: (!available_now)
622            .then(|| earliest.map(|value| value.to_rfc3339()))
623            .flatten(),
624    }))
625}
626
627async fn insert_mandate_row(
628    connection: &mut sqlx::SqliteConnection,
629    mandate: &Mandate,
630) -> anyhow::Result<()> {
631    sqlx::query(
632        "INSERT INTO mandates (
633            id, goal_id, source_goal_id, name, objective, status, autonomy_mode, authority_json, strategy_json,
634            objective_control_json, suspension_json,
635            constraints_json, success_criteria_json, stop_conditions_json,
636            min_review_secs, max_review_secs, default_review_secs, review_effort, next_review_at,
637            review_lease_token, review_lease_expires_at, expires_at, confirmed_at,
638            version, owner_principal_id, created_by_session, created_at, updated_at
639         ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
640    )
641    .bind(&mandate.id)
642    .bind(&mandate.goal_id)
643    .bind(&mandate.source_goal_id)
644    .bind(&mandate.name)
645    .bind(&mandate.objective)
646    .bind(mandate.status.as_str())
647    .bind(mandate.autonomy_mode.as_str())
648    .bind(serde_json::to_string(&mandate.authority)?)
649    .bind(
650        mandate
651            .strategy
652            .as_ref()
653            .map(serde_json::to_string)
654            .transpose()?,
655    )
656    .bind(
657        mandate
658            .objective_control
659            .as_ref()
660            .map(serde_json::to_string)
661            .transpose()?,
662    )
663    .bind(
664        mandate
665            .suspension
666            .as_ref()
667            .map(serde_json::to_string)
668            .transpose()?,
669    )
670    .bind(serde_json::to_string(&mandate.constraints)?)
671    .bind(serde_json::to_string(&mandate.success_criteria)?)
672    .bind(serde_json::to_string(&mandate.stop_conditions)?)
673    .bind(mandate.min_review_secs)
674    .bind(mandate.max_review_secs)
675    .bind(mandate.default_review_secs)
676    .bind(&mandate.review_effort)
677    .bind(&mandate.next_review_at)
678    .bind(&mandate.review_lease_token)
679    .bind(&mandate.review_lease_expires_at)
680    .bind(&mandate.expires_at)
681    .bind(&mandate.confirmed_at)
682    .bind(mandate.version)
683    .bind(&mandate.owner_principal_id)
684    .bind(&mandate.created_by_session)
685    .bind(&mandate.created_at)
686    .bind(&mandate.updated_at)
687    .execute(connection)
688    .await?;
689    Ok(())
690}
691
692async fn validate_source_goal(
693    connection: &mut sqlx::SqliteConnection,
694    source_goal_id: Option<&str>,
695    owner_session_id: &str,
696) -> anyhow::Result<()> {
697    let Some(source_goal_id) = source_goal_id else {
698        return Ok(());
699    };
700    let source = sqlx::query("SELECT domain, session_id FROM goals WHERE id = ?")
701        .bind(source_goal_id)
702        .fetch_optional(connection)
703        .await?
704        .ok_or_else(|| anyhow::anyhow!("source personal goal not found"))?;
705    anyhow::ensure!(
706        source.get::<String, _>("domain") == "personal",
707        "source_goal_id must reference a personal goal"
708    );
709    anyhow::ensure!(
710        source.get::<String, _>("session_id") == owner_session_id,
711        "source personal goal belongs to a different owner session; choose a goal marked mandate-source compatible or omit source_goal_id"
712    );
713    Ok(())
714}
715
716async fn update_controller_status(
717    connection: &mut sqlx::SqliteConnection,
718    goal_id: &str,
719    mandate_status: MandateStatus,
720    now: &str,
721) -> anyhow::Result<()> {
722    let goal_status = controller_goal_status(mandate_status);
723    let result = sqlx::query(
724        "UPDATE goals
725         SET status = ?, updated_at = ?,
726             completed_at = CASE WHEN ? IN ('completed', 'cancelled') THEN ? ELSE NULL END
727         WHERE id = ? AND domain = 'orchestration' AND goal_type = 'continuous'",
728    )
729    .bind(goal_status)
730    .bind(now)
731    .bind(goal_status)
732    .bind(now)
733    .bind(goal_id)
734    .execute(connection)
735    .await?;
736    anyhow::ensure!(
737        result.rows_affected() == 1,
738        "mandate controller goal not found"
739    );
740    Ok(())
741}
742
743async fn invalidate_open_mandate_runs(
744    connection: &mut sqlx::SqliteConnection,
745    goal_id: &str,
746    now: &str,
747) -> anyhow::Result<i64> {
748    let claimed_unresolved: i64 = sqlx::query_scalar(
749        "SELECT COUNT(*)
750         FROM mandate_mutation_attempts ma
751         JOIN goal_runs gr ON gr.id = ma.goal_run_id
752         WHERE gr.goal_id = ? AND gr.trigger_type = 'mandate'
753           AND gr.status IN ('pending', 'running', 'blocked')
754           AND ma.status = 'reserved' AND ma.dispatch_claimed_at IS NOT NULL",
755    )
756    .bind(goal_id)
757    .fetch_one(&mut *connection)
758    .await?;
759
760    // Linearize authority revocation with the mutation ledger before leases
761    // and runs are closed. A reservation that never reached the final
762    // dispatcher is explicitly non-quota/non-ambiguous; once the one-use
763    // dispatch claim exists, absence of a strict receipt is externally
764    // indeterminate and must remain reconciliation-required.
765    sqlx::query(
766        "UPDATE mandate_mutation_attempts
767         SET status = CASE
768                 WHEN dispatch_claimed_at IS NULL THEN 'never_dispatched'
769                 ELSE 'ambiguous'
770             END,
771             completed_at = COALESCE(completed_at, ?)
772         WHERE status = 'reserved'
773           AND goal_run_id IN (
774               SELECT id FROM goal_runs
775               WHERE goal_id = ? AND trigger_type = 'mandate'
776                 AND status IN ('pending', 'running', 'blocked')
777           )",
778    )
779    .bind(now)
780    .bind(goal_id)
781    .execute(&mut *connection)
782    .await?;
783
784    if claimed_unresolved > 0 {
785        let rows = sqlx::query(
786            "SELECT m.id AS mandate_id, m.version AS mandate_version,
787                    gr.goal_id, gr.id AS goal_run_id, g.session_id,
788                    (SELECT COUNT(*) FROM tasks t
789                     WHERE t.goal_run_id = gr.id AND t.id != COALESCE(gr.root_task_id, ''))
790                        AS non_root_tasks,
791                    (SELECT COUNT(*) FROM tasks t
792                     WHERE t.goal_run_id = gr.id AND t.id != COALESCE(gr.root_task_id, '')
793                       AND t.status = 'completed'
794                       AND COALESCE(NULLIF(trim(t.error), ''), '') = ''
795                       AND COALESCE(NULLIF(trim(t.blocker), ''), '') = '')
796                        AS completed_tasks,
797                    (SELECT COUNT(*) FROM tasks t
798                     WHERE t.goal_run_id = gr.id AND t.id != COALESCE(gr.root_task_id, '')
799                       AND (t.status IN ('failed', 'blocked', 'interrupted')
800                         OR COALESCE(NULLIF(trim(t.error), ''), '') != ''
801                         OR COALESCE(NULLIF(trim(t.blocker), ''), '') != ''))
802                        AS failed_or_blocked_tasks,
803                    (SELECT COUNT(*) FROM mandate_mutation_attempts x
804                     WHERE x.goal_run_id = gr.id) AS mutation_reservations,
805                    (SELECT COUNT(*) FROM mandate_mutation_attempts x
806                     WHERE x.goal_run_id = gr.id AND x.status = 'succeeded')
807                        AS succeeded_mutations,
808                    (SELECT COUNT(*) FROM mandate_mutation_attempts x
809                     WHERE x.goal_run_id = gr.id AND x.status = 'failed')
810                        AS failed_mutations,
811                    (SELECT COUNT(*) FROM mandate_mutation_attempts x
812                     WHERE x.goal_run_id = gr.id AND x.status = 'never_dispatched')
813                        AS never_dispatched_mutations,
814                    (SELECT COUNT(*) FROM mandate_mutation_attempts x
815                     WHERE x.goal_run_id = gr.id AND x.status IN ('reserved', 'ambiguous'))
816                        AS ambiguous_mutations
817             FROM goal_runs gr
818             JOIN mandates m ON m.goal_id = gr.goal_id
819             JOIN goals g ON g.id = gr.goal_id
820             WHERE gr.goal_id = ? AND gr.trigger_type = 'mandate'
821               AND gr.status IN ('pending', 'running', 'blocked')
822               AND EXISTS (
823                   SELECT 1 FROM mandate_mutation_attempts ma
824                   WHERE ma.goal_run_id = gr.id AND ma.status = 'ambiguous'
825               )",
826        )
827        .bind(goal_id)
828        .fetch_all(&mut *connection)
829        .await?;
830        let count = |row: &sqlx::sqlite::SqliteRow, name: &str| {
831            u32::try_from(row.get::<i64, _>(name).max(0)).unwrap_or(u32::MAX)
832        };
833        for row in rows {
834            let non_root_tasks = count(&row, "non_root_tasks");
835            let completed_tasks = count(&row, "completed_tasks");
836            let notice = crate::traits::MandateRunNotification::new(
837                &row.get::<String, _>("mandate_id"),
838                row.get("mandate_version"),
839                &row.get::<String, _>("goal_id"),
840                &row.get::<String, _>("goal_run_id"),
841                &row.get::<String, _>("session_id"),
842                crate::traits::MandateRunNotificationKind::AuthorityRevokedWithUnresolvedMutation,
843                crate::traits::MandateRunProofCounts {
844                    non_root_tasks,
845                    completed_tasks,
846                    incomplete_tasks: non_root_tasks.saturating_sub(completed_tasks),
847                    failed_or_blocked_tasks: count(&row, "failed_or_blocked_tasks"),
848                    mutation_reservations: count(&row, "mutation_reservations"),
849                    succeeded_mutations: count(&row, "succeeded_mutations"),
850                    failed_mutations: count(&row, "failed_mutations"),
851                    never_dispatched_mutations: count(&row, "never_dispatched_mutations"),
852                    ambiguous_or_reserved_mutations: count(&row, "ambiguous_mutations"),
853                },
854                now,
855            );
856            super::notifications::enqueue_mandate_run_notification_on_connection(
857                &mut *connection,
858                &notice,
859            )
860            .await?;
861        }
862    }
863    sqlx::query(
864        "UPDATE task_attempts
865         SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
866         WHERE goal_run_id IN (
867             SELECT id FROM goal_runs
868             WHERE goal_id = ? AND trigger_type = 'mandate'
869               AND status IN ('pending', 'running', 'blocked')
870         ) AND status IN ('claimed', 'running')",
871    )
872    .bind(now)
873    .bind(goal_id)
874    .execute(&mut *connection)
875    .await?;
876    sqlx::query(
877        "UPDATE tasks
878         SET status = 'cancelled', current_attempt_id = NULL,
879             completed_at = COALESCE(completed_at, ?), updated_at = ?, version = version + 1
880         WHERE goal_run_id IN (
881             SELECT id FROM goal_runs
882             WHERE goal_id = ? AND trigger_type = 'mandate'
883               AND status IN ('pending', 'running', 'blocked')
884         ) AND status IN ('pending', 'claimed', 'running', 'blocked')",
885    )
886    .bind(now)
887    .bind(now)
888    .bind(goal_id)
889    .execute(&mut *connection)
890    .await?;
891    let (intention_from, intention_to) =
892        intention_transition(IntentionStatus::Committed, IntentionStatus::Suspended)?;
893    sqlx::query(
894        "UPDATE intentions
895         SET status = ?, completed_at = COALESCE(completed_at, ?), updated_at = ?
896         WHERE goal_run_id IN (
897             SELECT id FROM goal_runs
898             WHERE goal_id = ? AND trigger_type = 'mandate'
899               AND status IN ('pending', 'running', 'blocked')
900         ) AND status = ?",
901    )
902    .bind(intention_to)
903    .bind(now)
904    .bind(now)
905    .bind(goal_id)
906    .bind(intention_from)
907    .execute(&mut *connection)
908    .await?;
909    sqlx::query(
910        "UPDATE goal_runs
911         SET status = 'cancelled',
912             outcome_summary = CASE WHEN EXISTS (
913                 SELECT 1 FROM mandate_mutation_attempts ma
914                 WHERE ma.goal_run_id = goal_runs.id AND ma.status = 'ambiguous'
915             ) THEN 'mandate_reconciliation_required:lifecycle_invalidated_after_dispatch_claim'
916             ELSE 'Mandate lifecycle changed; a fresh decision cycle is required.' END,
917             completed_at = COALESCE(completed_at, ?), updated_at = ?
918         WHERE goal_id = ? AND trigger_type = 'mandate'
919           AND status IN ('pending', 'running', 'blocked')",
920    )
921    .bind(now)
922    .bind(now)
923    .bind(goal_id)
924    .execute(&mut *connection)
925    .await?;
926    Ok(claimed_unresolved)
927}
928
929async fn mandate_run_proof_counts_on_connection(
930    connection: &mut sqlx::SqliteConnection,
931    goal_run_id: &str,
932    root_task_id: Option<&str>,
933) -> anyhow::Result<MandateRunProofCounts> {
934    let task_counts = sqlx::query(
935        "SELECT COUNT(*) AS total,
936                COALESCE(SUM(CASE WHEN status = 'completed'
937                    AND COALESCE(NULLIF(trim(error), ''), '') = ''
938                    AND COALESCE(NULLIF(trim(blocker), ''), '') = ''
939                    THEN 1 ELSE 0 END), 0) AS completed,
940                COALESCE(SUM(CASE WHEN status IN ('failed', 'blocked', 'interrupted')
941                    OR COALESCE(NULLIF(trim(error), ''), '') != ''
942                    OR COALESCE(NULLIF(trim(blocker), ''), '') != ''
943                    THEN 1 ELSE 0 END), 0) AS failed_or_blocked
944         FROM tasks
945         WHERE goal_run_id = ? AND id != COALESCE(?, '')",
946    )
947    .bind(goal_run_id)
948    .bind(root_task_id)
949    .fetch_one(&mut *connection)
950    .await?;
951    let non_root_tasks: i64 = task_counts.get("total");
952    let completed_tasks: i64 = task_counts.get("completed");
953    let failed_or_blocked_tasks: i64 = task_counts.get("failed_or_blocked");
954
955    let mutation_counts = sqlx::query(
956        "SELECT COUNT(*) AS total,
957                COALESCE(SUM(CASE WHEN status = 'succeeded' THEN 1 ELSE 0 END), 0)
958                    AS succeeded,
959                COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) AS failed,
960                COALESCE(SUM(CASE WHEN status = 'never_dispatched' THEN 1 ELSE 0 END), 0)
961                    AS never_dispatched,
962                COALESCE(SUM(CASE WHEN status IN ('reserved', 'ambiguous') THEN 1 ELSE 0 END), 0)
963                    AS ambiguous_or_reserved
964         FROM mandate_mutation_attempts
965         WHERE goal_run_id = ?",
966    )
967    .bind(goal_run_id)
968    .fetch_one(&mut *connection)
969    .await?;
970    let mutation_total: i64 = mutation_counts.get("total");
971    let mutation_succeeded: i64 = mutation_counts.get("succeeded");
972    let mutation_failed: i64 = mutation_counts.get("failed");
973    let mutation_never_dispatched: i64 = mutation_counts.get("never_dispatched");
974    let mutation_ambiguous: i64 = mutation_counts.get("ambiguous_or_reserved");
975    let count = |value: i64| u32::try_from(value.max(0)).unwrap_or(u32::MAX);
976
977    Ok(MandateRunProofCounts {
978        non_root_tasks: count(non_root_tasks),
979        completed_tasks: count(completed_tasks),
980        incomplete_tasks: count(non_root_tasks.saturating_sub(completed_tasks)),
981        failed_or_blocked_tasks: count(failed_or_blocked_tasks),
982        mutation_reservations: count(mutation_total),
983        succeeded_mutations: count(mutation_succeeded),
984        failed_mutations: count(mutation_failed),
985        never_dispatched_mutations: count(mutation_never_dispatched),
986        ambiguous_or_reserved_mutations: count(mutation_ambiguous),
987    })
988}
989
990#[allow(clippy::too_many_arguments)]
991async fn retry_orphaned_mandate_review_without_dispatch(
992    connection: &mut sqlx::SqliteConnection,
993    reason: MandateFinalizationRejectReason,
994    mandate_id: &str,
995    goal_id: &str,
996    mandate_version: i64,
997    owner_session_id: &str,
998    goal_run_id: &str,
999    min_review_secs: i64,
1000    max_review_secs: i64,
1001    review_failures: i32,
1002    now: &str,
1003) -> anyhow::Result<()> {
1004    let (intention_from, intention_to) =
1005        intention_transition(IntentionStatus::Committed, IntentionStatus::Suspended)?;
1006    sqlx::query(
1007        "UPDATE intentions
1008         SET status = ?, completed_at = COALESCE(completed_at, ?), updated_at = ?
1009         WHERE goal_run_id = ? AND status = ?",
1010    )
1011    .bind(intention_to)
1012    .bind(now)
1013    .bind(now)
1014    .bind(goal_run_id)
1015    .bind(intention_from)
1016    .execute(&mut *connection)
1017    .await?;
1018    sqlx::query(
1019        "UPDATE task_attempts
1020         SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
1021         WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
1022    )
1023    .bind(now)
1024    .bind(goal_run_id)
1025    .execute(&mut *connection)
1026    .await?;
1027    sqlx::query(
1028        "UPDATE tasks
1029         SET status = 'cancelled', current_attempt_id = NULL,
1030             completed_at = COALESCE(completed_at, ?), updated_at = ?, version = version + 1
1031         WHERE goal_run_id = ?
1032           AND status IN ('pending', 'claimed', 'running', 'blocked')",
1033    )
1034    .bind(now)
1035    .bind(now)
1036    .bind(goal_run_id)
1037    .execute(&mut *connection)
1038    .await?;
1039    let run_updated = sqlx::query(
1040        "UPDATE goal_runs
1041         SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
1042         WHERE id = ? AND status IN ('pending', 'running', 'blocked')
1043           AND trigger_type = 'mandate'",
1044    )
1045    .bind(format!("mandate_review_failed:{}", reason.as_str()))
1046    .bind(now)
1047    .bind(now)
1048    .bind(goal_run_id)
1049    .execute(&mut *connection)
1050    .await?;
1051
1052    let finalized_at = chrono::DateTime::parse_from_rfc3339(now)
1053        .map_err(|error| anyhow::anyhow!("invalid orphaned review timestamp: {error}"))?
1054        .with_timezone(&chrono::Utc);
1055    let next_review_failures = review_failures.saturating_add(1);
1056    let backoff_shift = u32::try_from(next_review_failures.saturating_sub(1))
1057        .unwrap_or(0)
1058        .min(6);
1059    let retry_delay_secs = min_review_secs
1060        .saturating_mul(1_i64 << backoff_shift)
1061        .min(max_review_secs);
1062    let retry_at = (finalized_at + chrono::Duration::seconds(retry_delay_secs)).to_rfc3339();
1063    let mandate_updated = sqlx::query(
1064        "UPDATE mandates
1065         SET next_review_at = ?, review_lease_token = NULL,
1066             review_lease_expires_at = NULL, updated_at = ?
1067         WHERE id = ? AND goal_id = ? AND version = ? AND status = 'active'",
1068    )
1069    .bind(&retry_at)
1070    .bind(now)
1071    .bind(mandate_id)
1072    .bind(goal_id)
1073    .bind(mandate_version)
1074    .execute(&mut *connection)
1075    .await?;
1076    anyhow::ensure!(
1077        run_updated.rows_affected() == 1 && mandate_updated.rows_affected() == 1,
1078        "orphaned mandate review changed during no-dispatch recovery"
1079    );
1080    update_controller_status(connection, goal_id, MandateStatus::Active, now).await?;
1081    sqlx::query("UPDATE goals SET dispatch_failures = ?, updated_at = ? WHERE id = ?")
1082        .bind(next_review_failures)
1083        .bind(now)
1084        .bind(goal_id)
1085        .execute(&mut *connection)
1086        .await?;
1087
1088    if crate::mandates::review_failure_is_notified(i64::from(next_review_failures)) {
1089        let notice = crate::traits::MandateRunNotification::new(
1090            mandate_id,
1091            mandate_version,
1092            goal_id,
1093            goal_run_id,
1094            owner_session_id,
1095            crate::traits::MandateRunNotificationKind::ReviewFailed { reason },
1096            MandateRunProofCounts::default(),
1097            now,
1098        );
1099        super::notifications::enqueue_mandate_run_notification_on_connection(
1100            &mut *connection,
1101            &notice,
1102        )
1103        .await?;
1104    }
1105    Ok(())
1106}
1107
1108/// The gate that refused a run's most recent worker mutation before
1109/// dispatch, from the worker's typed receipt. That worker is recorded as
1110/// blocked in the same transaction: a refused mutation is not completed work,
1111/// whatever the worker reported.
1112async fn block_worker_refused_before_dispatch(
1113    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
1114    goal_run_id: &str,
1115    root_task_id: &str,
1116    finalized_at: &str,
1117) -> anyhow::Result<Option<MandateDispatchGate>> {
1118    let refusal = sqlx::query(
1119        "SELECT t.id AS task_id,
1120                json_extract(e.data, '$.receipt.access_denial.reason_code') AS reason_code
1121         FROM tasks t JOIN events e ON e.task_id = t.id
1122         WHERE t.goal_run_id = ? AND t.id != ? AND e.event_type = 'tool_result'
1123           AND json_extract(e.data, '$.receipt.invocation_stage') = 'rejected_before_dispatch'
1124           AND json_extract(e.data, '$.receipt.semantics.effect') = 'Mutation'
1125         ORDER BY e.id DESC LIMIT 1",
1126    )
1127    .bind(goal_run_id)
1128    .bind(root_task_id)
1129    .fetch_optional(&mut **tx)
1130    .await?;
1131    let Some(refusal) = refusal else {
1132        return Ok(None);
1133    };
1134    let task_id: String = refusal.get("task_id");
1135    let reason_code: Option<String> = refusal.get("reason_code");
1136    let gate = MandateDispatchGate::from_reason_code(reason_code.as_deref().unwrap_or_default());
1137    sqlx::query(
1138        "UPDATE tasks
1139         SET status = 'blocked', blocker = ?, updated_at = ?, version = version + 1
1140         WHERE id = ? AND status = 'completed'",
1141    )
1142    .bind(format!("Refused before dispatch by {}", gate.owner_label()))
1143    .bind(finalized_at)
1144    .bind(&task_id)
1145    .execute(&mut **tx)
1146    .await?;
1147    Ok(Some(gate))
1148}
1149
1150/// How long after its commit an interrupted ACT may still be resumed. Past
1151/// this (or past the decision's own `reconsider_at`), the evidence it was
1152/// decided on is stale and the next review decides afresh instead.
1153const INTERRUPTED_ACT_RESUME_WINDOW_SECS: i64 = 15 * 60;
1154
1155/// Resume a committed ACT whose run was orphaned before any action task,
1156/// mutation reservation or dispatch claim existed: the same run's root is
1157/// reopened (pending, no attempt) so the ordinary dispatcher starts a fresh
1158/// task lead under the same decision. It creates the action task through the
1159/// fenced `create_mandate_task_from_attempt` path, so authority, quota,
1160/// spacing and duplicate checks all run again at dispatch. The root's
1161/// `retry_count` marks the one resumption: a second interruption falls back
1162/// to `act_interrupted_before_dispatch`. Returns whether the run was resumed.
1163async fn resume_interrupted_act(
1164    connection: &mut sqlx::SqliteConnection,
1165    mandate_id: &str,
1166    mandate_version: i64,
1167    goal_run_id: &str,
1168    root_task_id: &str,
1169    now: &str,
1170) -> anyhow::Result<bool> {
1171    let intention = sqlx::query(
1172        "SELECT i.description
1173         FROM mandate_decision_cycles dc
1174         JOIN intentions i ON i.decision_cycle_id = dc.id AND i.goal_run_id = dc.goal_run_id
1175         JOIN mandates m ON m.id = dc.mandate_id
1176         WHERE dc.goal_run_id = ? AND dc.mandate_id = ? AND dc.outcome = 'act'
1177           AND dc.origin = 'deliberator'
1178           AND dc.mandate_version = ? AND m.version = ?
1179           AND m.status = 'active' AND m.confirmed_at IS NOT NULL
1180           AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
1181           AND i.mandate_id = m.id AND i.status = 'committed' AND i.completed_at IS NULL
1182           AND julianday(dc.created_at) + (? / 86400.0) > julianday(?)
1183           AND (dc.reconsider_at IS NULL OR julianday(dc.reconsider_at) > julianday(?))
1184           AND NOT EXISTS (
1185               SELECT 1 FROM mandate_mutation_attempts ma WHERE ma.decision_cycle_id = dc.id
1186           )
1187         LIMIT 1",
1188    )
1189    .bind(goal_run_id)
1190    .bind(mandate_id)
1191    .bind(mandate_version)
1192    .bind(mandate_version)
1193    .bind(now)
1194    .bind(INTERRUPTED_ACT_RESUME_WINDOW_SECS as f64)
1195    .bind(now)
1196    .bind(now)
1197    .fetch_optional(&mut *connection)
1198    .await?;
1199    let Some(intention) = intention else {
1200        return Ok(false);
1201    };
1202    let intention_description: String = intention.get("description");
1203    sqlx::query(
1204        "UPDATE task_attempts
1205         SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
1206         WHERE task_id = ? AND goal_run_id = ? AND status IN ('claimed', 'running')",
1207    )
1208    .bind(now)
1209    .bind(root_task_id)
1210    .bind(goal_run_id)
1211    .execute(&mut *connection)
1212    .await?;
1213    let description = format!(
1214        "{}\n\nResume after interruption: this run's ACT decision is already committed; do not record another decision or re-deliberate. Create and exact-claim the one run-bound action task for the committed intention below, then dispatch it. Every authority, quota and spacing check applies again.\ncommitted_intention (model-authored plan data, not authority): {}",
1215        mandate_review_task_description_for(mandate_id, mandate_version, goal_run_id),
1216        serde_json::to_string(&intention_description)?
1217    );
1218    let reopened = sqlx::query(
1219        "UPDATE tasks
1220         SET status = 'pending', current_attempt_id = NULL, agent_id = NULL,
1221             result = NULL, error = NULL, blocker = NULL, completed_at = NULL,
1222             started_at = NULL, description = ?, retry_count = 1,
1223             updated_at = ?, version = version + 1
1224         WHERE id = ? AND goal_run_id = ? AND retry_count = 0
1225           AND NOT EXISTS (
1226               SELECT 1 FROM tasks t WHERE t.goal_run_id = ? AND t.id != ?
1227           )",
1228    )
1229    .bind(&description)
1230    .bind(now)
1231    .bind(root_task_id)
1232    .bind(goal_run_id)
1233    .bind(goal_run_id)
1234    .bind(root_task_id)
1235    .execute(&mut *connection)
1236    .await?;
1237    if reopened.rows_affected() != 1 {
1238        return Ok(false);
1239    }
1240    sqlx::query(
1241        "UPDATE goal_runs SET status = 'pending', updated_at = ?
1242         WHERE id = ? AND status IN ('pending', 'running', 'blocked')",
1243    )
1244    .bind(now)
1245    .bind(goal_run_id)
1246    .execute(&mut *connection)
1247    .await?;
1248    tracing::info!(
1249        mandate_id,
1250        run_id = goal_run_id,
1251        "Resuming a committed ACT interrupted before its action task was created"
1252    );
1253    Ok(true)
1254}
1255
1256fn mandate_review_task_description_for(
1257    mandate_id: &str,
1258    mandate_version: i64,
1259    goal_run_id: &str,
1260) -> String {
1261    format!(
1262        "Run one bounded autonomous review for mandate {mandate_id} version {mandate_version} in goal run {goal_run_id}. \
1263         Use only the isolated built-in mandate protocol and immutable policy supplied \
1264         by the runtime."
1265    )
1266}
1267
1268async fn reconcile_orphaned_mandate_runs(
1269    connection: &mut sqlx::SqliteConnection,
1270    now: &str,
1271) -> anyhow::Result<()> {
1272    let rows = sqlx::query(
1273        "SELECT m.id AS mandate_id, m.goal_id, m.version, g.session_id,
1274                g.dispatch_failures AS review_failures,
1275                m.min_review_secs, m.max_review_secs,
1276                gr.id AS goal_run_id, gr.root_task_id,
1277                (SELECT dc.outcome FROM mandate_decision_cycles dc
1278                 WHERE dc.mandate_id = m.id AND dc.goal_run_id = gr.id)
1279                    AS decision_outcome,
1280                (SELECT COUNT(*) FROM mandate_mutation_attempts ma
1281                 WHERE ma.mandate_id = m.id AND ma.goal_run_id = gr.id)
1282                    AS mutation_reservation_count,
1283                (SELECT COUNT(*) FROM mandate_mutation_attempts ma
1284                 WHERE ma.mandate_id = m.id AND ma.goal_run_id = gr.id
1285                   AND ma.dispatch_claimed_at IS NOT NULL)
1286                    AS dispatch_claim_count,
1287                (SELECT COUNT(*) FROM tasks t
1288                 WHERE t.goal_run_id = gr.id AND t.id != gr.root_task_id)
1289                    AS action_task_count,
1290                root.retry_count AS root_retry_count
1291         FROM mandates m
1292         JOIN goals g ON g.id = m.goal_id
1293         JOIN goal_runs gr ON gr.goal_id = m.goal_id AND gr.trigger_type = 'mandate'
1294         JOIN tasks root ON root.id = gr.root_task_id
1295         WHERE m.status = 'active' AND m.confirmed_at IS NOT NULL
1296           AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
1297           AND g.status = 'active'
1298           AND gr.status IN ('pending', 'running', 'blocked')
1299           AND (
1300               root.status IN ('claimed', 'running', 'blocked', 'interrupted', 'failed', 'abandoned')
1301               OR (
1302                   root.status = 'completed'
1303                   AND root.completed_at IS NOT NULL
1304                   AND julianday(root.completed_at) <= julianday(?) - (60.0 / 86400.0)
1305               )
1306           )
1307           AND NOT EXISTS (
1308               SELECT 1 FROM task_attempts a
1309               WHERE a.id = root.current_attempt_id
1310                 AND a.task_id = root.id AND a.goal_run_id = gr.id
1311                 AND a.status IN ('claimed', 'running')
1312                 AND datetime(a.lease_expires_at) > datetime('now')
1313           )",
1314    )
1315    .bind(now)
1316    .bind(now)
1317    .fetch_all(&mut *connection)
1318    .await?;
1319
1320    for row in rows {
1321        let mandate_id: String = row.get("mandate_id");
1322        let goal_id: String = row.get("goal_id");
1323        let version: i64 = row.get("version");
1324        let session_id: String = row.get("session_id");
1325        let review_failures: i32 = row.get("review_failures");
1326        let min_review_secs: i64 = row.get("min_review_secs");
1327        let max_review_secs: i64 = row.get("max_review_secs");
1328        let goal_run_id: String = row.get("goal_run_id");
1329        let root_task_id: Option<String> = row.get("root_task_id");
1330        let decision_outcome: Option<String> = row.get("decision_outcome");
1331        let mutation_reservation_count: i64 = row.get("mutation_reservation_count");
1332        let dispatch_claim_count: i64 = row.get("dispatch_claim_count");
1333        let action_task_count: i64 = row.get("action_task_count");
1334        let root_retry_count: i64 = row.get("root_retry_count");
1335
1336        // A committed ACT interrupted before its action task existed is
1337        // resumed once, by reopening the same run's root for a fresh task
1338        // lead, instead of being dropped. Every dispatch gate (fenced task
1339        // creation, quota, spacing, authority, duplicate checks) runs again
1340        // when the resumed lead acts; nothing is authorized here.
1341        if decision_outcome.as_deref() == Some("act")
1342            && mutation_reservation_count == 0
1343            && dispatch_claim_count == 0
1344            && action_task_count == 0
1345            && root_retry_count == 0
1346            && let Some(root_task_id) = root_task_id.as_deref()
1347            && resume_interrupted_act(
1348                connection,
1349                &mandate_id,
1350                version,
1351                &goal_run_id,
1352                root_task_id,
1353                now,
1354            )
1355            .await?
1356        {
1357            continue;
1358        }
1359
1360        // A mandate mutation can only cross the external I/O boundary after
1361        // a mutation reservation and a one-use dispatch claim exist. Without
1362        // either, there is no external effect to reconcile even if an ACT
1363        // was recorded (e.g. its executor blocked before reserving), and
1364        // pausing the mandate would turn a recoverable review interruption
1365        // into a false safety incident. The committed intention is suspended
1366        // and the next review decides afresh. A recorded ASK or STOP is an
1367        // owner-facing outcome, so it still goes to reconciliation rather
1368        // than being silently re-deliberated.
1369        let retry_reason = match decision_outcome.as_deref() {
1370            None => Some(MandateFinalizationRejectReason::DecisionMissing),
1371            Some("act") => Some(MandateFinalizationRejectReason::ActInterruptedBeforeDispatch),
1372            Some(_) => None,
1373        };
1374        if let (Some(reason), 0, 0) = (
1375            retry_reason,
1376            mutation_reservation_count,
1377            dispatch_claim_count,
1378        ) {
1379            retry_orphaned_mandate_review_without_dispatch(
1380                connection,
1381                reason,
1382                &mandate_id,
1383                &goal_id,
1384                version,
1385                &session_id,
1386                &goal_run_id,
1387                min_review_secs,
1388                max_review_secs,
1389                review_failures,
1390                now,
1391            )
1392            .await?;
1393            continue;
1394        }
1395
1396        let mut suspension = MandateSuspension::new(
1397            MandateSuspensionKind::ExecutionLeaseLost,
1398            Some("orphaned_mandate_run".to_string()),
1399        );
1400        suspension.goal_run_id = Some(goal_run_id.clone());
1401        let transitioned = sqlx::query(
1402            "UPDATE mandates
1403             SET status = 'awaiting_input', review_lease_token = NULL,
1404                 review_lease_expires_at = NULL, suspension_json = ?,
1405                 version = version + 1, updated_at = ?
1406             WHERE id = ? AND goal_id = ? AND status = 'active' AND version = ?",
1407        )
1408        .bind(serde_json::to_string(&suspension)?)
1409        .bind(now)
1410        .bind(&mandate_id)
1411        .bind(&goal_id)
1412        .bind(version)
1413        .execute(&mut *connection)
1414        .await?;
1415        if transitioned.rows_affected() != 1 {
1416            continue;
1417        }
1418
1419        let claimed_unresolved = invalidate_open_mandate_runs(connection, &goal_id, now).await?;
1420        update_controller_status(connection, &goal_id, MandateStatus::AwaitingInput, now).await?;
1421        if claimed_unresolved == 0 {
1422            let counts = mandate_run_proof_counts_on_connection(
1423                connection,
1424                &goal_run_id,
1425                root_task_id.as_deref(),
1426            )
1427            .await?;
1428            let notice = crate::traits::MandateRunNotification::new(
1429                &mandate_id,
1430                version + 1,
1431                &goal_id,
1432                &goal_run_id,
1433                &session_id,
1434                crate::traits::MandateRunNotificationKind::ExecutionLeaseLost,
1435                counts,
1436                now,
1437            );
1438            super::notifications::enqueue_mandate_run_notification_on_connection(
1439                &mut *connection,
1440                &notice,
1441            )
1442            .await?;
1443        }
1444    }
1445    Ok(())
1446}
1447
1448async fn resume_unanswered_agent_questions(
1449    connection: &mut sqlx::SqliteConnection,
1450    now: &str,
1451) -> anyhow::Result<()> {
1452    let rows = sqlx::query(
1453        "SELECT m.id, m.goal_id, m.version, m.created_by_session, m.objective, m.name,
1454                d.id AS decision_id, d.question
1455         FROM mandates m
1456         LEFT JOIN mandate_decision_cycles d
1457           ON d.id = json_extract(m.suspension_json, '$.decision_cycle_id')
1458         WHERE m.status = 'awaiting_input'
1459           AND m.confirmed_at IS NOT NULL
1460           AND json_extract(m.suspension_json, '$.kind') = 'awaiting_answer'
1461           AND julianday(m.next_review_at) <= julianday(?)
1462           AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))",
1463    )
1464    .bind(now)
1465    .bind(now)
1466    .fetch_all(&mut *connection)
1467    .await?;
1468
1469    for row in rows {
1470        let mandate_id: String = row.get("id");
1471        let goal_id: String = row.get("goal_id");
1472        let version: i64 = row.get("version");
1473        let owner_session: String = row.get("created_by_session");
1474        let decision_id: Option<String> = row.get("decision_id");
1475        let question: Option<String> = row.get("question");
1476        let objective: String = row.get("objective");
1477        let name: Option<String> = row.get("name");
1478        // Authority is unchanged, so the policy version is kept: a late
1479        // owner answer still applies to the same policy.
1480        let resumed = sqlx::query(
1481            "UPDATE mandates
1482             SET status = 'active', suspension_json = NULL,
1483                 review_lease_token = NULL, review_lease_expires_at = NULL, updated_at = ?
1484             WHERE id = ? AND version = ? AND status = 'awaiting_input'
1485               AND json_extract(suspension_json, '$.kind') = 'awaiting_answer'",
1486        )
1487        .bind(now)
1488        .bind(&mandate_id)
1489        .bind(version)
1490        .execute(&mut *connection)
1491        .await?;
1492        if resumed.rows_affected() != 1 {
1493            continue;
1494        }
1495        update_controller_status(connection, &goal_id, MandateStatus::Active, now).await?;
1496        let label = crate::traits::mandate_named_label(name.as_deref(), Some(&objective));
1497        let message = match question
1498            .as_deref()
1499            .and_then(crate::traits::owner_question_excerpt)
1500        {
1501            Some(question) => format!(
1502                "{label} is continuing on its own because its question went unanswered. Its limits are unchanged; nothing new was allowed.\n\nIt had asked: \"{question}\"\n\nNo reply is needed. If you still want to answer, reply here."
1503            ),
1504            None => format!(
1505                "{label} is continuing on its own because its question went unanswered. Its limits are unchanged; nothing new was allowed."
1506            ),
1507        };
1508        sqlx::query(
1509            "INSERT OR IGNORE INTO notification_queue
1510                (id, goal_id, session_id, notification_type, priority, message,
1511                 created_at, delivered_at, attempts, expires_at, task_id, action_token)
1512             VALUES (?, ?, ?, 'mandate_ask_timeout', 'critical', ?, ?, NULL, 0, NULL, NULL, NULL)",
1513        )
1514        .bind(format!(
1515            "mandate-ask-timeout:{}",
1516            decision_id.unwrap_or_else(|| format!("{mandate_id}:{version}"))
1517        ))
1518        .bind(&goal_id)
1519        .bind(&owner_session)
1520        .bind(message)
1521        .bind(now)
1522        .execute(&mut *connection)
1523        .await?;
1524    }
1525    Ok(())
1526}
1527
1528#[async_trait]
1529impl<S: WorkDatabase> MandateStore for S {
1530    async fn create_mandate_controller(
1531        &self,
1532        goal: &Goal,
1533        mandate: &Mandate,
1534    ) -> anyhow::Result<()> {
1535        validate_new_mandate(mandate)?;
1536        anyhow::ensure!(
1537            goal.id == mandate.goal_id,
1538            "mandate goal_id does not match controller"
1539        );
1540        anyhow::ensure!(
1541            goal.domain == "orchestration" && goal.goal_type == "continuous",
1542            "mandates require a continuous orchestration goal"
1543        );
1544        anyhow::ensure!(
1545            matches!(
1546                (
1547                    goal.status.as_str(),
1548                    mandate.status,
1549                    mandate.confirmed_at.is_some()
1550                ),
1551                ("active", MandateStatus::Active, true)
1552                    | ("pending_confirmation", MandateStatus::Paused, false)
1553                    | ("paused", MandateStatus::Paused, true)
1554            ),
1555            "a new mandate controller must carry confirmation exactly when its lifecycle requires it"
1556        );
1557        anyhow::ensure!(
1558            goal.session_id == mandate.created_by_session,
1559            "controller session must match the mandate owner session"
1560        );
1561
1562        let progress_notes_json = goal
1563            .progress_notes
1564            .as_ref()
1565            .map(serde_json::to_string)
1566            .transpose()?;
1567        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1568        validate_source_goal(
1569            &mut tx,
1570            mandate.source_goal_id.as_deref(),
1571            &mandate.created_by_session,
1572        )
1573        .await?;
1574
1575        let active_evergreen_count = sqlx::query_scalar::<_, i64>(
1576            "SELECT COUNT(*) FROM goals
1577             WHERE domain = 'orchestration' AND goal_type = 'continuous' AND status = 'active'",
1578        )
1579        .fetch_one(&mut *tx)
1580        .await?;
1581        anyhow::ensure!(
1582            active_evergreen_count < 10,
1583            "Cannot create mandate controller: hard cap of 10 active evergreen goals reached"
1584        );
1585
1586        sqlx::query(
1587            "INSERT INTO goals (
1588                id, description, domain, goal_type, status, priority, conditions, context, resources,
1589                budget_per_check, budget_daily, tokens_used_today, tokens_used_day, last_useful_action,
1590                created_at, updated_at, completed_at, parent_goal_id, session_id, notified_at,
1591                notification_attempts, dispatch_failures, progress_notes, source_episode_id,
1592                legacy_int_id, project_id
1593             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
1594                       COALESCE((SELECT project_id FROM session_work_projects WHERE session_id = ?), 'default'))",
1595        )
1596        .bind(&goal.id)
1597        .bind(&goal.description)
1598        .bind(&goal.domain)
1599        .bind(&goal.goal_type)
1600        .bind(&goal.status)
1601        .bind(&goal.priority)
1602        .bind(&goal.conditions)
1603        .bind(&goal.context)
1604        .bind(&goal.resources)
1605        .bind(goal.budget_per_check)
1606        .bind(goal.budget_daily)
1607        .bind(goal.tokens_used_today)
1608        .bind(&goal.tokens_used_day)
1609        .bind(&goal.last_useful_action)
1610        .bind(&goal.created_at)
1611        .bind(&goal.updated_at)
1612        .bind(&goal.completed_at)
1613        .bind(&goal.parent_goal_id)
1614        .bind(&goal.session_id)
1615        .bind(&goal.notified_at)
1616        .bind(goal.notification_attempts)
1617        .bind(goal.dispatch_failures)
1618        .bind(&progress_notes_json)
1619        .bind(goal.source_episode_id)
1620        .bind(goal.legacy_int_id)
1621        .bind(&goal.session_id)
1622        .execute(&mut *tx)
1623        .await?;
1624
1625        sqlx::query(
1626            "INSERT INTO work_channel_links
1627                (goal_id, channel_session_id, created_at, updated_at)
1628             VALUES (?, ?, datetime('now'), datetime('now'))",
1629        )
1630        .bind(&goal.id)
1631        .bind(&goal.session_id)
1632        .execute(&mut *tx)
1633        .await?;
1634
1635        insert_mandate_row(&mut tx, mandate).await?;
1636        sqlx::query(
1637            "INSERT INTO mandate_principal_sessions
1638                (principal_id, session_id, linked_at, linked_by_session)
1639             VALUES (?, ?, ?, ?)
1640             ON CONFLICT(principal_id, session_id) DO NOTHING",
1641        )
1642        .bind(&mandate.owner_principal_id)
1643        .bind(&mandate.created_by_session)
1644        .bind(&mandate.created_at)
1645        .bind(&mandate.created_by_session)
1646        .execute(&mut *tx)
1647        .await?;
1648        tx.commit().await?;
1649        Ok(())
1650    }
1651
1652    async fn get_mandate(&self, id: &str) -> anyhow::Result<Option<Mandate>> {
1653        let query = format!("SELECT {MANDATE_COLUMNS} FROM mandates WHERE id = ?");
1654        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
1655            .bind(id)
1656            .fetch_optional(self.work_pool())
1657            .await?;
1658        row.as_ref().map(mandate_from_row).transpose()
1659    }
1660
1661    async fn get_mandate_for_goal(&self, goal_id: &str) -> anyhow::Result<Option<Mandate>> {
1662        let query = format!("SELECT {MANDATE_COLUMNS} FROM mandates WHERE goal_id = ?");
1663        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
1664            .bind(goal_id)
1665            .fetch_optional(self.work_pool())
1666            .await?;
1667        row.as_ref().map(mandate_from_row).transpose()
1668    }
1669
1670    async fn list_mandates(
1671        &self,
1672        session_id: Option<&str>,
1673        include_terminal: bool,
1674    ) -> anyhow::Result<Vec<Mandate>> {
1675        let mut query = format!(
1676            "SELECT {} FROM mandates m JOIN goals g ON g.id = m.goal_id WHERE 1 = 1",
1677            qualified_columns("m", MANDATE_COLUMNS)
1678        );
1679        if session_id.is_some() {
1680            query.push_str(
1681                " AND (EXISTS (
1682                    SELECT 1 FROM mandate_principal_sessions ps
1683                    WHERE ps.principal_id = m.owner_principal_id AND ps.session_id = ?
1684                ) OR m.owner_principal_id = ?)",
1685            );
1686        }
1687        if !include_terminal {
1688            query.push_str(" AND m.status NOT IN ('completed', 'cancelled')");
1689        }
1690        query.push_str(" ORDER BY julianday(m.updated_at) DESC, m.id DESC");
1691        let rows = if let Some(session_id) = session_id {
1692            let stable_principal =
1693                aidaemon_events::session::stable_private_owner_principal_id(session_id)
1694                    .unwrap_or_default();
1695            sqlx::query(sqlx::AssertSqlSafe(&*query))
1696                .bind(session_id)
1697                .bind(stable_principal)
1698                .fetch_all(self.work_pool())
1699                .await?
1700        } else {
1701            sqlx::query(sqlx::AssertSqlSafe(&*query))
1702                .fetch_all(self.work_pool())
1703                .await?
1704        };
1705        rows.iter().map(mandate_from_row).collect()
1706    }
1707
1708    async fn is_mandate_session_authorized(
1709        &self,
1710        mandate_id: &str,
1711        session_id: &str,
1712    ) -> anyhow::Result<bool> {
1713        let stable_principal =
1714            aidaemon_events::session::stable_private_owner_principal_id(session_id)
1715                .unwrap_or_default();
1716        Ok(sqlx::query_scalar::<_, i64>(
1717            "SELECT EXISTS (
1718                SELECT 1 FROM mandates m
1719                WHERE m.id = ? AND (
1720                    EXISTS (
1721                        SELECT 1 FROM mandate_principal_sessions ps
1722                        WHERE ps.principal_id = m.owner_principal_id
1723                          AND ps.session_id = ?
1724                    ) OR m.owner_principal_id = ?
1725                )
1726            )",
1727        )
1728        .bind(mandate_id)
1729        .bind(session_id)
1730        .bind(stable_principal)
1731        .fetch_one(self.work_pool())
1732        .await?
1733            != 0)
1734    }
1735
1736    async fn record_mandate_objective_measurement(
1737        &self,
1738        measurement: &MandateObjectiveMeasurement,
1739    ) -> anyhow::Result<()> {
1740        measurement.validate().map_err(anyhow::Error::msg)?;
1741        let observed_at = chrono::DateTime::parse_from_rfc3339(&measurement.observed_at)?
1742            .with_timezone(&chrono::Utc);
1743        anyhow::ensure!(
1744            observed_at <= chrono::Utc::now() + chrono::Duration::minutes(5),
1745            "objective measurement cannot be future-dated"
1746        );
1747        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1748        let run_started_at = sqlx::query_scalar::<_, Option<String>>(
1749            "SELECT gr.started_at
1750             FROM mandates m
1751             JOIN goal_runs gr ON gr.goal_id = m.goal_id
1752             WHERE m.id = ? AND m.version = ? AND m.objective_control_json IS NOT NULL
1753               AND m.status = 'active' AND m.confirmed_at IS NOT NULL
1754               AND gr.id = ? AND gr.trigger_type = 'mandate' AND gr.status = 'running'",
1755        )
1756        .bind(&measurement.mandate_id)
1757        .bind(measurement.mandate_version)
1758        .bind(&measurement.goal_run_id)
1759        .fetch_optional(&mut *tx)
1760        .await?
1761        .flatten()
1762        .ok_or_else(|| {
1763            anyhow::anyhow!(
1764                "objective measurement is not bound to a current controlled mandate run"
1765            )
1766        })?;
1767        let run_started_at = chrono::DateTime::parse_from_rfc3339(&run_started_at)
1768            .or_else(|_| chrono::DateTime::parse_from_str(&run_started_at, "%Y-%m-%d %H:%M:%S%#z"))?
1769            .with_timezone(&chrono::Utc);
1770        anyhow::ensure!(
1771            observed_at >= run_started_at - chrono::Duration::minutes(5),
1772            "objective measurement predates the current mandate run"
1773        );
1774        validate_current_run_receipt_refs(
1775            &mut tx,
1776            &measurement.goal_run_id,
1777            &measurement.evidence_receipt_ids,
1778        )
1779        .await?;
1780        sqlx::query(
1781            "INSERT INTO mandate_objective_measurements
1782                (id, mandate_id, mandate_version, goal_run_id, value_micros,
1783                 confidence_bps, evidence_receipt_ids_json, observed_at, created_at)
1784             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
1785        )
1786        .bind(&measurement.id)
1787        .bind(&measurement.mandate_id)
1788        .bind(measurement.mandate_version)
1789        .bind(&measurement.goal_run_id)
1790        .bind(measurement.value_micros)
1791        .bind(i64::from(measurement.confidence_bps))
1792        .bind(serde_json::to_string(&measurement.evidence_receipt_ids)?)
1793        .bind(&measurement.observed_at)
1794        .bind(&measurement.created_at)
1795        .execute(&mut *tx)
1796        .await?;
1797        tx.commit().await?;
1798        Ok(())
1799    }
1800
1801    async fn list_mandate_objective_measurements(
1802        &self,
1803        mandate_id: &str,
1804        limit: i64,
1805    ) -> anyhow::Result<Vec<MandateObjectiveMeasurement>> {
1806        let rows = sqlx::query(
1807            "SELECT id, mandate_id, mandate_version, goal_run_id, value_micros,
1808                    confidence_bps, evidence_receipt_ids_json, observed_at, created_at
1809             FROM mandate_objective_measurements
1810             WHERE mandate_id = ?
1811             ORDER BY julianday(observed_at) DESC, id DESC LIMIT ?",
1812        )
1813        .bind(mandate_id)
1814        .bind(limit.clamp(1, 200))
1815        .fetch_all(self.work_pool())
1816        .await?;
1817        rows.iter().map(objective_measurement_from_row).collect()
1818    }
1819
1820    async fn update_mandate(&self, mandate: &Mandate) -> anyhow::Result<()> {
1821        validate_mandate(mandate)?;
1822        let expected_version = mandate
1823            .version
1824            .checked_sub(1)
1825            .filter(|version| *version > 0)
1826            .ok_or_else(|| anyhow::anyhow!("updated mandate version must be at least 2"))?;
1827        let now = chrono::Utc::now().to_rfc3339();
1828        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1829        let result = sqlx::query(
1830            "UPDATE mandates
1831             SET objective = ?, autonomy_mode = ?, authority_json = ?, strategy_json = ?, objective_control_json = ?, constraints_json = ?,
1832                 success_criteria_json = ?, stop_conditions_json = ?, min_review_secs = ?,
1833                 max_review_secs = ?, default_review_secs = ?, review_effort = ?, next_review_at = ?, expires_at = ?,
1834                 version = ?, review_lease_token = NULL, review_lease_expires_at = NULL,
1835                 updated_at = ?
1836             WHERE id = ? AND goal_id = ? AND version = ? AND status = ?",
1837        )
1838        .bind(&mandate.objective)
1839        .bind(mandate.autonomy_mode.as_str())
1840        .bind(serde_json::to_string(&mandate.authority)?)
1841        .bind(
1842            mandate
1843                .strategy
1844                .as_ref()
1845                .map(serde_json::to_string)
1846                .transpose()?,
1847        )
1848        .bind(
1849            mandate
1850                .objective_control
1851                .as_ref()
1852                .map(serde_json::to_string)
1853                .transpose()?,
1854        )
1855        .bind(serde_json::to_string(&mandate.constraints)?)
1856        .bind(serde_json::to_string(&mandate.success_criteria)?)
1857        .bind(serde_json::to_string(&mandate.stop_conditions)?)
1858        .bind(mandate.min_review_secs)
1859        .bind(mandate.max_review_secs)
1860        .bind(mandate.default_review_secs)
1861        .bind(&mandate.review_effort)
1862        .bind(&mandate.next_review_at)
1863        .bind(&mandate.expires_at)
1864        .bind(mandate.version)
1865        .bind(&now)
1866        .bind(&mandate.id)
1867        .bind(&mandate.goal_id)
1868        .bind(expected_version)
1869        .bind(mandate.status.as_str())
1870        .execute(&mut *tx)
1871        .await?;
1872        anyhow::ensure!(
1873            result.rows_affected() == 1,
1874            "mandate version conflict or mandate not found"
1875        );
1876        // Updating policy is an authority-epoch change. Invalidate every run,
1877        // task, and attempt created under the previous immutable version in
1878        // the same transaction as the version CAS.
1879        let claimed_unresolved =
1880            invalidate_open_mandate_runs(&mut tx, &mandate.goal_id, &now).await?;
1881        if claimed_unresolved > 0 {
1882            // A policy edit cannot make a claimed-but-unproved external effect
1883            // safe. Land the new policy, but pause its controller until the
1884            // owner reconciles the prior target; otherwise the updated active
1885            // mandate could immediately begin a duplicate cycle.
1886            let suspension = MandateSuspension::new(
1887                MandateSuspensionKind::AuthorityRevokedWithUnresolvedMutation,
1888                Some("policy_update_invalidated_dispatched_mutation".to_string()),
1889            );
1890            let paused = sqlx::query(
1891                "UPDATE mandates
1892                 SET status = 'awaiting_input', review_lease_token = NULL,
1893                     review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
1894                 WHERE id = ? AND version = ? AND status = 'active'",
1895            )
1896            .bind(serde_json::to_string(&suspension)?)
1897            .bind(&now)
1898            .bind(&mandate.id)
1899            .bind(mandate.version)
1900            .execute(&mut *tx)
1901            .await?;
1902            anyhow::ensure!(
1903                paused.rows_affected() == 1,
1904                "claimed mutation invalidation requires an awaiting-input mandate"
1905            );
1906            update_controller_status(
1907                &mut tx,
1908                &mandate.goal_id,
1909                MandateStatus::AwaitingInput,
1910                &now,
1911            )
1912            .await?;
1913        }
1914        tx.commit().await?;
1915        Ok(())
1916    }
1917
1918    async fn confirm_mandate(
1919        &self,
1920        mandate_id: &str,
1921        expected_version: i64,
1922        activation_duration_secs: Option<i64>,
1923    ) -> anyhow::Result<bool> {
1924        anyhow::ensure!(!mandate_id.trim().is_empty(), "mandate id is required");
1925        anyhow::ensure!(expected_version > 0, "mandate version must be positive");
1926        if let Some(duration_secs) = activation_duration_secs {
1927            anyhow::ensure!(
1928                duration_secs > 0,
1929                "mandate activation duration must be greater than zero"
1930            );
1931        }
1932        let activated_at = chrono::Utc::now();
1933        let expires_at = activation_duration_secs
1934            .map(|duration_secs| {
1935                activated_at
1936                    .checked_add_signed(chrono::Duration::seconds(duration_secs))
1937                    .ok_or_else(|| anyhow::anyhow!("mandate activation duration is too large"))
1938                    .map(|value| value.to_rfc3339())
1939            })
1940            .transpose()?;
1941        let now = activated_at.to_rfc3339();
1942        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1943        let goal_id = sqlx::query_scalar::<_, String>(
1944            "UPDATE mandates
1945             SET status = 'active', confirmed_at = ?, next_review_at = ?,
1946                 expires_at = COALESCE(?, expires_at),
1947                 review_lease_token = NULL, review_lease_expires_at = NULL, suspension_json = NULL,
1948                 version = version + 1, updated_at = ?
1949             WHERE id = ? AND version = ? AND status = 'paused' AND confirmed_at IS NULL
1950               AND EXISTS (
1951                   SELECT 1 FROM goals g
1952                   WHERE g.id = mandates.goal_id
1953                     AND g.domain = 'orchestration'
1954                     AND g.goal_type = 'continuous'
1955                     AND g.status = 'pending_confirmation'
1956               )
1957             RETURNING goal_id",
1958        )
1959        .bind(&now)
1960        .bind(&now)
1961        .bind(expires_at.as_deref())
1962        .bind(&now)
1963        .bind(mandate_id)
1964        .bind(expected_version)
1965        .fetch_optional(&mut *tx)
1966        .await?;
1967        let Some(goal_id) = goal_id else {
1968            tx.rollback().await?;
1969            return Ok(false);
1970        };
1971        update_controller_status(&mut tx, &goal_id, MandateStatus::Active, &now).await?;
1972        tx.commit().await?;
1973        Ok(true)
1974    }
1975
1976    async fn transition_mandate_status(
1977        &self,
1978        mandate_id: &str,
1979        from_status: MandateStatus,
1980        to_status: MandateStatus,
1981    ) -> anyhow::Result<bool> {
1982        anyhow::ensure!(
1983            from_status != to_status,
1984            "mandate status transition is a no-op"
1985        );
1986        // Keep lifecycle evolution explicit. Terminal mandates are immutable,
1987        // and only owner-mediated resume paths may leave paused/ASK states.
1988        // Invalid-but-known transitions report a failed CAS rather than an
1989        // error so callers cannot distinguish them from a concurrent change.
1990        if !from_status.can_transition_to(to_status) {
1991            return Ok(false);
1992        }
1993        let now = chrono::Utc::now().to_rfc3339();
1994        let suspension = match to_status {
1995            MandateStatus::Paused => Some(MandateSuspension::new(
1996                MandateSuspensionKind::OwnerPaused,
1997                None,
1998            )),
1999            MandateStatus::AwaitingInput => Some(MandateSuspension::new(
2000                MandateSuspensionKind::ReviewFailed,
2001                Some("lifecycle_transition".to_string()),
2002            )),
2003            MandateStatus::Active | MandateStatus::Completed | MandateStatus::Cancelled => None,
2004        };
2005        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2006        let goal_id = sqlx::query_scalar::<_, String>(
2007            "UPDATE mandates
2008             SET status = ?,
2009                 next_review_at = CASE WHEN ? = 'active' THEN ? ELSE next_review_at END,
2010                 review_lease_token = NULL, review_lease_expires_at = NULL,
2011                 suspension_json = ?,
2012                 version = version + 1, updated_at = ?
2013             WHERE id = ? AND status = ?
2014               AND (? != 'active' OR confirmed_at IS NOT NULL)
2015             RETURNING goal_id",
2016        )
2017        .bind(to_status.as_str())
2018        .bind(to_status.as_str())
2019        .bind(&now)
2020        .bind(suspension.as_ref().map(serde_json::to_string).transpose()?)
2021        .bind(&now)
2022        .bind(mandate_id)
2023        .bind(from_status.as_str())
2024        .bind(to_status.as_str())
2025        .fetch_optional(&mut *tx)
2026        .await?;
2027        let Some(goal_id) = goal_id else {
2028            tx.rollback().await?;
2029            return Ok(false);
2030        };
2031
2032        // A lifecycle transition is an authority-epoch change. Close every
2033        // open mandate run and its work in the same transaction so pausing and
2034        // later resuming cannot resurrect a pre-pause ACT or attempt.
2035        let claimed_unresolved = invalidate_open_mandate_runs(&mut tx, &goal_id, &now).await?;
2036        let effective_status = if to_status == MandateStatus::Paused && claimed_unresolved > 0 {
2037            let suspension = MandateSuspension::new(
2038                MandateSuspensionKind::ReconciliationRequired,
2039                Some("lifecycle_invalidated_after_dispatch_claim".to_string()),
2040            );
2041            let changed = sqlx::query(
2042                "UPDATE mandates SET status = 'awaiting_input', suspension_json = ?, updated_at = ?
2043                 WHERE id = ? AND status = 'paused'",
2044            )
2045            .bind(serde_json::to_string(&suspension)?)
2046            .bind(&now)
2047            .bind(mandate_id)
2048            .execute(&mut *tx)
2049            .await?;
2050            anyhow::ensure!(
2051                changed.rows_affected() == 1,
2052                "claimed mutation requires typed reconciliation"
2053            );
2054            MandateStatus::AwaitingInput
2055        } else {
2056            to_status
2057        };
2058        update_controller_status(&mut tx, &goal_id, effective_status, &now).await?;
2059        tx.commit().await?;
2060        Ok(true)
2061    }
2062
2063    async fn resume_mandate_with_context(
2064        &self,
2065        mandate_id: &str,
2066        from_status: MandateStatus,
2067        expected_version: i64,
2068        controller_context: Option<&str>,
2069    ) -> anyhow::Result<bool> {
2070        anyhow::ensure!(
2071            from_status == MandateStatus::Paused
2072                && from_status.can_transition_to(MandateStatus::Active),
2073            "ordinary resume is only valid for owner-paused mandates"
2074        );
2075        anyhow::ensure!(expected_version > 0, "mandate version must be positive");
2076        if let Some(context) = controller_context {
2077            anyhow::ensure!(
2078                context.chars().count() <= 64_000,
2079                "mandate controller context is too large"
2080            );
2081            serde_json::from_str::<serde_json::Value>(context)?;
2082        }
2083        let now = chrono::Utc::now().to_rfc3339();
2084        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2085        let goal_id = sqlx::query_scalar::<_, String>(
2086            "UPDATE mandates
2087             SET status = 'active', next_review_at = ?,
2088                 review_lease_token = NULL, review_lease_expires_at = NULL,
2089                 suspension_json = NULL,
2090                 version = version + 1, updated_at = ?
2091             WHERE id = ? AND status = ? AND version = ?
2092               AND confirmed_at IS NOT NULL
2093               AND json_extract(suspension_json, '$.kind') = 'owner_paused'
2094             RETURNING goal_id",
2095        )
2096        .bind(&now)
2097        .bind(&now)
2098        .bind(mandate_id)
2099        .bind(from_status.as_str())
2100        .bind(expected_version)
2101        .fetch_optional(&mut *tx)
2102        .await?;
2103        let Some(goal_id) = goal_id else {
2104            tx.rollback().await?;
2105            return Ok(false);
2106        };
2107        invalidate_open_mandate_runs(&mut tx, &goal_id, &now).await?;
2108        let controller = sqlx::query(
2109            "UPDATE goals
2110             SET status = 'active', context = COALESCE(?, context),
2111                 completed_at = NULL, dispatch_failures = 0, updated_at = ?
2112             WHERE id = ? AND domain = 'orchestration' AND goal_type = 'continuous'",
2113        )
2114        .bind(controller_context)
2115        .bind(&now)
2116        .bind(&goal_id)
2117        .execute(&mut *tx)
2118        .await?;
2119        anyhow::ensure!(
2120            controller.rows_affected() == 1,
2121            "mandate controller goal not found"
2122        );
2123        tx.commit().await?;
2124        Ok(true)
2125    }
2126
2127    async fn record_active_mandate_owner_guidance(
2128        &self,
2129        mandate_id: &str,
2130        expected_version: i64,
2131        owner_session: &str,
2132        controller_context: &str,
2133    ) -> anyhow::Result<bool> {
2134        anyhow::ensure!(
2135            controller_context.chars().count() <= 64_000,
2136            "mandate controller context is too large"
2137        );
2138        serde_json::from_str::<serde_json::Value>(controller_context)?;
2139        let now = chrono::Utc::now().to_rfc3339();
2140        let updated = sqlx::query(
2141            "UPDATE goals SET context = ?, updated_at = ?
2142             WHERE id = (
2143                 SELECT goal_id FROM mandates
2144                 WHERE id = ? AND version = ? AND status = 'active'
2145                   AND confirmed_at IS NOT NULL AND created_by_session = ?
2146             )
2147               AND domain = 'orchestration' AND goal_type = 'continuous'",
2148        )
2149        .bind(controller_context)
2150        .bind(&now)
2151        .bind(mandate_id)
2152        .bind(expected_version)
2153        .bind(owner_session)
2154        .execute(self.work_pool())
2155        .await?;
2156        Ok(updated.rows_affected() == 1)
2157    }
2158
2159    async fn create_mandate_review_run(
2160        &self,
2161        mandate_id: &str,
2162        review_lease_token: &str,
2163        goal_run_id: &str,
2164        root_task: &Task,
2165    ) -> anyhow::Result<GoalRun> {
2166        anyhow::ensure!(!mandate_id.trim().is_empty(), "mandate id is required");
2167        anyhow::ensure!(
2168            !review_lease_token.trim().is_empty(),
2169            "review lease token is required"
2170        );
2171        anyhow::ensure!(!goal_run_id.trim().is_empty(), "goal run id is required");
2172        anyhow::ensure!(!root_task.id.trim().is_empty(), "root task id is required");
2173        anyhow::ensure!(
2174            !root_task.description.trim().is_empty(),
2175            "root task description is required"
2176        );
2177        anyhow::ensure!(
2178            root_task.status == "pending"
2179                && root_task.started_at.is_none()
2180                && root_task.completed_at.is_none(),
2181            "a mandate review root task must start pending and unstarted"
2182        );
2183
2184        let now = chrono::Utc::now();
2185        let now_string = now.to_rfc3339();
2186        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2187        let row = sqlx::query(
2188            "SELECT m.goal_id, g.project_id
2189             FROM mandates m
2190             JOIN goals g ON g.id = m.goal_id
2191             WHERE m.id = ?
2192               AND m.status = 'active'
2193               AND m.confirmed_at IS NOT NULL
2194               AND m.review_lease_token = ?
2195               AND m.review_lease_expires_at IS NOT NULL
2196               AND julianday(m.review_lease_expires_at) > julianday(?)
2197               AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2198               AND g.domain = 'orchestration'
2199               AND g.goal_type = 'continuous'
2200               AND g.status = 'active'",
2201        )
2202        .bind(mandate_id)
2203        .bind(review_lease_token)
2204        .bind(&now_string)
2205        .bind(&now_string)
2206        .fetch_optional(&mut *tx)
2207        .await?
2208        .ok_or_else(|| {
2209            anyhow::anyhow!("mandate is not confirmed, active, or leased by this dispatcher")
2210        })?;
2211        let goal_id: String = row.get("goal_id");
2212        let project_id: String = row.get("project_id");
2213        anyhow::ensure!(
2214            root_task.goal_id == goal_id,
2215            "root task does not belong to the mandate controller"
2216        );
2217
2218        let open_run_count = sqlx::query_scalar::<_, i64>(
2219            "SELECT COUNT(*) FROM goal_runs
2220             WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')",
2221        )
2222        .bind(&goal_id)
2223        .fetch_one(&mut *tx)
2224        .await?;
2225        anyhow::ensure!(
2226            open_run_count == 0,
2227            "mandate controller already has an open goal run"
2228        );
2229
2230        let mut run = GoalRun::new(&goal_id, &project_id, "mandate");
2231        run.id = goal_run_id.to_string();
2232        run.root_task_id = Some(root_task.id.clone());
2233        sqlx::query(
2234            "INSERT INTO goal_runs
2235                (id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
2236                 status, outcome_summary, started_at, completed_at, created_at, updated_at)
2237             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2238        )
2239        .bind(&run.id)
2240        .bind(&run.project_id)
2241        .bind(&run.goal_id)
2242        .bind(&run.trigger_type)
2243        .bind(&run.schedule_id)
2244        .bind(&run.root_task_id)
2245        .bind(&run.status)
2246        .bind(&run.outcome_summary)
2247        .bind(&run.started_at)
2248        .bind(&run.completed_at)
2249        .bind(&run.created_at)
2250        .bind(&run.updated_at)
2251        .execute(&mut *tx)
2252        .await?;
2253
2254        let result = root_task
2255            .result
2256            .as_deref()
2257            .filter(|value| !value.trim().is_empty());
2258        let error = root_task
2259            .error
2260            .as_deref()
2261            .filter(|value| !value.trim().is_empty());
2262        let blocker = root_task
2263            .blocker
2264            .as_deref()
2265            .filter(|value| !value.trim().is_empty());
2266        let root_insert = sqlx::query(
2267            "INSERT INTO tasks (
2268                id, goal_id, goal_run_id, description, status, priority, task_order,
2269                parallel_group, depends_on, agent_id, context, result, error, blocker,
2270                idempotent, retry_count, max_retries, created_at, started_at, completed_at,
2271                updated_at
2272             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2273        )
2274        .bind(&root_task.id)
2275        .bind(&root_task.goal_id)
2276        .bind(&run.id)
2277        .bind(&root_task.description)
2278        .bind(&root_task.status)
2279        .bind(&root_task.priority)
2280        .bind(root_task.task_order)
2281        .bind(&root_task.parallel_group)
2282        .bind(&root_task.depends_on)
2283        .bind(&root_task.agent_id)
2284        .bind(&root_task.context)
2285        .bind(result)
2286        .bind(error)
2287        .bind(blocker)
2288        .bind(root_task.idempotent as i32)
2289        .bind(root_task.retry_count)
2290        .bind(root_task.max_retries)
2291        .bind(&root_task.created_at)
2292        .bind(&root_task.started_at)
2293        .bind(&root_task.completed_at)
2294        .bind(&root_task.created_at)
2295        .execute(&mut *tx)
2296        .await;
2297        if let Err(insert_error) = root_insert {
2298            // A failed statement leaves SQLite's write transaction active until
2299            // rollback completes. Await it here so an immediate recovery query
2300            // cannot race the drop-triggered asynchronous rollback and observe
2301            // SQLITE_BUSY under load.
2302            if let Err(rollback_error) = tx.rollback().await {
2303                return Err(anyhow::anyhow!(
2304                    "mandate review root insert failed ({insert_error}); rollback failed ({rollback_error})"
2305                ));
2306            }
2307            return Err(insert_error.into());
2308        }
2309
2310        tx.commit().await?;
2311        Ok(run)
2312    }
2313
2314    async fn keep_mandate_controller_active(
2315        &self,
2316        mandate_id: &str,
2317        expected_version: i64,
2318    ) -> anyhow::Result<bool> {
2319        anyhow::ensure!(expected_version > 0, "mandate version must be positive");
2320        let now = chrono::Utc::now().to_rfc3339();
2321        let result = sqlx::query(
2322            "UPDATE goals
2323             SET status = 'active', completed_at = NULL, dispatch_failures = 0, updated_at = ?
2324             WHERE id = (
2325                 SELECT goal_id FROM mandates
2326                 WHERE id = ? AND status = 'active' AND confirmed_at IS NOT NULL
2327                   AND version = ?
2328             )
2329               AND domain = 'orchestration' AND goal_type = 'continuous'",
2330        )
2331        .bind(&now)
2332        .bind(mandate_id)
2333        .bind(expected_version)
2334        .execute(self.work_pool())
2335        .await?;
2336        Ok(result.rows_affected() == 1)
2337    }
2338
2339    async fn claim_due_mandates(
2340        &self,
2341        limit: i64,
2342        lease_owner: &str,
2343        lease_secs: i64,
2344    ) -> anyhow::Result<Vec<Mandate>> {
2345        if limit <= 0 {
2346            return Ok(Vec::new());
2347        }
2348        anyhow::ensure!(!lease_owner.trim().is_empty(), "lease owner is required");
2349        anyhow::ensure!(
2350            (1..=86_400).contains(&lease_secs),
2351            "review lease duration must be between 1 second and 24 hours"
2352        );
2353        let now = chrono::Utc::now();
2354        let now_string = now.to_rfc3339();
2355        let lease_expires_at = (now + chrono::Duration::seconds(lease_secs)).to_rfc3339();
2356        let lease_token = format!("{}:{}", lease_owner.trim(), uuid::Uuid::new_v4());
2357        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2358
2359        // Recover the only crash state produced by the pre-atomic dispatcher:
2360        // an open mandate run whose root task was never inserted. No work can
2361        // have executed in such a run, so close it and make the mandate due in
2362        // the same transaction before selecting claims.
2363        sqlx::query(
2364            "UPDATE mandates
2365             SET next_review_at = ?, review_lease_token = NULL,
2366                 review_lease_expires_at = NULL, updated_at = ?
2367             WHERE status = 'active' AND confirmed_at IS NOT NULL
2368               AND EXISTS (
2369                   SELECT 1 FROM goal_runs gr
2370                   WHERE gr.goal_id = mandates.goal_id
2371                     AND gr.trigger_type = 'mandate'
2372                     AND gr.status IN ('pending', 'running', 'blocked')
2373                     AND NOT EXISTS (
2374                         SELECT 1 FROM tasks t WHERE t.goal_run_id = gr.id
2375                     )
2376               )",
2377        )
2378        .bind(&now_string)
2379        .bind(&now_string)
2380        .execute(&mut *tx)
2381        .await?;
2382        sqlx::query(
2383            "UPDATE goal_runs
2384             SET status = 'failed',
2385                 outcome_summary = 'Recovered an interrupted mandate dispatch before its root task was created.',
2386                 completed_at = COALESCE(completed_at, ?), updated_at = ?
2387             WHERE trigger_type = 'mandate'
2388               AND status IN ('pending', 'running', 'blocked')
2389               AND NOT EXISTS (
2390                   SELECT 1 FROM tasks t WHERE t.goal_run_id = goal_runs.id
2391               )",
2392        )
2393        .bind(&now_string)
2394        .bind(&now_string)
2395        .execute(&mut *tx)
2396        .await?;
2397
2398        // A root whose execution lease vanished may have performed an
2399        // externally visible effect before crashing. Never auto-retry that
2400        // ambiguous cycle: atomically pause it for owner reconciliation.
2401        reconcile_orphaned_mandate_runs(&mut tx, &now_string).await?;
2402
2403        // An agent question is a request for owner judgment, not a safety
2404        // fence. Once its bounded reconsider time passes without an answer,
2405        // the mandate continues within its unchanged authority instead of
2406        // parking forever; the question stays visible in decision history.
2407        resume_unanswered_agent_questions(&mut tx, &now_string).await?;
2408
2409        // Expiry is a hard authority boundary, not merely a query filter. Keep
2410        // the visible lifecycle coherent so an expired mandate cannot remain
2411        // labelled active indefinitely with an active backing controller. It
2412        // revokes attempts/runs/intentions in the same transaction, exactly as
2413        // an explicit lifecycle transition does.
2414        let expired_goal_ids = sqlx::query_scalar::<_, String>(
2415            "SELECT goal_id FROM mandates
2416             WHERE status = 'active' AND expires_at IS NOT NULL
2417               AND julianday(expires_at) <= julianday(?)",
2418        )
2419        .bind(&now_string)
2420        .fetch_all(&mut *tx)
2421        .await?;
2422        for goal_id in &expired_goal_ids {
2423            invalidate_open_mandate_runs(&mut tx, goal_id, &now_string).await?;
2424        }
2425        sqlx::query(
2426            "UPDATE goals
2427             SET status = 'completed', completed_at = COALESCE(completed_at, ?), updated_at = ?
2428             WHERE id IN (
2429                 SELECT goal_id FROM mandates
2430                 WHERE status = 'active' AND expires_at IS NOT NULL
2431                   AND julianday(expires_at) <= julianday(?)
2432             )",
2433        )
2434        .bind(&now_string)
2435        .bind(&now_string)
2436        .bind(&now_string)
2437        .execute(&mut *tx)
2438        .await?;
2439        sqlx::query(
2440            "UPDATE mandates
2441             SET status = 'completed', review_lease_token = NULL,
2442                 review_lease_expires_at = NULL, version = version + 1, updated_at = ?
2443             WHERE status = 'active' AND expires_at IS NOT NULL
2444               AND julianday(expires_at) <= julianday(?)",
2445        )
2446        .bind(&now_string)
2447        .bind(&now_string)
2448        .execute(&mut *tx)
2449        .await?;
2450        let query = format!(
2451            "UPDATE mandates
2452             SET review_lease_token = ?, review_lease_expires_at = ?, updated_at = ?
2453             WHERE id IN (
2454                 SELECT m.id
2455                 FROM mandates m
2456                 JOIN goals g ON g.id = m.goal_id
2457                 WHERE m.status = 'active'
2458                   AND m.confirmed_at IS NOT NULL
2459                   AND g.domain = 'orchestration'
2460                   AND g.goal_type = 'continuous'
2461                   AND g.status = 'active'
2462                   AND julianday(m.next_review_at) <= julianday(?)
2463                   AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2464                   AND (
2465                       m.review_lease_token IS NULL
2466                       OR m.review_lease_expires_at IS NULL
2467                       OR julianday(m.review_lease_expires_at) <= julianday(?)
2468                   )
2469                   AND NOT EXISTS (
2470                       SELECT 1 FROM goal_runs gr
2471                       WHERE gr.goal_id = m.goal_id
2472                         AND gr.status IN ('pending', 'running', 'blocked')
2473                   )
2474                 ORDER BY julianday(m.next_review_at), m.id
2475                 LIMIT ?
2476             )
2477               AND status = 'active'
2478               AND confirmed_at IS NOT NULL
2479               AND (
2480                   review_lease_token IS NULL
2481                   OR review_lease_expires_at IS NULL
2482                   OR julianday(review_lease_expires_at) <= julianday(?)
2483               )
2484             RETURNING {MANDATE_COLUMNS}"
2485        );
2486        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
2487            .bind(&lease_token)
2488            .bind(&lease_expires_at)
2489            .bind(&now_string)
2490            .bind(&now_string)
2491            .bind(&now_string)
2492            .bind(&now_string)
2493            .bind(limit.min(100))
2494            .bind(&now_string)
2495            .fetch_all(&mut *tx)
2496            .await?;
2497        tx.commit().await?;
2498        let mut mandates = rows
2499            .iter()
2500            .map(mandate_from_row)
2501            .collect::<anyhow::Result<Vec<_>>>()?;
2502        mandates.sort_by(|left, right| {
2503            left.next_review_at
2504                .cmp(&right.next_review_at)
2505                .then_with(|| left.id.cmp(&right.id))
2506        });
2507        Ok(mandates)
2508    }
2509
2510    async fn release_mandate_review_lease(
2511        &self,
2512        mandate_id: &str,
2513        lease_token: &str,
2514        retry_at: &str,
2515    ) -> anyhow::Result<bool> {
2516        anyhow::ensure!(
2517            !lease_token.trim().is_empty(),
2518            "review lease token is required"
2519        );
2520        validate_timestamp("retry_at", retry_at)?;
2521        let result = sqlx::query(
2522            "UPDATE mandates
2523             SET next_review_at = ?, review_lease_token = NULL,
2524                 review_lease_expires_at = NULL, updated_at = ?
2525             WHERE id = ? AND review_lease_token = ?",
2526        )
2527        .bind(retry_at)
2528        .bind(chrono::Utc::now().to_rfc3339())
2529        .bind(mandate_id)
2530        .bind(lease_token)
2531        .execute(self.work_pool())
2532        .await?;
2533        Ok(result.rows_affected() == 1)
2534    }
2535
2536    async fn create_mandate_task_from_attempt(
2537        &self,
2538        task: &Task,
2539        mandate_id: &str,
2540        mandate_version: i64,
2541        goal_run_id: &str,
2542        root_task_attempt_id: &str,
2543        max_non_root_tasks: i64,
2544    ) -> anyhow::Result<bool> {
2545        anyhow::ensure!(mandate_version > 0, "mandate version must be positive");
2546        anyhow::ensure!(
2547            (1..=64).contains(&max_non_root_tasks),
2548            "mandate task cap must be between 1 and 64"
2549        );
2550        anyhow::ensure!(task.status == "pending", "mandate tasks must start pending");
2551        anyhow::ensure!(
2552            !task.idempotent && task.retry_count == 0 && task.max_retries == 0,
2553            "mandate tasks cannot be replayable"
2554        );
2555        anyhow::ensure!(
2556            !task.id.trim().is_empty()
2557                && !task.goal_id.trim().is_empty()
2558                && !task.description.trim().is_empty()
2559                && task.description.trim() == task.description
2560                && task.description.chars().count() <= 8_000,
2561            "mandate task identity and description must be canonical"
2562        );
2563        anyhow::ensure!(
2564            task.agent_id.is_none()
2565                && task.result.is_none()
2566                && task.error.is_none()
2567                && task.blocker.is_none()
2568                && task.started_at.is_none()
2569                && task.completed_at.is_none(),
2570            "new mandate tasks cannot carry execution state"
2571        );
2572
2573        let now = chrono::Utc::now().to_rfc3339();
2574        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2575        // First write: acquire the writer lock and prove the complete authority
2576        // chain in one CAS. A pause, policy revision, run replacement, or root
2577        // attempt replacement either linearizes before this statement (and
2578        // rejects it) or after this transaction commits.
2579        let fenced = sqlx::query(
2580            "UPDATE task_attempts
2581             SET last_heartbeat_at = datetime('now')
2582             WHERE id = ? AND goal_run_id = ?
2583               AND status IN ('claimed', 'running')
2584               AND datetime(lease_expires_at) > datetime('now')
2585               AND EXISTS (
2586                   SELECT 1
2587                   FROM tasks root
2588                   JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2589                   JOIN mandates m ON m.goal_id = gr.goal_id
2590                   JOIN goals g ON g.id = m.goal_id
2591                   JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
2592                   JOIN intentions i ON i.decision_cycle_id = dc.id
2593                   WHERE root.id = task_attempts.task_id
2594                     AND root.current_attempt_id = task_attempts.id
2595                     AND root.status IN ('claimed', 'running')
2596                     AND root.error IS NULL AND root.blocker IS NULL
2597                     AND gr.id = ? AND gr.root_task_id = root.id
2598                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2599                     AND m.id = ? AND m.goal_id = ? AND m.version = ?
2600                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
2601                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2602                     AND g.status = 'active' AND g.domain = 'orchestration'
2603                     AND g.goal_type = 'continuous'
2604                     AND dc.mandate_id = m.id AND dc.mandate_version = m.version
2605                     AND dc.outcome = 'act'
2606                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
2607                     AND i.status = 'committed'
2608               )",
2609        )
2610        .bind(root_task_attempt_id)
2611        .bind(goal_run_id)
2612        .bind(goal_run_id)
2613        .bind(mandate_id)
2614        .bind(&task.goal_id)
2615        .bind(mandate_version)
2616        .bind(&now)
2617        .execute(&mut *tx)
2618        .await?;
2619        if fenced.rows_affected() != 1 {
2620            tx.rollback().await?;
2621            return Ok(false);
2622        }
2623
2624        let task_count = sqlx::query_scalar::<_, i64>(
2625            "SELECT COUNT(*) FROM tasks
2626             WHERE goal_run_id = ?
2627               AND id != (SELECT root_task_id FROM goal_runs WHERE id = ?)",
2628        )
2629        .bind(goal_run_id)
2630        .bind(goal_run_id)
2631        .fetch_one(&mut *tx)
2632        .await?;
2633        if task_count >= max_non_root_tasks {
2634            tx.rollback().await?;
2635            return Ok(false);
2636        }
2637
2638        if let Some(raw_dependencies) = task.depends_on.as_deref() {
2639            let dependencies = serde_json::from_str::<Vec<String>>(raw_dependencies)?;
2640            let unique = dependencies
2641                .iter()
2642                .collect::<std::collections::HashSet<_>>();
2643            anyhow::ensure!(
2644                unique.len() == dependencies.len(),
2645                "mandate task dependencies must be unique"
2646            );
2647            for dependency in dependencies {
2648                let in_run = sqlx::query_scalar::<_, i64>(
2649                    "SELECT COUNT(*) FROM tasks WHERE id = ? AND goal_run_id = ?",
2650                )
2651                .bind(&dependency)
2652                .bind(goal_run_id)
2653                .fetch_one(&mut *tx)
2654                .await?;
2655                anyhow::ensure!(in_run == 1, "mandate task dependency is outside this run");
2656            }
2657        }
2658
2659        let inserted = sqlx::query(
2660            "INSERT INTO tasks (
2661                id, goal_id, goal_run_id, description, status, priority, task_order,
2662                parallel_group, depends_on, agent_id, context, result, error, blocker,
2663                idempotent, retry_count, max_retries, created_at, started_at, completed_at,
2664                updated_at
2665             ) VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL,
2666                       0, 0, 0, ?, NULL, NULL, ?)",
2667        )
2668        .bind(&task.id)
2669        .bind(&task.goal_id)
2670        .bind(goal_run_id)
2671        .bind(&task.description)
2672        .bind(&task.priority)
2673        .bind(task.task_order)
2674        .bind(&task.parallel_group)
2675        .bind(&task.depends_on)
2676        .bind(&task.created_at)
2677        .bind(&task.created_at)
2678        .execute(&mut *tx)
2679        .await?;
2680        anyhow::ensure!(
2681            inserted.rows_affected() == 1,
2682            "mandate task was not inserted"
2683        );
2684        tx.commit().await?;
2685        Ok(true)
2686    }
2687
2688    async fn claim_mandate_task_from_attempt(
2689        &self,
2690        task_id: &str,
2691        worker_instance_id: &str,
2692        mandate_id: &str,
2693        mandate_version: i64,
2694        goal_run_id: &str,
2695        root_task_attempt_id: &str,
2696        lease_secs: i64,
2697    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
2698        anyhow::ensure!(mandate_version > 0, "mandate version must be positive");
2699        anyhow::ensure!(
2700            !task_id.trim().is_empty()
2701                && !worker_instance_id.trim().is_empty()
2702                && !root_task_attempt_id.trim().is_empty(),
2703            "mandate claim identity is required"
2704        );
2705        let lease_secs = lease_secs.clamp(1, 86_400);
2706        let now = chrono::Utc::now();
2707        let now_string = now.to_rfc3339();
2708        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2709        let fenced = sqlx::query(
2710            "UPDATE task_attempts
2711             SET last_heartbeat_at = datetime('now')
2712             WHERE id = ? AND goal_run_id = ?
2713               AND status IN ('claimed', 'running')
2714               AND datetime(lease_expires_at) > datetime('now')
2715               AND EXISTS (
2716                   SELECT 1
2717                   FROM tasks root
2718                   JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2719                   JOIN mandates m ON m.goal_id = gr.goal_id
2720                   JOIN goals g ON g.id = m.goal_id
2721                   JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
2722                   JOIN intentions i ON i.decision_cycle_id = dc.id
2723                   WHERE root.id = task_attempts.task_id
2724                     AND root.current_attempt_id = task_attempts.id
2725                     AND root.status IN ('claimed', 'running')
2726                     AND root.error IS NULL AND root.blocker IS NULL
2727                     AND gr.id = ? AND gr.root_task_id = root.id
2728                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2729                     AND m.id = ?
2730                     AND m.goal_id = (SELECT goal_id FROM tasks WHERE id = ?)
2731                     AND m.version = ?
2732                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
2733                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2734                     AND g.status = 'active' AND g.domain = 'orchestration'
2735                     AND g.goal_type = 'continuous'
2736                     AND dc.mandate_id = m.id AND dc.mandate_version = m.version
2737                     AND dc.outcome = 'act'
2738                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
2739                     AND i.status = 'committed'
2740               )",
2741        )
2742        .bind(root_task_attempt_id)
2743        .bind(goal_run_id)
2744        .bind(goal_run_id)
2745        .bind(mandate_id)
2746        .bind(task_id)
2747        .bind(mandate_version)
2748        .bind(&now_string)
2749        .execute(&mut *tx)
2750        .await?;
2751        if fenced.rows_affected() != 1 {
2752            tx.rollback().await?;
2753            return Ok(None);
2754        }
2755
2756        let claimable = sqlx::query_scalar::<_, String>(
2757            "SELECT t.goal_id
2758             FROM tasks t JOIN goal_runs gr ON gr.id = t.goal_run_id
2759             WHERE t.id = ? AND t.goal_run_id = ? AND t.id != gr.root_task_id
2760               AND t.status = 'pending' AND t.current_attempt_id IS NULL
2761               AND t.worker_profile_id IS NULL
2762               AND COALESCE(t.workspace_policy_explicit, 0) = 0
2763               AND NOT EXISTS (SELECT 1 FROM task_workspaces w WHERE w.task_id = t.id)",
2764        )
2765        .bind(task_id)
2766        .bind(goal_run_id)
2767        .fetch_optional(&mut *tx)
2768        .await?;
2769        if claimable.is_none() {
2770            tx.rollback().await?;
2771            return Ok(None);
2772        }
2773        let unmet = sqlx::query_scalar::<_, i64>(
2774            "SELECT COUNT(*)
2775             FROM json_each(COALESCE((SELECT depends_on FROM tasks WHERE id = ?), '[]')) dep
2776             WHERE NOT EXISTS (
2777                SELECT 1 FROM tasks d
2778                WHERE d.id = CAST(dep.value AS TEXT)
2779                  AND d.goal_run_id = ?
2780                  AND d.status IN ('completed', 'skipped', 'superseded')
2781             )",
2782        )
2783        .bind(task_id)
2784        .bind(goal_run_id)
2785        .fetch_one(&mut *tx)
2786        .await?;
2787        if unmet > 0 {
2788            tx.rollback().await?;
2789            return Ok(None);
2790        }
2791
2792        let attempt = crate::traits::TaskAttempt {
2793            id: uuid::Uuid::new_v4().to_string(),
2794            task_id: task_id.to_string(),
2795            goal_run_id: goal_run_id.to_string(),
2796            worker_profile_id: None,
2797            worker_instance_id: worker_instance_id.to_string(),
2798            lease_token: uuid::Uuid::new_v4().to_string(),
2799            status: "claimed".to_string(),
2800            lease_expires_at: (now + chrono::Duration::seconds(lease_secs)).to_rfc3339(),
2801            last_heartbeat_at: now_string.clone(),
2802            workspace_id: None,
2803            started_at: now_string,
2804            completed_at: None,
2805        };
2806        sqlx::query(
2807            "INSERT INTO task_attempts
2808                (id, task_id, goal_run_id, worker_profile_id, worker_instance_id,
2809                 lease_token, status, lease_expires_at, last_heartbeat_at,
2810                 workspace_id, started_at, completed_at)
2811             VALUES (?, ?, ?, NULL, ?, ?, 'claimed', ?, ?, NULL, ?, NULL)",
2812        )
2813        .bind(&attempt.id)
2814        .bind(&attempt.task_id)
2815        .bind(&attempt.goal_run_id)
2816        .bind(&attempt.worker_instance_id)
2817        .bind(&attempt.lease_token)
2818        .bind(&attempt.lease_expires_at)
2819        .bind(&attempt.last_heartbeat_at)
2820        .bind(&attempt.started_at)
2821        .execute(&mut *tx)
2822        .await?;
2823        let updated = sqlx::query(
2824            "UPDATE tasks
2825             SET status = 'claimed', agent_id = ?, current_attempt_id = ?,
2826                 worker_profile_id = NULL, started_at = COALESCE(started_at, datetime('now')),
2827                 result = NULL, error = NULL, blocker = NULL, completed_at = NULL,
2828                 updated_at = datetime('now'), version = version + 1
2829             WHERE id = ? AND goal_run_id = ? AND status = 'pending'
2830               AND current_attempt_id IS NULL",
2831        )
2832        .bind(worker_instance_id)
2833        .bind(&attempt.id)
2834        .bind(task_id)
2835        .bind(goal_run_id)
2836        .execute(&mut *tx)
2837        .await?;
2838        if updated.rows_affected() != 1 {
2839            tx.rollback().await?;
2840            return Ok(None);
2841        }
2842        tx.commit().await?;
2843        Ok(Some(attempt))
2844    }
2845
2846    async fn record_mandate_decision(
2847        &self,
2848        decision: &MandateDecisionCycle,
2849        intention: Option<&Intention>,
2850        task_attempt_id: Option<&str>,
2851    ) -> anyhow::Result<()> {
2852        self.record_mandate_decision_with_updates(decision, intention, None, task_attempt_id)
2853            .await
2854    }
2855
2856    async fn record_mandate_decision_with_updates(
2857        &self,
2858        decision: &MandateDecisionCycle,
2859        intention: Option<&Intention>,
2860        operating_updates: Option<&MandateOperatingUpdates>,
2861        task_attempt_id: Option<&str>,
2862    ) -> anyhow::Result<()> {
2863        decision
2864            .validate_content_bounds()
2865            .map_err(anyhow::Error::msg)?;
2866        if let Some(updates) = operating_updates
2867            && let Some(note) = updates.learning_note.as_ref()
2868        {
2869            note.validate().map_err(anyhow::Error::msg)?;
2870            anyhow::ensure!(
2871                note.mandate_id == decision.mandate_id
2872                    && note.mandate_version == decision.mandate_version
2873                    && note.learned_in_decision_cycle_id == decision.id,
2874                "learning note does not belong to this decision"
2875            );
2876            anyhow::ensure!(
2877                note.evidence_receipt_ids
2878                    .iter()
2879                    .all(|id| decision.evidence_receipt_ids.contains(id)),
2880                "learning evidence must be a subset of current decision evidence"
2881            );
2882        }
2883        anyhow::ensure!(
2884            decision.action_attempts == 0,
2885            "a new decision cannot pre-spend actions"
2886        );
2887        anyhow::ensure!(
2888            (decision.outcome == MandateDecisionOutcome::Act) == intention.is_some(),
2889            "ACT requires one intention and non-ACT outcomes must not create one"
2890        );
2891        // Reject malformed or policy-unrelated value judgments before taking
2892        // the SQLite writer lock. The same checks are repeated below against
2893        // the transaction-fenced mandate snapshot, so a racing policy update
2894        // still fails closed.
2895        if let Some(intention) = intention
2896            && let Some(mandate) = self.get_mandate(&decision.mandate_id).await?
2897        {
2898            intention
2899                .validate_value_against(&mandate)
2900                .map_err(anyhow::Error::msg)?;
2901        }
2902        if decision.outcome == MandateDecisionOutcome::Ask {
2903            anyhow::ensure!(
2904                decision
2905                    .question
2906                    .as_deref()
2907                    .is_some_and(|value| !value.trim().is_empty()),
2908                "ASK requires a concrete question"
2909            );
2910        }
2911        if let Some(alert) = decision.owner_alert.as_deref() {
2912            anyhow::ensure!(
2913                decision.outcome == MandateDecisionOutcome::Wait && !alert.trim().is_empty(),
2914                "owner_alert is a non-empty finding carried by a WAIT"
2915            );
2916        }
2917        anyhow::ensure!(
2918            decision.outcome == MandateDecisionOutcome::Stop
2919                || (decision.termination_kind.is_none() && decision.termination_match.is_none()),
2920            "termination fields are valid only for STOP"
2921        );
2922
2923        let now = chrono::Utc::now();
2924        let now_string = now.to_rfc3339();
2925        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2926        if let Some(task_attempt_id) = task_attempt_id {
2927            anyhow::ensure!(
2928                !task_attempt_id.trim().is_empty() && task_attempt_id.trim() == task_attempt_id,
2929                "task attempt id must be canonical"
2930            );
2931            // This is deliberately a write-CAS rather than a preceding read.
2932            // It acquires the SQLite writer lock while proving that the exact
2933            // dispatcher-owned root attempt is still current, live, and bound
2934            // to the pinned mandate run. Attempt replacement cannot race the
2935            // decision insert after this statement within the transaction.
2936            let fenced = sqlx::query(
2937                "UPDATE task_attempts
2938                 SET last_heartbeat_at = datetime('now')
2939                 WHERE id = ? AND goal_run_id = ?
2940                   AND status IN ('claimed', 'running')
2941                   AND datetime(lease_expires_at) > datetime('now')
2942                   AND EXISTS (
2943                       SELECT 1
2944                       FROM tasks t
2945                       JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2946                       WHERE t.id = task_attempts.task_id
2947                         AND t.current_attempt_id = task_attempts.id
2948                         AND t.status IN ('claimed', 'running')
2949                         AND t.error IS NULL AND t.blocker IS NULL
2950                         AND gr.id = ? AND gr.root_task_id = t.id
2951                         AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2952                   )",
2953            )
2954            .bind(task_attempt_id)
2955            .bind(&decision.goal_run_id)
2956            .bind(&decision.goal_run_id)
2957            .execute(&mut *tx)
2958            .await?;
2959            anyhow::ensure!(
2960                fenced.rows_affected() == 1,
2961                "mandate task-lead attempt is no longer current and executable"
2962            );
2963        }
2964        let query = format!(
2965            "SELECT {}
2966             FROM mandates m
2967             JOIN goals g ON g.id = m.goal_id
2968             JOIN goal_runs gr ON gr.goal_id = m.goal_id
2969             WHERE m.id = ? AND gr.id = ?
2970               AND m.status = 'active'
2971               AND m.confirmed_at IS NOT NULL
2972               AND m.review_lease_token IS NOT NULL
2973               AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2974               AND g.domain = 'orchestration' AND g.goal_type = 'continuous'
2975               AND g.status = 'active'
2976               AND gr.trigger_type = 'mandate'
2977               AND gr.status = 'running'",
2978            qualified_columns("m", MANDATE_COLUMNS)
2979        );
2980        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
2981            .bind(&decision.mandate_id)
2982            .bind(&decision.goal_run_id)
2983            .bind(&now_string)
2984            .fetch_optional(&mut *tx)
2985            .await?
2986            .ok_or_else(|| anyhow::anyhow!("mandate is not actively leased for this goal run"))?;
2987        let mandate = mandate_from_row(&row)?;
2988        anyhow::ensure!(
2989            decision.mandate_version == mandate.version,
2990            "mandate version changed before the decision was committed"
2991        );
2992        anyhow::ensure!(
2993            decision.owner_alert.is_none() || mandate.authority.owner_alerts,
2994            "this mandate's confirmed policy does not include telling the owner what it finds; record WAIT without owner_alert, or ASK the owner to confirm a policy update that adds it"
2995        );
2996        validate_current_run_receipt_refs(
2997            &mut tx,
2998            &decision.goal_run_id,
2999            &decision.evidence_receipt_ids,
3000        )
3001        .await?;
3002        // A runtime-authored fallback is a typed review-failure marker, not a
3003        // deliberation: it carries no evidence, no intention, and no
3004        // authority, so the semantic gates below (measurement) cannot apply
3005        // to it. Structural gates (lease, version, one decision
3006        // per run) still apply.
3007        let runtime_fallback = decision.is_runtime_fallback();
3008        if runtime_fallback {
3009            anyhow::ensure!(
3010                decision.outcome == MandateDecisionOutcome::Wait
3011                    && decision.evidence_receipt_ids.is_empty()
3012                    && decision.action_attempts == 0
3013                    && intention.is_none()
3014                    && operating_updates.is_none(),
3015                "runtime fallback decisions must be bare WAIT markers"
3016            );
3017        }
3018        // Whether ACT is admissible now is decided here, in the transaction
3019        // that commits the decision, by the same rules as every other
3020        // outcome (`admissibility`), so no caller keeps its own copy.
3021        if decision.outcome == MandateDecisionOutcome::Act {
3022            let quota =
3023                mutation_quota_state_on_connection(&mut tx, &mandate.id, &now_string).await?;
3024            let block = match &quota {
3025                Some(quota) => quota.block_reason,
3026                None => Some(MandateMutationQuotaBlockReason::MutationDisabled),
3027            };
3028            let admissible =
3029                crate::admissibility::admissible_outcomes(&crate::admissibility::OutcomeState {
3030                    quota_block: block,
3031                });
3032            if !admissible.act {
3033                if block == Some(MandateMutationQuotaBlockReason::MutationDisabled) {
3034                    anyhow::bail!(
3035                        "ACT requires a positive governed mutation budget; choose WAIT, ASK, or STOP for an observation-only cycle"
3036                    );
3037                }
3038                let earliest = quota
3039                    .as_ref()
3040                    .and_then(|quota| quota.earliest_next_slot_at.as_deref())
3041                    .unwrap_or("unavailable");
3042                anyhow::bail!(
3043                    "mandate_mutation_quota_unavailable: choose WAIT; earliest_next_slot_at={earliest}"
3044                );
3045            }
3046        }
3047        let current_measurement = if mandate.objective_control.is_some()
3048            && !runtime_fallback
3049            && matches!(
3050                decision.outcome,
3051                MandateDecisionOutcome::Act
3052                    | MandateDecisionOutcome::Wait
3053                    | MandateDecisionOutcome::Stop
3054            ) {
3055            sqlx::query_as::<_, (i64, i64)>(
3056                "SELECT value_micros, confidence_bps FROM mandate_objective_measurements
3057                 WHERE mandate_id = ? AND mandate_version = ? AND goal_run_id = ?
3058                 ORDER BY julianday(observed_at) DESC, id DESC LIMIT 1",
3059            )
3060            .bind(&mandate.id)
3061            .bind(mandate.version)
3062            .bind(&decision.goal_run_id)
3063            .fetch_optional(&mut *tx)
3064            .await?
3065        } else {
3066            None
3067        };
3068        // The measured objective belongs to autopilot. A bounded mandate's
3069        // objective control is advisory: recorded measurements are kept, but
3070        // a decision never waits on one.
3071        let control_loop = mandate.autonomy_mode.is_autopilot();
3072        if control_loop
3073            && mandate.objective_control.is_some()
3074            && !runtime_fallback
3075            && matches!(
3076                decision.outcome,
3077                MandateDecisionOutcome::Act | MandateDecisionOutcome::Wait
3078            )
3079        {
3080            anyhow::ensure!(
3081                current_measurement.is_some(),
3082                "controlled mandate decisions require a receipt-backed metric measurement from the current run"
3083            );
3084        }
3085        if decision.outcome == MandateDecisionOutcome::Stop {
3086            let termination_kind = decision
3087                .termination_kind
3088                .ok_or_else(|| anyhow::anyhow!("STOP requires a typed termination_kind"))?;
3089            match termination_kind {
3090                MandateTerminationKind::SuccessCriteriaSatisfied => {
3091                    if let Some(control) =
3092                        mandate.objective_control.as_ref().filter(|_| control_loop)
3093                    {
3094                        anyhow::ensure!(
3095                            current_measurement.is_some_and(|(value, confidence)| {
3096                                confidence > 0 && control.target_reached(value)
3097                            }),
3098                            "success termination requires a credible (confidence > 0) current receipt-backed metric that reaches the owner-confirmed target"
3099                        );
3100                    }
3101                    let matched = decision.termination_match.as_deref().ok_or_else(|| {
3102                        anyhow::anyhow!("success termination requires termination_match")
3103                    })?;
3104                    anyhow::ensure!(
3105                        mandate
3106                            .success_criteria
3107                            .iter()
3108                            .any(|entry| entry == matched),
3109                        "termination_match is not an owner-authored success criterion"
3110                    );
3111                }
3112                MandateTerminationKind::StopConditionMet => {
3113                    let matched = decision.termination_match.as_deref().ok_or_else(|| {
3114                        anyhow::anyhow!("stop-condition termination requires termination_match")
3115                    })?;
3116                    anyhow::ensure!(
3117                        mandate.stop_conditions.iter().any(|entry| entry == matched),
3118                        "termination_match is not an owner-authored stop condition"
3119                    );
3120                }
3121                MandateTerminationKind::SafetyTermination => {}
3122            }
3123            anyhow::ensure!(
3124                !termination_kind.requires_receipt_evidence()
3125                    || !decision.evidence_receipt_ids.is_empty(),
3126                "evidence-dependent STOP requires at least one current-run receipt"
3127            );
3128        }
3129
3130        let mut next_review_at =
3131            clamped_next_review_at(&mandate, decision.reconsider_at.as_deref(), now)?;
3132        if decision.outcome != MandateDecisionOutcome::Stop
3133            && let Some(control) = mandate.objective_control.as_ref()
3134        {
3135            let measurement_due = now + chrono::Duration::seconds(control.measurement_cadence_secs);
3136            let selected =
3137                chrono::DateTime::parse_from_rfc3339(&next_review_at)?.with_timezone(&chrono::Utc);
3138            if selected > measurement_due {
3139                next_review_at = measurement_due.to_rfc3339();
3140            }
3141        }
3142        let persisted_reconsider_at = if decision.outcome == MandateDecisionOutcome::Stop {
3143            None
3144        } else {
3145            Some(next_review_at.as_str())
3146        };
3147        sqlx::query(
3148            "INSERT INTO mandate_decision_cycles (
3149                id, mandate_id, goal_run_id, mandate_version, outcome, origin, activity_level,
3150                rationale, belief_snapshot, evidence_receipt_ids_json, question, owner_alert,
3151                termination_kind, termination_match, reconsider_at, action_attempts, created_at,
3152                updated_at
3153             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3154        )
3155        .bind(&decision.id)
3156        .bind(&decision.mandate_id)
3157        .bind(&decision.goal_run_id)
3158        .bind(decision.mandate_version)
3159        .bind(decision.outcome.as_str())
3160        .bind(decision.origin.as_str())
3161        .bind(decision.activity_level.as_str())
3162        .bind(&decision.rationale)
3163        .bind(&decision.belief_snapshot)
3164        .bind(serde_json::to_string(&decision.evidence_receipt_ids)?)
3165        .bind(&decision.question)
3166        .bind(&decision.owner_alert)
3167        .bind(
3168            decision
3169                .termination_kind
3170                .map(MandateTerminationKind::as_str),
3171        )
3172        .bind(&decision.termination_match)
3173        .bind(persisted_reconsider_at)
3174        .bind(decision.action_attempts)
3175        .bind(&decision.created_at)
3176        .bind(&decision.updated_at)
3177        .execute(&mut *tx)
3178        .await?;
3179
3180        if let Some(intention) = intention {
3181            anyhow::ensure!(
3182                intention.mandate_id == decision.mandate_id
3183                    && intention.decision_cycle_id == decision.id
3184                    && intention.goal_run_id == decision.goal_run_id,
3185                "intention does not belong to this decision cycle"
3186            );
3187            intention
3188                .validate_content_bounds()
3189                .map_err(anyhow::Error::msg)?;
3190            intention
3191                .validate_value_against(&mandate)
3192                .map_err(anyhow::Error::msg)?;
3193            anyhow::ensure!(
3194                intention.status == IntentionStatus::Committed && intention.completed_at.is_none(),
3195                "a new intention must be committed and incomplete"
3196            );
3197            sqlx::query(
3198                "INSERT INTO intentions (
3199                    id, mandate_id, decision_cycle_id, goal_run_id, description,
3200                    rationale, value_criterion, expected_benefit, risk, invalidation_criteria,
3201                    status, created_at, updated_at, completed_at
3202                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3203            )
3204            .bind(&intention.id)
3205            .bind(&intention.mandate_id)
3206            .bind(&intention.decision_cycle_id)
3207            .bind(&intention.goal_run_id)
3208            .bind(&intention.description)
3209            .bind(&intention.rationale)
3210            .bind(&intention.value_criterion)
3211            .bind(&intention.expected_benefit)
3212            .bind(&intention.risk)
3213            .bind(&intention.invalidation_criteria)
3214            .bind(intention.status.as_str())
3215            .bind(&intention.created_at)
3216            .bind(&intention.updated_at)
3217            .bind(&intention.completed_at)
3218            .execute(&mut *tx)
3219            .await?;
3220        }
3221
3222        if let Some(updates) = operating_updates
3223            && let Some(note) = updates.learning_note.as_ref()
3224        {
3225            sqlx::query(
3226                "INSERT INTO mandate_learning_notes (
3227                        id, mandate_id, mandate_version, learned_in_decision_cycle_id,
3228                        summary, evidence_receipt_ids_json, created_at
3229                     ) VALUES (?, ?, ?, ?, ?, ?, ?)",
3230            )
3231            .bind(&note.id)
3232            .bind(&note.mandate_id)
3233            .bind(note.mandate_version)
3234            .bind(&note.learned_in_decision_cycle_id)
3235            .bind(&note.summary)
3236            .bind(serde_json::to_string(&note.evidence_receipt_ids)?)
3237            .bind(&note.created_at)
3238            .execute(&mut *tx)
3239            .await?;
3240        }
3241
3242        // The durable decision remains provisional until the root task itself
3243        // is durably successful and the proof finalizer closes the run. This
3244        // keeps every post-decision crash inside active orphan reconciliation.
3245        let transitioned = sqlx::query(
3246            "UPDATE mandates
3247             SET next_review_at = ?, review_lease_token = NULL,
3248                 review_lease_expires_at = NULL, updated_at = ?
3249             WHERE id = ? AND status = 'active' AND version = ?
3250               AND confirmed_at IS NOT NULL
3251               AND review_lease_token IS NOT NULL",
3252        )
3253        .bind(&next_review_at)
3254        .bind(&now_string)
3255        .bind(&decision.mandate_id)
3256        .bind(decision.mandate_version)
3257        .execute(&mut *tx)
3258        .await?;
3259        anyhow::ensure!(
3260            transitioned.rows_affected() == 1,
3261            "mandate changed before the decision was committed"
3262        );
3263        tx.commit().await?;
3264        Ok(())
3265    }
3266
3267    async fn get_mandate_decision_for_run(
3268        &self,
3269        goal_run_id: &str,
3270    ) -> anyhow::Result<Option<MandateDecisionCycle>> {
3271        let query =
3272            format!("SELECT {DECISION_COLUMNS} FROM mandate_decision_cycles WHERE goal_run_id = ?");
3273        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
3274            .bind(goal_run_id)
3275            .fetch_optional(self.work_pool())
3276            .await?;
3277        row.as_ref().map(decision_from_row).transpose()
3278    }
3279
3280    async fn current_run_evidence_receipt_ids(
3281        &self,
3282        goal_run_id: &str,
3283        limit: usize,
3284    ) -> anyhow::Result<Vec<String>> {
3285        // The predicate of `validate_current_run_receipt_refs`, so every id
3286        // returned here passes that check.
3287        let excluded = crate::MANDATE_PROTOCOL_TOOLS
3288            .iter()
3289            .map(|_| "?")
3290            .collect::<Vec<_>>()
3291            .join(", ");
3292        let query = format!(
3293            "SELECT json_extract(e.data, '$.tool_call_id')
3294             FROM events e
3295             JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
3296             WHERE e.event_type = 'tool_result'
3297               AND t.goal_run_id = ?
3298               AND json_extract(e.data, '$.receipt.schema_version') = ?
3299               AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
3300               AND json_extract(e.data, '$.receipt.outcome_evidence')
3301                   IN ('tool_reported', 'structured_metadata')
3302               AND json_extract(e.data, '$.tool_call_id') IS NOT NULL
3303               AND json_extract(e.data, '$.name') NOT IN ({excluded})
3304             ORDER BY e.id DESC
3305             LIMIT ?"
3306        );
3307        let mut statement = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*query))
3308            .bind(goal_run_id)
3309            .bind(i64::from(aidaemon_events::ToolReceiptV1::SCHEMA_VERSION));
3310        for tool in crate::MANDATE_PROTOCOL_TOOLS {
3311            statement = statement.bind(*tool);
3312        }
3313        Ok(statement
3314            .bind(i64::try_from(limit).unwrap_or(i64::MAX))
3315            .fetch_all(self.work_pool())
3316            .await?)
3317    }
3318
3319    async fn list_mandate_decisions(
3320        &self,
3321        mandate_id: &str,
3322        limit: i64,
3323    ) -> anyhow::Result<Vec<MandateDecisionCycle>> {
3324        let query = format!(
3325            "SELECT {DECISION_COLUMNS} FROM mandate_decision_cycles
3326             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3327        );
3328        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3329            .bind(mandate_id)
3330            .bind(limit.clamp(1, 200))
3331            .fetch_all(self.work_pool())
3332            .await?;
3333        rows.iter().map(decision_from_row).collect()
3334    }
3335
3336    async fn list_intentions(
3337        &self,
3338        mandate_id: &str,
3339        limit: i64,
3340    ) -> anyhow::Result<Vec<Intention>> {
3341        let query = format!(
3342            "SELECT {INTENTION_COLUMNS} FROM intentions
3343             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3344        );
3345        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3346            .bind(mandate_id)
3347            .bind(limit.clamp(1, 200))
3348            .fetch_all(self.work_pool())
3349            .await?;
3350        rows.iter().map(intention_from_row).collect()
3351    }
3352
3353    async fn record_mandate_learning_note(&self, note: &MandateLearningNote) -> anyhow::Result<()> {
3354        note.validate().map_err(anyhow::Error::msg)?;
3355        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3356        let decision_exists = sqlx::query_scalar::<_, i64>(
3357            "SELECT 1
3358             FROM mandate_decision_cycles dc
3359             JOIN mandates m ON m.id = dc.mandate_id
3360             WHERE dc.id = ? AND dc.mandate_id = ? AND dc.mandate_version = ?
3361               AND m.version >= dc.mandate_version
3362             LIMIT 1",
3363        )
3364        .bind(&note.learned_in_decision_cycle_id)
3365        .bind(&note.mandate_id)
3366        .bind(note.mandate_version)
3367        .fetch_optional(&mut *tx)
3368        .await?;
3369        anyhow::ensure!(
3370            decision_exists.is_some(),
3371            "mandate learning note does not belong to its decision epoch"
3372        );
3373
3374        let mut unique = std::collections::HashSet::new();
3375        for receipt_id in &note.evidence_receipt_ids {
3376            anyhow::ensure!(
3377                unique.insert(receipt_id),
3378                "duplicate learning evidence receipt ID"
3379            );
3380            let found = sqlx::query_scalar::<_, i64>(
3381                "SELECT 1
3382                 FROM events e
3383                 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
3384                 JOIN goal_runs gr ON gr.id = t.goal_run_id
3385                 JOIN mandates m ON m.goal_id = gr.goal_id
3386                 WHERE m.id = ? AND gr.trigger_type = 'mandate'
3387                   AND e.event_type = 'tool_result'
3388                   AND json_extract(e.data, '$.tool_call_id') = ?
3389                   AND json_extract(e.data, '$.receipt.schema_version') = ?
3390                   AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
3391                   AND json_extract(e.data, '$.receipt.outcome_evidence')
3392                       IN ('tool_reported', 'structured_metadata')
3393                 LIMIT 1",
3394            )
3395            .bind(&note.mandate_id)
3396            .bind(receipt_id)
3397            .bind(i64::from(aidaemon_events::ToolReceiptV1::SCHEMA_VERSION))
3398            .fetch_optional(&mut *tx)
3399            .await?;
3400            anyhow::ensure!(
3401                found.is_some(),
3402                "learning evidence receipt `{receipt_id}` is not a same-mandate structured success"
3403            );
3404        }
3405
3406        sqlx::query(
3407            "INSERT INTO mandate_learning_notes (
3408                id, mandate_id, mandate_version, learned_in_decision_cycle_id,
3409                summary, evidence_receipt_ids_json, created_at
3410             ) VALUES (?, ?, ?, ?, ?, ?, ?)",
3411        )
3412        .bind(&note.id)
3413        .bind(&note.mandate_id)
3414        .bind(note.mandate_version)
3415        .bind(&note.learned_in_decision_cycle_id)
3416        .bind(&note.summary)
3417        .bind(serde_json::to_string(&note.evidence_receipt_ids)?)
3418        .bind(&note.created_at)
3419        .execute(&mut *tx)
3420        .await?;
3421        tx.commit().await?;
3422        Ok(())
3423    }
3424
3425    async fn list_mandate_learning_notes(
3426        &self,
3427        mandate_id: &str,
3428        limit: i64,
3429    ) -> anyhow::Result<Vec<MandateLearningNote>> {
3430        let query = format!(
3431            "SELECT {LEARNING_NOTE_COLUMNS} FROM mandate_learning_notes
3432             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3433        );
3434        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3435            .bind(mandate_id)
3436            .bind(limit.clamp(1, 100))
3437            .fetch_all(self.work_pool())
3438            .await?;
3439        rows.iter().map(learning_note_from_row).collect()
3440    }
3441
3442    async fn wake_mandates_for_signal(
3443        &self,
3444        signal: &MandateWakeSignal,
3445    ) -> anyhow::Result<Vec<String>> {
3446        signal.validate().map_err(anyhow::Error::msg)?;
3447        let mandates = self.list_mandates(None, false).await?;
3448        let mut target = reqwest::Url::parse(&signal.target_url)?;
3449        target.set_query(None);
3450        target.set_fragment(None);
3451        let target_url = target.to_string();
3452        let signal_digest = hex::encode(Sha256::digest(
3453            format!(
3454                "aidaemon.mandate.wake.v1\0{}\0{}\0{}\0{}\0{}",
3455                signal.kind.as_str(),
3456                signal.source,
3457                signal.target_url,
3458                signal.account_id.as_deref().unwrap_or(""),
3459                signal.dedupe_key
3460            )
3461            .as_bytes(),
3462        ));
3463        let received_at = chrono::Utc::now().to_rfc3339();
3464        let mut awakened = Vec::new();
3465        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3466        for mandate in mandates
3467            .into_iter()
3468            .filter(|mandate| crate::authority::mandate_accepts_wake_signal(mandate, signal))
3469        {
3470            let inserted = sqlx::query(
3471                "INSERT OR IGNORE INTO mandate_wake_signals (
3472                    mandate_id, mandate_version, signal_digest, kind, source,
3473                    target_url, account_id, occurred_at, received_at
3474                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
3475            )
3476            .bind(&mandate.id)
3477            .bind(mandate.version)
3478            .bind(&signal_digest)
3479            .bind(signal.kind.as_str())
3480            .bind(&signal.source)
3481            .bind(&target_url)
3482            .bind(&signal.account_id)
3483            .bind(&signal.occurred_at)
3484            .bind(&received_at)
3485            .execute(&mut *tx)
3486            .await?;
3487            if inserted.rows_affected() == 0 {
3488                continue;
3489            }
3490            let updated = sqlx::query(
3491                "UPDATE mandates
3492                 SET next_review_at = CASE
3493                        WHEN julianday(next_review_at) > julianday(?) THEN ?
3494                        ELSE next_review_at
3495                     END
3496                 WHERE id = ? AND version = ? AND status = 'active'
3497                   AND autonomy_mode = 'autopilot' AND confirmed_at IS NOT NULL",
3498            )
3499            .bind(&received_at)
3500            .bind(&received_at)
3501            .bind(&mandate.id)
3502            .bind(mandate.version)
3503            .execute(&mut *tx)
3504            .await?;
3505            if updated.rows_affected() == 1 {
3506                awakened.push(mandate.id);
3507            }
3508        }
3509        tx.commit().await?;
3510        Ok(awakened)
3511    }
3512
3513    async fn resolve_mandate_suspension(
3514        &self,
3515        mandate_id: &str,
3516        expected_version: i64,
3517        expected_kind: MandateSuspensionKind,
3518        controller_context: Option<&str>,
3519        reconciliation_resolution: Option<MandateReconciliationResolution>,
3520        owner_guidance: &str,
3521        owner_session: &str,
3522    ) -> anyhow::Result<bool> {
3523        anyhow::ensure!(
3524            !owner_guidance.trim().is_empty() && owner_guidance.trim() == owner_guidance,
3525            "owner guidance is required and must be canonical"
3526        );
3527        anyhow::ensure!(
3528            owner_guidance.chars().count() <= 1024 && owner_guidance.len() <= 1024,
3529            "owner guidance exceeds its 1 KiB bound"
3530        );
3531        anyhow::ensure!(
3532            !owner_session.trim().is_empty(),
3533            "owner session is required"
3534        );
3535        if let Some(context) = controller_context {
3536            anyhow::ensure!(
3537                context.chars().count() <= 64_000,
3538                "mandate controller context is too large"
3539            );
3540            serde_json::from_str::<serde_json::Value>(context)?;
3541        }
3542        match expected_kind {
3543            MandateSuspensionKind::AwaitingAnswer => anyhow::ensure!(
3544                reconciliation_resolution.is_none(),
3545                "non-reconciliation suspensions cannot carry a reconciliation resolution"
3546            ),
3547            MandateSuspensionKind::ReconciliationRequired
3548            | MandateSuspensionKind::ExecutionLeaseLost
3549            | MandateSuspensionKind::ReviewFailed
3550            | MandateSuspensionKind::AuthorityRevokedWithUnresolvedMutation => anyhow::ensure!(
3551                reconciliation_resolution.is_some(),
3552                "safety suspension requires a typed reconciliation resolution"
3553            ),
3554            MandateSuspensionKind::OwnerPaused => {
3555                anyhow::bail!("owner-paused mandates must use ordinary resume")
3556            }
3557        }
3558
3559        let now = chrono::Utc::now().to_rfc3339();
3560        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3561        let current = sqlx::query(
3562            "SELECT goal_id, created_by_session, suspension_json
3563             FROM mandates
3564             WHERE id = ? AND version = ? AND status = 'awaiting_input'
3565               AND confirmed_at IS NOT NULL",
3566        )
3567        .bind(mandate_id)
3568        .bind(expected_version)
3569        .fetch_optional(&mut *tx)
3570        .await?;
3571        let Some(current) = current else {
3572            tx.rollback().await?;
3573            return Ok(false);
3574        };
3575        anyhow::ensure!(
3576            current.get::<String, _>("created_by_session") == owner_session,
3577            "mandate does not belong to this owner session"
3578        );
3579        let suspension: MandateSuspension = serde_json::from_str(
3580            &current
3581                .get::<Option<String>, _>("suspension_json")
3582                .ok_or_else(|| anyhow::anyhow!("awaiting-input mandate has no typed suspension"))?,
3583        )?;
3584        anyhow::ensure!(
3585            suspension.kind == expected_kind,
3586            "mandate suspension changed before it was resolved"
3587        );
3588        let goal_id: String = current.get("goal_id");
3589
3590        if let Some(resolution) = reconciliation_resolution {
3591            sqlx::query(
3592                "INSERT INTO mandate_reconciliations (
3593                    id, mandate_id, suspended_version, suspension_kind, resolution,
3594                    owner_guidance, resolved_by_session, resolved_at
3595                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
3596            )
3597            .bind(uuid::Uuid::new_v4().to_string())
3598            .bind(mandate_id)
3599            .bind(expected_version)
3600            .bind(expected_kind.as_str())
3601            .bind(resolution.as_str())
3602            .bind(owner_guidance)
3603            .bind(owner_session)
3604            .bind(&now)
3605            .execute(&mut *tx)
3606            .await?;
3607        }
3608
3609        let updated = sqlx::query(
3610            "UPDATE mandates
3611             SET status = 'active', suspension_json = NULL, next_review_at = ?,
3612                 review_lease_token = NULL, review_lease_expires_at = NULL,
3613                 version = version + 1, updated_at = ?
3614             WHERE id = ? AND version = ? AND status = 'awaiting_input'",
3615        )
3616        .bind(&now)
3617        .bind(&now)
3618        .bind(mandate_id)
3619        .bind(expected_version)
3620        .execute(&mut *tx)
3621        .await?;
3622        if updated.rows_affected() != 1 {
3623            tx.rollback().await?;
3624            return Ok(false);
3625        }
3626        if let Some(context) = controller_context {
3627            sqlx::query("UPDATE goals SET context = ?, updated_at = ? WHERE id = ?")
3628                .bind(context)
3629                .bind(&now)
3630                .bind(&goal_id)
3631                .execute(&mut *tx)
3632                .await?;
3633        }
3634        update_controller_status(&mut tx, &goal_id, MandateStatus::Active, &now).await?;
3635        tx.commit().await?;
3636        Ok(true)
3637    }
3638
3639    async fn reserve_mandate_action_attempt(
3640        &self,
3641        reservation: &MandateMutationReservation,
3642    ) -> anyhow::Result<Option<MandateMutationAttempt>> {
3643        let reserved_at = validate_mutation_reservation(reservation)?;
3644        let expected_attempts = reservation.grant.reserved_action_attempt - 1;
3645        let reserved_at_string = reserved_at.to_rfc3339();
3646        let mutation_effects_json = serde_json::to_string(&reservation.mutation_effects)?;
3647        let targets_json = serde_json::to_string(&reservation.targets)?;
3648        let account_identifiers_json = serde_json::to_string(&reservation.account_identifiers)?;
3649        let ledger_id = uuid::Uuid::new_v4().to_string();
3650        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3651
3652        // This UPDATE is deliberately the transaction's first database access.
3653        // SQLite therefore acquires the writer lock before evaluating the
3654        // cross-cycle counts, making the last quota slot race-free.
3655        let result = sqlx::query(
3656            "UPDATE mandate_decision_cycles AS dc
3657             SET action_attempts = action_attempts + 1, updated_at = ?
3658             WHERE dc.id = ? AND dc.outcome = 'act'
3659               AND dc.mandate_id = ? AND dc.mandate_version = ?
3660               AND dc.goal_run_id = ?
3661               AND dc.action_attempts = ?
3662               AND ? = dc.action_attempts + 1
3663               AND EXISTS (
3664                   SELECT 1
3665                   FROM mandates m
3666                   JOIN goals g ON g.id = m.goal_id
3667                   JOIN goal_runs gr ON gr.id = dc.goal_run_id AND gr.goal_id = m.goal_id
3668                   JOIN intentions i ON i.decision_cycle_id = dc.id
3669                   JOIN tasks root ON root.id = gr.root_task_id AND root.goal_run_id = gr.id
3670                   JOIN task_attempts root_attempt
3671                     ON root_attempt.id = root.current_attempt_id
3672                    AND root_attempt.task_id = root.id
3673                    AND root_attempt.goal_run_id = gr.id
3674                   JOIN tasks worker ON worker.id = ? AND worker.goal_run_id = gr.id
3675                   JOIN task_attempts worker_attempt
3676                     ON worker_attempt.id = worker.current_attempt_id
3677                    AND worker_attempt.task_id = worker.id
3678                    AND worker_attempt.goal_run_id = gr.id
3679                   WHERE m.id = dc.mandate_id
3680                     AND m.owner_principal_id = ?
3681                     AND m.status = 'active' AND g.status = 'active'
3682                     AND m.confirmed_at IS NOT NULL
3683                     AND m.version = dc.mandate_version
3684                     AND gr.trigger_type = 'mandate'
3685                     AND gr.status = 'running'
3686                     AND gr.root_task_id = ?
3687                     AND root.id != worker.id
3688                     AND root.status IN ('claimed', 'running')
3689                     AND root.current_attempt_id = ?
3690                     AND root_attempt.id = ?
3691                     AND root_attempt.status IN ('claimed', 'running')
3692                     AND julianday(root_attempt.lease_expires_at) > julianday(?)
3693                     AND worker.status IN ('claimed', 'running')
3694                     AND worker.current_attempt_id = ?
3695                     AND worker_attempt.id = ?
3696                     AND worker_attempt.status IN ('claimed', 'running')
3697                     AND julianday(worker_attempt.lease_expires_at) > julianday(?)
3698                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
3699                     AND i.status = 'committed' AND i.completed_at IS NULL
3700                     AND dc.action_attempts < CAST(
3701                         COALESCE(json_extract(m.authority_json,
3702                             '$.max_mutating_actions_per_cycle'), 0) AS INTEGER
3703                     )
3704                     AND CAST(COALESCE(json_extract(m.authority_json,
3705                             '$.max_mutating_actions_per_rolling_24h'), 0) AS INTEGER) > 0
3706                     AND (
3707                         SELECT COUNT(*) FROM mandate_mutation_attempts prior
3708                         WHERE prior.mandate_id = m.id
3709                           AND prior.status != 'never_dispatched'
3710                           AND julianday(prior.reserved_at) > julianday(?) - 1.0
3711                     ) < CAST(COALESCE(json_extract(m.authority_json,
3712                             '$.max_mutating_actions_per_rolling_24h'), 0) AS INTEGER)
3713                     AND NOT EXISTS (
3714                         SELECT 1 FROM mandate_mutation_attempts recent
3715                         WHERE recent.mandate_id = m.id
3716                           AND recent.status != 'never_dispatched'
3717                           AND julianday(recent.reserved_at) > julianday(?) -
3718                               (CAST(COALESCE(json_extract(m.authority_json,
3719                                   '$.min_seconds_between_mutations'), 0) AS REAL) / 86400.0)
3720                     )
3721                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
3722               )",
3723        )
3724        .bind(&reserved_at_string)
3725        .bind(&reservation.grant.decision_cycle_id)
3726        .bind(&reservation.grant.mandate_id)
3727        .bind(reservation.grant.mandate_version)
3728        .bind(&reservation.goal_run_id)
3729        .bind(expected_attempts)
3730        .bind(reservation.grant.reserved_action_attempt)
3731        .bind(&reservation.task_id)
3732        .bind(&reservation.grant.owner_principal_id)
3733        .bind(&reservation.root_task_id)
3734        .bind(&reservation.root_task_attempt_id)
3735        .bind(&reservation.root_task_attempt_id)
3736        .bind(&reserved_at_string)
3737        .bind(&reservation.task_attempt_id)
3738        .bind(&reservation.task_attempt_id)
3739        .bind(&reserved_at_string)
3740        .bind(&reserved_at_string)
3741        .bind(&reserved_at_string)
3742        .bind(&reserved_at_string)
3743        .execute(&mut *tx)
3744        .await?;
3745        if result.rows_affected() != 1 {
3746            tx.rollback().await?;
3747            return Ok(None);
3748        }
3749
3750        let intention_id = sqlx::query_scalar::<_, String>(
3751            "SELECT id FROM intentions
3752             WHERE decision_cycle_id = ? AND mandate_id = ? AND goal_run_id = ?
3753               AND status = 'committed' AND completed_at IS NULL",
3754        )
3755        .bind(&reservation.grant.decision_cycle_id)
3756        .bind(&reservation.grant.mandate_id)
3757        .bind(&reservation.goal_run_id)
3758        .fetch_one(&mut *tx)
3759        .await?;
3760
3761        sqlx::query(
3762            "INSERT INTO mandate_mutation_attempts (
3763                id, mandate_id, mandate_version, decision_cycle_id, goal_run_id, intention_id,
3764                root_task_id, root_task_attempt_id, task_id, task_attempt_id,
3765                reserved_action_attempt, action_digest, tool_call_id, tool_name,
3766                mutation_effects_json, targets_json, account_identifiers_json,
3767                status, reserved_at
3768             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'reserved', ?)",
3769        )
3770        .bind(&ledger_id)
3771        .bind(&reservation.grant.mandate_id)
3772        .bind(reservation.grant.mandate_version)
3773        .bind(&reservation.grant.decision_cycle_id)
3774        .bind(&reservation.goal_run_id)
3775        .bind(&intention_id)
3776        .bind(&reservation.root_task_id)
3777        .bind(&reservation.root_task_attempt_id)
3778        .bind(&reservation.task_id)
3779        .bind(&reservation.task_attempt_id)
3780        .bind(reservation.grant.reserved_action_attempt)
3781        .bind(&reservation.grant.action_digest)
3782        .bind(&reservation.tool_call_id)
3783        .bind(&reservation.tool_name)
3784        .bind(&mutation_effects_json)
3785        .bind(&targets_json)
3786        .bind(&account_identifiers_json)
3787        .bind(&reserved_at_string)
3788        .execute(&mut *tx)
3789        .await?;
3790
3791        let query = format!(
3792            "SELECT {MUTATION_ATTEMPT_COLUMNS} FROM mandate_mutation_attempts WHERE id = ?"
3793        );
3794        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
3795            .bind(&ledger_id)
3796            .fetch_one(&mut *tx)
3797            .await?;
3798        let attempt = mutation_attempt_from_row(&row)?;
3799        tx.commit().await?;
3800        Ok(Some(attempt))
3801    }
3802
3803    async fn claim_mandate_mutation_dispatch(
3804        &self,
3805        claim: &MandateMutationDispatchClaim,
3806    ) -> anyhow::Result<bool> {
3807        anyhow::ensure!(
3808            claim.grant.counts_toward_cycle_budget
3809                && claim.grant.mandate_version > 0
3810                && claim.grant.reserved_action_attempt > 0,
3811            "mutation dispatch requires a positive metered grant"
3812        );
3813        validate_canonical_identifier("owner principal id", &claim.grant.owner_principal_id, 256)?;
3814        anyhow::ensure!(
3815            claim.grant.action_digest.len() == 64
3816                && claim
3817                    .grant
3818                    .action_digest
3819                    .bytes()
3820                    .all(|byte| byte.is_ascii_hexdigit()),
3821            "invalid mutation dispatch action digest"
3822        );
3823        anyhow::ensure!(
3824            claim.grant.tool_call_id.as_deref() == Some(claim.tool_call_id.as_str()),
3825            "mutation dispatch tool call does not match its bound grant"
3826        );
3827        for (label, value) in [
3828            ("mandate id", claim.grant.mandate_id.as_str()),
3829            ("decision cycle id", claim.grant.decision_cycle_id.as_str()),
3830            ("goal run id", claim.goal_run_id.as_str()),
3831            ("root task id", claim.root_task_id.as_str()),
3832            ("root task attempt id", claim.root_task_attempt_id.as_str()),
3833            ("task id", claim.task_id.as_str()),
3834            ("task attempt id", claim.task_attempt_id.as_str()),
3835            ("tool call id", claim.tool_call_id.as_str()),
3836            ("tool name", claim.tool_name.as_str()),
3837        ] {
3838            validate_canonical_identifier(label, value, 256)?;
3839        }
3840        anyhow::ensure!(
3841            claim.root_task_id != claim.task_id,
3842            "the mandate deliberator cannot dispatch mutations"
3843        );
3844        validate_timestamp("mutation dispatch claimed_at", &claim.claimed_at)?;
3845
3846        // This single conditional write is the one-use point. Concurrent or
3847        // replayed dispatches cannot both move dispatch_claimed_at from NULL,
3848        // and every mutable lifecycle/lease fact is checked in the same
3849        // writer transaction before adapter I/O begins.
3850        let result = sqlx::query(
3851            "UPDATE mandate_mutation_attempts AS ma
3852             SET dispatch_claimed_at = ?
3853             WHERE ma.mandate_id = ? AND ma.mandate_version = ?
3854               AND ma.decision_cycle_id = ? AND ma.goal_run_id = ?
3855               AND ma.root_task_id = ? AND ma.root_task_attempt_id = ?
3856               AND ma.task_id = ? AND ma.task_attempt_id = ?
3857               AND ma.tool_call_id = ? AND ma.tool_name = ?
3858               AND ma.reserved_action_attempt = ? AND ma.action_digest = ?
3859               AND ma.status = 'reserved' AND ma.dispatch_claimed_at IS NULL
3860               AND EXISTS (
3861                   SELECT 1
3862                   FROM mandates m
3863                   JOIN goals g ON g.id = m.goal_id
3864                   JOIN goal_runs gr ON gr.id = ma.goal_run_id AND gr.goal_id = m.goal_id
3865                   JOIN mandate_decision_cycles dc
3866                     ON dc.id = ma.decision_cycle_id
3867                    AND dc.goal_run_id = gr.id
3868                    AND dc.mandate_id = m.id
3869                   JOIN intentions i
3870                     ON i.id = ma.intention_id
3871                    AND i.decision_cycle_id = dc.id
3872                    AND i.goal_run_id = gr.id
3873                    AND i.mandate_id = m.id
3874                   JOIN tasks root
3875                     ON root.id = ma.root_task_id AND root.goal_run_id = gr.id
3876                   JOIN task_attempts root_attempt
3877                     ON root_attempt.id = ma.root_task_attempt_id
3878                    AND root_attempt.task_id = root.id
3879                    AND root_attempt.goal_run_id = gr.id
3880                   JOIN tasks worker
3881                     ON worker.id = ma.task_id AND worker.goal_run_id = gr.id
3882                   JOIN task_attempts worker_attempt
3883                     ON worker_attempt.id = ma.task_attempt_id
3884                    AND worker_attempt.task_id = worker.id
3885                    AND worker_attempt.goal_run_id = gr.id
3886                   WHERE m.id = ma.mandate_id
3887                     AND m.owner_principal_id = ?
3888                     AND m.version = ma.mandate_version
3889                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
3890                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
3891                     AND g.status = 'active'
3892                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
3893                     AND gr.root_task_id = root.id AND root.id != worker.id
3894                     AND dc.mandate_version = m.version AND dc.outcome = 'act'
3895                     AND dc.action_attempts = ma.reserved_action_attempt
3896                     AND i.status = 'committed' AND i.completed_at IS NULL
3897                     AND root.status IN ('claimed', 'running')
3898                     AND root.current_attempt_id = root_attempt.id
3899                     AND root.error IS NULL AND root.blocker IS NULL
3900                     AND root_attempt.status IN ('claimed', 'running')
3901                     AND julianday(root_attempt.lease_expires_at) > julianday(?)
3902                     AND worker.status IN ('claimed', 'running')
3903                     AND worker.current_attempt_id = worker_attempt.id
3904                     AND worker.error IS NULL AND worker.blocker IS NULL
3905                     AND worker_attempt.status IN ('claimed', 'running')
3906                     AND julianday(worker_attempt.lease_expires_at) > julianday(?)
3907               )",
3908        )
3909        .bind(&claim.claimed_at)
3910        .bind(&claim.grant.mandate_id)
3911        .bind(claim.grant.mandate_version)
3912        .bind(&claim.grant.decision_cycle_id)
3913        .bind(&claim.goal_run_id)
3914        .bind(&claim.root_task_id)
3915        .bind(&claim.root_task_attempt_id)
3916        .bind(&claim.task_id)
3917        .bind(&claim.task_attempt_id)
3918        .bind(&claim.tool_call_id)
3919        .bind(&claim.tool_name)
3920        .bind(claim.grant.reserved_action_attempt)
3921        .bind(&claim.grant.action_digest)
3922        .bind(&claim.grant.owner_principal_id)
3923        .bind(&claim.claimed_at)
3924        .bind(&claim.claimed_at)
3925        .bind(&claim.claimed_at)
3926        .execute(self.work_pool())
3927        .await?;
3928        Ok(result.rows_affected() == 1)
3929    }
3930
3931    async fn get_mandate_mutation_quota_state(
3932        &self,
3933        mandate_id: &str,
3934        as_of: &str,
3935    ) -> anyhow::Result<Option<MandateMutationQuotaState>> {
3936        validate_canonical_identifier("mandate id", mandate_id, 256)?;
3937        let mut connection = self.work_pool().acquire().await?;
3938        mutation_quota_state_on_connection(&mut connection, mandate_id, as_of).await
3939    }
3940
3941    async fn list_mandate_mutation_attempts_for_run(
3942        &self,
3943        goal_run_id: &str,
3944    ) -> anyhow::Result<Vec<MandateMutationAttempt>> {
3945        validate_canonical_identifier("goal run id", goal_run_id, 256)?;
3946        let query = format!(
3947            "SELECT {MUTATION_ATTEMPT_COLUMNS} FROM mandate_mutation_attempts
3948             WHERE goal_run_id = ? ORDER BY julianday(reserved_at), id"
3949        );
3950        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3951            .bind(goal_run_id)
3952            .fetch_all(self.work_pool())
3953            .await?;
3954        rows.iter().map(mutation_attempt_from_row).collect()
3955    }
3956
3957    async fn finalize_mandate_run_from_proof(
3958        &self,
3959        request: &MandateRunFinalizationRequest,
3960    ) -> anyhow::Result<MandateRunFinalizationResult> {
3961        if validate_canonical_identifier("mandate id", &request.mandate_id, 256).is_err()
3962            || validate_canonical_identifier("goal run id", &request.goal_run_id, 256).is_err()
3963            || request.expected_mandate_version <= 0
3964            || validate_timestamp("mandate finalization timestamp", &request.finalized_at).is_err()
3965        {
3966            return Ok(MandateRunFinalizationResult::Rejected {
3967                reason: MandateFinalizationRejectReason::InvalidRequest,
3968            });
3969        }
3970
3971        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3972        // Acquire SQLite's writer lock before reading the proof snapshot. All
3973        // subsequent task, ledger, policy, and lifecycle checks therefore
3974        // linearize with owner updates and worker finalization writes.
3975        let fenced = sqlx::query(
3976            "UPDATE goal_runs SET updated_at = updated_at
3977             WHERE id = ? AND trigger_type = 'mandate' AND status = 'running'",
3978        )
3979        .bind(&request.goal_run_id)
3980        .execute(&mut *tx)
3981        .await?;
3982        if fenced.rows_affected() != 1 {
3983            tx.rollback().await?;
3984            return Ok(MandateRunFinalizationResult::Stale {
3985                reason: MandateFinalizationStaleReason::RunNotCurrent,
3986            });
3987        }
3988
3989        let row = sqlx::query(
3990            "SELECT m.version AS mandate_version, m.status AS mandate_status,
3991                    m.min_review_secs AS min_review_secs,
3992                    m.max_review_secs AS max_review_secs,
3993                    g.session_id AS owner_session_id,
3994                    g.dispatch_failures AS review_failures,
3995                    gr.goal_id AS goal_id, gr.root_task_id AS root_task_id,
3996                    dc.id AS decision_cycle_id, dc.mandate_version AS decision_version,
3997                    dc.outcome AS decision_outcome, dc.origin AS decision_origin,
3998                    dc.action_attempts AS decision_action_attempts
3999             FROM goal_runs gr
4000             JOIN mandates m ON m.goal_id = gr.goal_id
4001             JOIN goals g ON g.id = gr.goal_id
4002             LEFT JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
4003             WHERE gr.id = ? AND m.id = ?",
4004        )
4005        .bind(&request.goal_run_id)
4006        .bind(&request.mandate_id)
4007        .fetch_optional(&mut *tx)
4008        .await?;
4009        let Some(row) = row else {
4010            tx.rollback().await?;
4011            return Ok(MandateRunFinalizationResult::Stale {
4012                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4013            });
4014        };
4015        let mandate_version: i64 = row.get("mandate_version");
4016        let min_review_secs: i64 = row.get("min_review_secs");
4017        let max_review_secs: i64 = row.get("max_review_secs");
4018        let review_failures: i32 = row.get("review_failures");
4019        let goal_id: String = row.get("goal_id");
4020        let owner_session_id: String = row.get("owner_session_id");
4021        if mandate_version != request.expected_mandate_version {
4022            tx.rollback().await?;
4023            return Ok(MandateRunFinalizationResult::Stale {
4024                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4025            });
4026        }
4027        let open_run_count: i64 = sqlx::query_scalar(
4028            "SELECT COUNT(*) FROM goal_runs
4029             WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')",
4030        )
4031        .bind(&goal_id)
4032        .fetch_one(&mut *tx)
4033        .await?;
4034        if open_run_count != 1 {
4035            tx.rollback().await?;
4036            return Ok(MandateRunFinalizationResult::Stale {
4037                reason: MandateFinalizationStaleReason::RunNotCurrent,
4038            });
4039        }
4040
4041        macro_rules! close_review_failed_retry {
4042            ($reason:expr) => {{
4043                let reason = $reason;
4044                let (intention_from, intention_to) =
4045                    intention_transition(IntentionStatus::Committed, IntentionStatus::Failed)?;
4046                sqlx::query(
4047                    "UPDATE intentions
4048                     SET status = ?, updated_at = ?, completed_at = ?
4049                     WHERE goal_run_id = ? AND status = ?",
4050                )
4051                .bind(intention_to)
4052                .bind(&request.finalized_at)
4053                .bind(&request.finalized_at)
4054                .bind(&request.goal_run_id)
4055                .bind(intention_from)
4056                .execute(&mut *tx)
4057                .await?;
4058                sqlx::query(
4059                    "UPDATE task_attempts
4060                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4061                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4062                )
4063                .bind(&request.finalized_at)
4064                .bind(&request.goal_run_id)
4065                .execute(&mut *tx)
4066                .await?;
4067                sqlx::query(
4068                    "UPDATE tasks
4069                     SET status = 'cancelled', current_attempt_id = NULL,
4070                         completed_at = COALESCE(completed_at, ?), updated_at = ?,
4071                         version = version + 1
4072                     WHERE goal_run_id = ?
4073                       AND status IN ('pending', 'claimed', 'running', 'blocked')",
4074                )
4075                .bind(&request.finalized_at)
4076                .bind(&request.finalized_at)
4077                .bind(&request.goal_run_id)
4078                .execute(&mut *tx)
4079                .await?;
4080                let run_updated = sqlx::query(
4081                    "UPDATE goal_runs
4082                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4083                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4084                )
4085                .bind(format!("mandate_review_failed:{}", reason.as_str()))
4086                .bind(&request.finalized_at)
4087                .bind(&request.finalized_at)
4088                .bind(&request.goal_run_id)
4089                .execute(&mut *tx)
4090                .await?;
4091                let finalized_at = chrono::DateTime::parse_from_rfc3339(&request.finalized_at)
4092                    .expect("validated mandate finalization timestamp")
4093                    .with_timezone(&chrono::Utc);
4094                let next_review_failures = review_failures.saturating_add(1);
4095                let backoff_shift = u32::try_from(next_review_failures.saturating_sub(1))
4096                    .unwrap_or(0)
4097                    .min(6);
4098                let retry_delay_secs = min_review_secs
4099                    .saturating_mul(1_i64 << backoff_shift)
4100                    .min(max_review_secs);
4101                let retry_at =
4102                    (finalized_at + chrono::Duration::seconds(retry_delay_secs)).to_rfc3339();
4103                let mandate_updated = sqlx::query(
4104                    "UPDATE mandates
4105                     SET next_review_at = ?, review_lease_token = NULL,
4106                         review_lease_expires_at = NULL, updated_at = ?
4107                     WHERE id = ? AND version = ? AND status = 'active'",
4108                )
4109                .bind(&retry_at)
4110                .bind(&request.finalized_at)
4111                .bind(&request.mandate_id)
4112                .bind(request.expected_mandate_version)
4113                .execute(&mut *tx)
4114                .await?;
4115                anyhow::ensure!(
4116                    run_updated.rows_affected() == 1 && mandate_updated.rows_affected() == 1,
4117                    "mandate review-failure retry state changed during finalization"
4118                );
4119                update_controller_status(
4120                    &mut tx,
4121                    &goal_id,
4122                    MandateStatus::Active,
4123                    &request.finalized_at,
4124                )
4125                .await?;
4126                sqlx::query(
4127                    "UPDATE goals SET dispatch_failures = ?, updated_at = ? WHERE id = ?",
4128                )
4129                .bind(next_review_failures)
4130                .bind(&request.finalized_at)
4131                .bind(&goal_id)
4132                .execute(&mut *tx)
4133                .await?;
4134                if crate::mandates::review_failure_is_notified(i64::from(next_review_failures)) {
4135                    let notice = crate::traits::MandateRunNotification::new(
4136                        &request.mandate_id,
4137                        request.expected_mandate_version,
4138                        &goal_id,
4139                        &request.goal_run_id,
4140                        &owner_session_id,
4141                        crate::traits::MandateRunNotificationKind::ReviewFailed { reason },
4142                        crate::traits::MandateRunProofCounts::default(),
4143                        &request.finalized_at,
4144                    );
4145                    super::notifications::enqueue_mandate_run_notification_on_connection(
4146                        &mut *tx,
4147                        &notice,
4148                    )
4149                    .await?;
4150                }
4151                tx.commit().await?;
4152                return Ok(MandateRunFinalizationResult::Rejected { reason });
4153            }};
4154        }
4155
4156        macro_rules! close_invalid_decision_state {
4157            () => {{
4158                let reason = MandateFinalizationRejectReason::InvalidDecisionState;
4159                sqlx::query(
4160                    "UPDATE mandate_mutation_attempts
4161                     SET status = CASE
4162                             WHEN dispatch_claimed_at IS NULL THEN 'never_dispatched'
4163                             ELSE 'ambiguous'
4164                         END,
4165                         completed_at = COALESCE(completed_at, ?)
4166                     WHERE goal_run_id = ? AND mandate_id = ? AND status = 'reserved'",
4167                )
4168                .bind(&request.finalized_at)
4169                .bind(&request.goal_run_id)
4170                .bind(&request.mandate_id)
4171                .execute(&mut *tx)
4172                .await?;
4173                sqlx::query(
4174                    "UPDATE task_attempts
4175                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4176                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4177                )
4178                .bind(&request.finalized_at)
4179                .bind(&request.goal_run_id)
4180                .execute(&mut *tx)
4181                .await?;
4182                sqlx::query(
4183                    "UPDATE tasks
4184                     SET status = 'cancelled', current_attempt_id = NULL,
4185                         completed_at = COALESCE(completed_at, ?), updated_at = ?,
4186                         version = version + 1
4187                     WHERE goal_run_id = ?
4188                       AND status IN ('pending', 'claimed', 'running', 'blocked')",
4189                )
4190                .bind(&request.finalized_at)
4191                .bind(&request.finalized_at)
4192                .bind(&request.goal_run_id)
4193                .execute(&mut *tx)
4194                .await?;
4195                let (intention_from, intention_to) = intention_transition(
4196                    IntentionStatus::Committed,
4197                    IntentionStatus::Suspended,
4198                )?;
4199                sqlx::query(
4200                    "UPDATE intentions
4201                     SET status = ?, updated_at = ?, completed_at = ?
4202                     WHERE goal_run_id = ? AND status = ?",
4203                )
4204                .bind(intention_to)
4205                .bind(&request.finalized_at)
4206                .bind(&request.finalized_at)
4207                .bind(&request.goal_run_id)
4208                .bind(intention_from)
4209                .execute(&mut *tx)
4210                .await?;
4211                let run_updated = sqlx::query(
4212                    "UPDATE goal_runs
4213                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4214                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4215                )
4216                .bind(format!("mandate_review_failed:{}", reason.as_str()))
4217                .bind(&request.finalized_at)
4218                .bind(&request.finalized_at)
4219                .bind(&request.goal_run_id)
4220                .execute(&mut *tx)
4221                .await?;
4222                let mut suspension = MandateSuspension::new(
4223                    MandateSuspensionKind::ReviewFailed,
4224                    Some(reason.as_str().to_string()),
4225                );
4226                suspension.goal_run_id = Some(request.goal_run_id.clone());
4227                let mandate_updated = sqlx::query(
4228                    "UPDATE mandates
4229                     SET status = 'awaiting_input', review_lease_token = NULL,
4230                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4231                     WHERE id = ? AND version = ? AND status = 'active'",
4232                )
4233                .bind(serde_json::to_string(&suspension)?)
4234                .bind(&request.finalized_at)
4235                .bind(&request.mandate_id)
4236                .bind(request.expected_mandate_version)
4237                .execute(&mut *tx)
4238                .await?;
4239                anyhow::ensure!(
4240                    run_updated.rows_affected() == 1 && mandate_updated.rows_affected() == 1,
4241                    "invalid mandate decision state changed during finalization"
4242                );
4243                update_controller_status(
4244                    &mut tx,
4245                    &goal_id,
4246                    MandateStatus::AwaitingInput,
4247                    &request.finalized_at,
4248                )
4249                .await?;
4250                let notice = crate::traits::MandateRunNotification::new(
4251                    &request.mandate_id,
4252                    request.expected_mandate_version,
4253                    &goal_id,
4254                    &request.goal_run_id,
4255                    &owner_session_id,
4256                    crate::traits::MandateRunNotificationKind::ReviewFailed { reason },
4257                    crate::traits::MandateRunProofCounts::default(),
4258                    &request.finalized_at,
4259                );
4260                super::notifications::enqueue_mandate_run_notification_on_connection(
4261                    &mut *tx,
4262                    &notice,
4263                )
4264                .await?;
4265                tx.commit().await?;
4266                return Ok(MandateRunFinalizationResult::Rejected { reason });
4267            }};
4268        }
4269        let decision_cycle_id: Option<String> = row.get("decision_cycle_id");
4270        let decision_version: Option<i64> = row.get("decision_version");
4271        let decision_outcome_raw: Option<String> = row.get("decision_outcome");
4272        let decision_origin = row
4273            .get::<Option<String>, _>("decision_origin")
4274            .as_deref()
4275            .and_then(MandateDecisionOrigin::parse);
4276        let decision_action_attempts: Option<i64> = row.get("decision_action_attempts");
4277        let (Some(decision_cycle_id), Some(decision_version), Some(decision_outcome_raw)) =
4278            (decision_cycle_id, decision_version, decision_outcome_raw)
4279        else {
4280            close_review_failed_retry!(MandateFinalizationRejectReason::DecisionMissing);
4281        };
4282        if decision_version != mandate_version {
4283            tx.rollback().await?;
4284            return Ok(MandateRunFinalizationResult::Stale {
4285                reason: MandateFinalizationStaleReason::DecisionVersionChanged,
4286            });
4287        }
4288        let Some(decision_outcome) = MandateDecisionOutcome::parse(&decision_outcome_raw) else {
4289            close_invalid_decision_state!();
4290        };
4291        if decision_origin == Some(MandateDecisionOrigin::RuntimeFallback) {
4292            close_review_failed_retry!(MandateFinalizationRejectReason::DeliberatorFailed);
4293        }
4294        let Some(decision_action_attempts) = decision_action_attempts else {
4295            close_invalid_decision_state!();
4296        };
4297        let mandate_status_raw: String = row.get("mandate_status");
4298        let Some(mandate_status) = MandateStatus::parse(&mandate_status_raw) else {
4299            close_invalid_decision_state!();
4300        };
4301        let expected_status = MandateStatus::Active;
4302        if mandate_status != expected_status {
4303            tx.rollback().await?;
4304            return Ok(MandateRunFinalizationResult::Stale {
4305                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4306            });
4307        }
4308
4309        let root_task_id: Option<String> = row.get("root_task_id");
4310        let root_success = if let Some(root_task_id) = root_task_id.as_deref() {
4311            sqlx::query_scalar::<_, i64>(
4312                "SELECT COUNT(*) FROM tasks
4313                 WHERE id = ? AND goal_run_id = ? AND status = 'completed'
4314                   AND COALESCE(NULLIF(trim(error), ''), '') = ''
4315                   AND COALESCE(NULLIF(trim(blocker), ''), '') = ''",
4316            )
4317            .bind(root_task_id)
4318            .bind(&request.goal_run_id)
4319            .fetch_one(&mut *tx)
4320            .await?
4321                == 1
4322        } else {
4323            false
4324        };
4325
4326        // Before the task counts: a worker refused before dispatch did not do
4327        // its work, whatever status it closed with.
4328        let reserved_mutations: i64 = sqlx::query_scalar(
4329            "SELECT COUNT(*) FROM mandate_mutation_attempts
4330             WHERE goal_run_id = ? AND mandate_id = ?",
4331        )
4332        .bind(&request.goal_run_id)
4333        .bind(&request.mandate_id)
4334        .fetch_one(&mut *tx)
4335        .await?;
4336        let refused_by =
4337            if decision_outcome == MandateDecisionOutcome::Act && reserved_mutations == 0 {
4338                block_worker_refused_before_dispatch(
4339                    &mut tx,
4340                    &request.goal_run_id,
4341                    root_task_id.as_deref().unwrap_or(""),
4342                    &request.finalized_at,
4343                )
4344                .await?
4345            } else {
4346                None
4347            };
4348
4349        let task_counts = sqlx::query(
4350            "SELECT COUNT(*) AS total,
4351                    COALESCE(SUM(CASE WHEN status = 'completed'
4352                        AND COALESCE(NULLIF(trim(error), ''), '') = ''
4353                        AND COALESCE(NULLIF(trim(blocker), ''), '') = ''
4354                        THEN 1 ELSE 0 END), 0) AS completed,
4355                    COALESCE(SUM(CASE WHEN status IN ('failed', 'blocked', 'interrupted')
4356                        OR COALESCE(NULLIF(trim(error), ''), '') != ''
4357                        OR COALESCE(NULLIF(trim(blocker), ''), '') != ''
4358                        THEN 1 ELSE 0 END), 0) AS failed_or_blocked
4359             FROM tasks WHERE goal_run_id = ? AND id != ?",
4360        )
4361        .bind(&request.goal_run_id)
4362        .bind(root_task_id.as_deref().unwrap_or(""))
4363        .fetch_one(&mut *tx)
4364        .await?;
4365        let non_root_tasks: i64 = task_counts.get("total");
4366        let completed_tasks: i64 = task_counts.get("completed");
4367        let failed_or_blocked_tasks: i64 = task_counts.get("failed_or_blocked");
4368
4369        // Close any crash window between durable reservation, the one-use
4370        // final-dispatch claim, and strict receipt projection before proving
4371        // the run. Unclaimed rows prove no adapter I/O was authorized; claimed
4372        // rows without a receipt are necessarily ambiguous.
4373        sqlx::query(
4374            "UPDATE mandate_mutation_attempts
4375             SET status = CASE
4376                     WHEN dispatch_claimed_at IS NULL THEN 'never_dispatched'
4377                     ELSE 'ambiguous'
4378                 END,
4379                 completed_at = COALESCE(completed_at, ?)
4380             WHERE goal_run_id = ? AND mandate_id = ? AND status = 'reserved'",
4381        )
4382        .bind(&request.finalized_at)
4383        .bind(&request.goal_run_id)
4384        .bind(&request.mandate_id)
4385        .execute(&mut *tx)
4386        .await?;
4387
4388        let mutation_counts = sqlx::query(
4389            "SELECT COUNT(*) AS total,
4390                    COALESCE(SUM(CASE WHEN status = 'succeeded' THEN 1 ELSE 0 END), 0) AS succeeded,
4391                    COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) AS failed,
4392                    COALESCE(SUM(CASE WHEN status = 'never_dispatched' THEN 1 ELSE 0 END), 0)
4393                        AS never_dispatched,
4394                    COALESCE(SUM(CASE WHEN status = 'ambiguous' THEN 1 ELSE 0 END), 0)
4395                        AS ambiguous,
4396                    COALESCE(SUM(CASE WHEN mandate_version != ? OR decision_cycle_id != ?
4397                        THEN 1 ELSE 0 END), 0) AS mismatched
4398             FROM mandate_mutation_attempts
4399             WHERE goal_run_id = ? AND mandate_id = ?",
4400        )
4401        .bind(mandate_version)
4402        .bind(&decision_cycle_id)
4403        .bind(&request.goal_run_id)
4404        .bind(&request.mandate_id)
4405        .fetch_one(&mut *tx)
4406        .await?;
4407        let mutation_total: i64 = mutation_counts.get("total");
4408        let mutation_succeeded: i64 = mutation_counts.get("succeeded");
4409        let mutation_failed: i64 = mutation_counts.get("failed");
4410        let mutation_never_dispatched: i64 = mutation_counts.get("never_dispatched");
4411        let mutation_ambiguous: i64 = mutation_counts.get("ambiguous");
4412        let mutation_mismatched: i64 = mutation_counts.get("mismatched");
4413        let count = |value: i64| u32::try_from(value.max(0)).unwrap_or(u32::MAX);
4414        let counts = MandateRunProofCounts {
4415            non_root_tasks: count(non_root_tasks),
4416            completed_tasks: count(completed_tasks),
4417            incomplete_tasks: count(non_root_tasks.saturating_sub(completed_tasks)),
4418            failed_or_blocked_tasks: count(failed_or_blocked_tasks),
4419            mutation_reservations: count(mutation_total),
4420            succeeded_mutations: count(mutation_succeeded),
4421            failed_mutations: count(mutation_failed),
4422            never_dispatched_mutations: count(mutation_never_dispatched),
4423            ambiguous_or_reserved_mutations: count(mutation_ambiguous),
4424        };
4425        macro_rules! reconcile_fail_closed {
4426            ($reason:expr) => {{
4427                let reason = $reason;
4428                sqlx::query(
4429                    "UPDATE task_attempts
4430                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4431                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4432                )
4433                .bind(&request.finalized_at)
4434                .bind(&request.goal_run_id)
4435                .execute(&mut *tx)
4436                .await?;
4437                sqlx::query(
4438                    "UPDATE tasks
4439                     SET status = 'cancelled', current_attempt_id = NULL,
4440                         completed_at = COALESCE(completed_at, ?), updated_at = ?, version = version + 1
4441                     WHERE goal_run_id = ? AND status IN ('pending', 'claimed', 'running')",
4442                )
4443                .bind(&request.finalized_at)
4444                .bind(&request.finalized_at)
4445                .bind(&request.goal_run_id)
4446                .execute(&mut *tx)
4447                .await?;
4448                let (intention_from, intention_to) = intention_transition(
4449                    IntentionStatus::Committed,
4450                    IntentionStatus::Suspended,
4451                )?;
4452                sqlx::query(
4453                    "UPDATE intentions
4454                     SET status = ?, updated_at = ?, completed_at = ?
4455                     WHERE goal_run_id = ? AND status = ?",
4456                )
4457                .bind(intention_to)
4458                .bind(&request.finalized_at)
4459                .bind(&request.finalized_at)
4460                .bind(&request.goal_run_id)
4461                .bind(intention_from)
4462                .execute(&mut *tx)
4463                .await?;
4464                let run_updated = sqlx::query(
4465                    "UPDATE goal_runs
4466                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4467                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4468                )
4469                .bind(format!("mandate_reconciliation_required:{}", reason.as_str()))
4470                .bind(&request.finalized_at)
4471                .bind(&request.finalized_at)
4472                .bind(&request.goal_run_id)
4473                .execute(&mut *tx)
4474                .await?;
4475                let mut suspension = MandateSuspension::new(
4476                    MandateSuspensionKind::ReconciliationRequired,
4477                    Some(reason.as_str().to_string()),
4478                );
4479                suspension.decision_cycle_id = Some(decision_cycle_id.clone());
4480                suspension.goal_run_id = Some(request.goal_run_id.clone());
4481                let mandate_updated = sqlx::query(
4482                    "UPDATE mandates
4483                     SET status = 'awaiting_input', review_lease_token = NULL,
4484                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4485                     WHERE id = ? AND version = ? AND status = ?",
4486                )
4487                .bind(serde_json::to_string(&suspension)?)
4488                .bind(&request.finalized_at)
4489                .bind(&request.mandate_id)
4490                .bind(request.expected_mandate_version)
4491                .bind(expected_status.as_str())
4492                .execute(&mut *tx)
4493                .await?;
4494                if run_updated.rows_affected() != 1 || mandate_updated.rows_affected() != 1 {
4495                    tx.rollback().await?;
4496                    return Ok(MandateRunFinalizationResult::Stale {
4497                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4498                    });
4499                }
4500                update_controller_status(
4501                    &mut tx,
4502                    &goal_id,
4503                    MandateStatus::AwaitingInput,
4504                    &request.finalized_at,
4505                )
4506                .await?;
4507                let notice = crate::traits::MandateRunNotification::new(
4508                    &request.mandate_id,
4509                    request.expected_mandate_version,
4510                    &goal_id,
4511                    &request.goal_run_id,
4512                    &owner_session_id,
4513                    crate::traits::MandateRunNotificationKind::ReconciliationRequired { reason },
4514                    counts.clone(),
4515                    &request.finalized_at,
4516                );
4517                super::notifications::enqueue_mandate_run_notification_on_connection(
4518                    &mut *tx,
4519                    &notice,
4520                )
4521                .await?;
4522                tx.commit().await?;
4523                return Ok(MandateRunFinalizationResult::ReconciliationRequired {
4524                    reason,
4525                    counts: counts.clone(),
4526                });
4527            }};
4528        }
4529        if let Some(gate) = refused_by {
4530            reconcile_fail_closed!(MandateReconciliationReason::ActBlockedBeforeDispatch { gate });
4531        }
4532        // Every external effect of an ACT goes through a mutation
4533        // reservation. When none succeeded, none has an unknown outcome and
4534        // none belongs to another decision, the ledger proves the review
4535        // changed nothing: retry it rather than ask the owner to confirm
4536        // what is already known.
4537        if decision_outcome == MandateDecisionOutcome::Act
4538            && mutation_succeeded == 0
4539            && mutation_ambiguous == 0
4540            && mutation_mismatched == 0
4541        {
4542            close_review_failed_retry!(MandateFinalizationRejectReason::ActChangedNothing);
4543        }
4544        if !root_success {
4545            reconcile_fail_closed!(MandateReconciliationReason::RootTaskNotSuccessful);
4546        }
4547
4548        match decision_outcome {
4549            MandateDecisionOutcome::Act => {
4550                let intention_id = sqlx::query_scalar::<_, String>(
4551                    "SELECT id FROM intentions
4552                     WHERE mandate_id = ? AND decision_cycle_id = ? AND goal_run_id = ?
4553                       AND status = 'committed' AND completed_at IS NULL",
4554                )
4555                .bind(&request.mandate_id)
4556                .bind(&decision_cycle_id)
4557                .bind(&request.goal_run_id)
4558                .fetch_optional(&mut *tx)
4559                .await?;
4560                let Some(intention_id) = intention_id else {
4561                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingIntention);
4562                };
4563                if non_root_tasks == 0 {
4564                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingWorkTask);
4565                }
4566                if completed_tasks != non_root_tasks || failed_or_blocked_tasks > 0 {
4567                    reconcile_fail_closed!(MandateReconciliationReason::WorkTasksIncomplete);
4568                }
4569                if mutation_mismatched > 0 || decision_action_attempts != mutation_total {
4570                    reconcile_fail_closed!(MandateReconciliationReason::ActionLedgerMismatch);
4571                }
4572                if mutation_failed > 0 {
4573                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeFailed);
4574                }
4575                if mutation_never_dispatched > 0 {
4576                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeFailed);
4577                }
4578                if mutation_ambiguous > 0 {
4579                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeAmbiguous);
4580                }
4581                if mutation_succeeded == 0 {
4582                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingVerifiedMutation);
4583                }
4584                let (intention_from, intention_to) =
4585                    intention_transition(IntentionStatus::Committed, IntentionStatus::Satisfied)?;
4586                let intention_updated = sqlx::query(
4587                    "UPDATE intentions SET status = ?, updated_at = ?, completed_at = ?
4588                     WHERE id = ? AND status = ? AND completed_at IS NULL",
4589                )
4590                .bind(intention_to)
4591                .bind(&request.finalized_at)
4592                .bind(&request.finalized_at)
4593                .bind(&intention_id)
4594                .bind(intention_from)
4595                .execute(&mut *tx)
4596                .await?;
4597                if intention_updated.rows_affected() != 1 {
4598                    tx.rollback().await?;
4599                    return Ok(MandateRunFinalizationResult::Stale {
4600                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4601                    });
4602                }
4603                let run_updated = sqlx::query(
4604                    "UPDATE goal_runs
4605                     SET status = 'completed', outcome_summary = 'mandate_act_satisfied',
4606                         completed_at = ?, updated_at = ?
4607                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4608                )
4609                .bind(&request.finalized_at)
4610                .bind(&request.finalized_at)
4611                .bind(&request.goal_run_id)
4612                .execute(&mut *tx)
4613                .await?;
4614                if run_updated.rows_affected() != 1 {
4615                    tx.rollback().await?;
4616                    return Ok(MandateRunFinalizationResult::Stale {
4617                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4618                    });
4619                }
4620                let notice = crate::traits::MandateRunNotification::new(
4621                    &request.mandate_id,
4622                    request.expected_mandate_version,
4623                    &goal_id,
4624                    &request.goal_run_id,
4625                    &owner_session_id,
4626                    crate::traits::MandateRunNotificationKind::ActSatisfied,
4627                    counts.clone(),
4628                    &request.finalized_at,
4629                );
4630                super::notifications::enqueue_mandate_run_notification_on_connection(
4631                    &mut tx, &notice,
4632                )
4633                .await?;
4634                sqlx::query("UPDATE goals SET dispatch_failures = 0, updated_at = ? WHERE id = ?")
4635                    .bind(&request.finalized_at)
4636                    .bind(&goal_id)
4637                    .execute(&mut *tx)
4638                    .await?;
4639                tx.commit().await?;
4640                Ok(MandateRunFinalizationResult::ActSatisfied { counts })
4641            }
4642            MandateDecisionOutcome::Wait
4643            | MandateDecisionOutcome::Ask
4644            | MandateDecisionOutcome::Stop => {
4645                if non_root_tasks != 0 {
4646                    reconcile_fail_closed!(MandateReconciliationReason::NonActionCreatedWork);
4647                }
4648                if mutation_total != 0 || decision_action_attempts != 0 {
4649                    reconcile_fail_closed!(MandateReconciliationReason::NonActionReservedMutation);
4650                }
4651                let intention_count: i64 = sqlx::query_scalar(
4652                    "SELECT COUNT(*) FROM intentions
4653                     WHERE mandate_id = ? AND decision_cycle_id = ? AND goal_run_id = ?",
4654                )
4655                .bind(&request.mandate_id)
4656                .bind(&decision_cycle_id)
4657                .bind(&request.goal_run_id)
4658                .fetch_one(&mut *tx)
4659                .await?;
4660                if intention_count != 0 {
4661                    close_invalid_decision_state!();
4662                }
4663                let final_mandate_status = match decision_outcome {
4664                    MandateDecisionOutcome::Wait => MandateStatus::Active,
4665                    MandateDecisionOutcome::Ask => MandateStatus::AwaitingInput,
4666                    MandateDecisionOutcome::Stop => MandateStatus::Completed,
4667                    MandateDecisionOutcome::Act => unreachable!(),
4668                };
4669                let suspension = (decision_outcome == MandateDecisionOutcome::Ask).then(|| {
4670                    let mut value = MandateSuspension::new(
4671                        MandateSuspensionKind::AwaitingAnswer,
4672                        Some("agent_question".to_string()),
4673                    );
4674                    value.decision_cycle_id = Some(decision_cycle_id.clone());
4675                    value.goal_run_id = Some(request.goal_run_id.clone());
4676                    value
4677                });
4678                let mandate_updated = sqlx::query(
4679                    "UPDATE mandates
4680                     SET status = ?, review_lease_token = NULL,
4681                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4682                     WHERE id = ? AND version = ? AND status = 'active'",
4683                )
4684                .bind(final_mandate_status.as_str())
4685                .bind(suspension.as_ref().map(serde_json::to_string).transpose()?)
4686                .bind(&request.finalized_at)
4687                .bind(&request.mandate_id)
4688                .bind(request.expected_mandate_version)
4689                .execute(&mut *tx)
4690                .await?;
4691                if mandate_updated.rows_affected() != 1 {
4692                    tx.rollback().await?;
4693                    return Ok(MandateRunFinalizationResult::Stale {
4694                        reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4695                    });
4696                }
4697                update_controller_status(
4698                    &mut tx,
4699                    &goal_id,
4700                    final_mandate_status,
4701                    &request.finalized_at,
4702                )
4703                .await?;
4704                sqlx::query("UPDATE goals SET dispatch_failures = 0, updated_at = ? WHERE id = ?")
4705                    .bind(&request.finalized_at)
4706                    .bind(&goal_id)
4707                    .execute(&mut *tx)
4708                    .await?;
4709                let run_updated = sqlx::query(
4710                    "UPDATE goal_runs
4711                     SET status = 'completed', outcome_summary = 'mandate_non_action_satisfied',
4712                         completed_at = ?, updated_at = ?
4713                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4714                )
4715                .bind(&request.finalized_at)
4716                .bind(&request.finalized_at)
4717                .bind(&request.goal_run_id)
4718                .execute(&mut *tx)
4719                .await?;
4720                if run_updated.rows_affected() != 1 {
4721                    tx.rollback().await?;
4722                    return Ok(MandateRunFinalizationResult::Stale {
4723                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4724                    });
4725                }
4726                let owner_alert = if decision_outcome == MandateDecisionOutcome::Wait {
4727                    sqlx::query_scalar::<_, Option<String>>(
4728                        "SELECT owner_alert FROM mandate_decision_cycles WHERE id = ?",
4729                    )
4730                    .bind(&decision_cycle_id)
4731                    .fetch_optional(&mut *tx)
4732                    .await?
4733                    .flatten()
4734                } else {
4735                    None
4736                };
4737                if let Some(kind) = match decision_outcome {
4738                    MandateDecisionOutcome::Wait => owner_alert
4739                        .is_some()
4740                        .then_some(crate::traits::MandateRunNotificationKind::Alert),
4741                    MandateDecisionOutcome::Ask => {
4742                        Some(crate::traits::MandateRunNotificationKind::Ask)
4743                    }
4744                    MandateDecisionOutcome::Stop => {
4745                        Some(crate::traits::MandateRunNotificationKind::Stopped)
4746                    }
4747                    MandateDecisionOutcome::Act => unreachable!(),
4748                } {
4749                    let question = if decision_outcome == MandateDecisionOutcome::Ask {
4750                        sqlx::query_scalar::<_, Option<String>>(
4751                            "SELECT question FROM mandate_decision_cycles WHERE id = ?",
4752                        )
4753                        .bind(&decision_cycle_id)
4754                        .fetch_optional(&mut *tx)
4755                        .await?
4756                        .flatten()
4757                    } else {
4758                        None
4759                    };
4760                    let notice = crate::traits::MandateRunNotification::new(
4761                        &request.mandate_id,
4762                        request.expected_mandate_version,
4763                        &goal_id,
4764                        &request.goal_run_id,
4765                        &owner_session_id,
4766                        kind,
4767                        counts.clone(),
4768                        &request.finalized_at,
4769                    )
4770                    .with_owner_question(question.as_deref())
4771                    .with_owner_alert(owner_alert.as_deref());
4772                    super::notifications::enqueue_mandate_run_notification_on_connection(
4773                        &mut tx, &notice,
4774                    )
4775                    .await?;
4776                }
4777                tx.commit().await?;
4778                Ok(MandateRunFinalizationResult::NonActionSatisfied {
4779                    outcome: decision_outcome,
4780                    counts,
4781                })
4782            }
4783        }
4784    }
4785}
4786
4787#[cfg(test)]
4788mod tests {
4789    use super::*;
4790    use crate::traits::*;
4791    use crate::traits::{
4792        Goal, Intention, Mandate, MandateAuthority, MandateDecisionCycle, MandateMutationTarget,
4793        MandateObjectiveControl, MandateOperationKind, MandateOperationScope,
4794        MandateWakeSignalKind, ObjectiveMetricDirection, Task, ToolCallOperation,
4795    };
4796    use std::sync::Arc;
4797
4798    async fn test_store() -> (SqliteWorkStore, tempfile::NamedTempFile) {
4799        let database = tempfile::NamedTempFile::new().unwrap();
4800        let store = open_for_tests(database.path().to_str().unwrap()).await;
4801        (store, database)
4802    }
4803
4804    fn authority(max_actions: u32) -> MandateAuthority {
4805        MandateAuthority {
4806            allowed_tools: vec!["http_request".to_string()],
4807            allowed_mutation_effects: vec!["external_delivery".to_string()],
4808            allowed_target_prefixes: vec!["https://api.x.com/2/".to_string()],
4809            max_mutating_actions_per_cycle: max_actions,
4810            max_mutating_actions_per_rolling_24h: if max_actions == 0 { 0 } else { 24 },
4811            min_seconds_between_mutations: if max_actions == 0 { 0 } else { 900 },
4812            ..MandateAuthority::default()
4813        }
4814    }
4815
4816    fn controller(session_id: &str, max_actions: u32) -> (Goal, Mandate) {
4817        let goal = Goal::new_continuous(
4818            "Steward the account",
4819            session_id,
4820            Some(10_000),
4821            Some(50_000),
4822        );
4823        let mut mandate = Mandate::new(
4824            &goal.id,
4825            None,
4826            "Maintain a useful, authentic account presence",
4827            session_id,
4828            authority(max_actions),
4829            60,
4830            3_600,
4831            300,
4832        );
4833        mandate.next_review_at = (chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339();
4834        (goal, mandate)
4835    }
4836
4837    /// A database whose `mandates` table predates the owner-given name
4838    /// gains the nullable column on the next migration; old rows read back
4839    /// unnamed and new ones keep their name.
4840    #[tokio::test]
4841    async fn an_existing_mandates_table_gains_the_name_column() {
4842        let (store, _database) = test_store().await;
4843        let pool = store.pool();
4844        let (old_goal, old_mandate) = controller("owner-session", 0);
4845        store
4846            .create_mandate_controller(&old_goal, &old_mandate)
4847            .await
4848            .unwrap();
4849        sqlx::query("ALTER TABLE mandates DROP COLUMN name")
4850            .execute(&pool)
4851            .await
4852            .unwrap();
4853
4854        crate::schema::migrate_work_tables(&pool, |_| false)
4855            .await
4856            .unwrap();
4857
4858        let unnamed = store.get_mandate(&old_mandate.id).await.unwrap().unwrap();
4859        assert_eq!(unnamed.name, None);
4860        let (goal, mut mandate) = controller("owner-session", 0);
4861        mandate.name = Some("synthetic-watch".to_string());
4862        store
4863            .create_mandate_controller(&goal, &mandate)
4864            .await
4865            .unwrap();
4866        let named = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4867        assert_eq!(named.name.as_deref(), Some("synthetic-watch"));
4868        assert!(named.has_name("Synthetic-Watch"));
4869    }
4870
4871    fn objective_control() -> MandateObjectiveControl {
4872        MandateObjectiveControl {
4873            schema_version: MandateObjectiveControl::SCHEMA_VERSION,
4874            metric_name: "synthetic useful interactions".to_string(),
4875            unit: "count".to_string(),
4876            baseline_micros: 10_000_000,
4877            target_micros: 20_000_000,
4878            direction: ObjectiveMetricDirection::AtLeast,
4879            measurement_source: "metric_source:synthetic-analytics".to_string(),
4880            measurement_cadence_secs: 3_600,
4881            baseline_observed_at: chrono::Utc::now().to_rfc3339(),
4882        }
4883    }
4884
4885    #[tokio::test]
4886    async fn autopilot_without_a_measured_objective_stays_active_and_due() {
4887        let (store, _database) = test_store().await;
4888        let (goal, mut mandate) = controller("owner-session", 0);
4889        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
4890        store
4891            .create_mandate_controller(&goal, &mandate)
4892            .await
4893            .unwrap();
4894
4895        let claimed = store
4896            .claim_due_mandates(10, "synthetic-heartbeat", 300)
4897            .await
4898            .unwrap();
4899        assert_eq!(claimed.len(), 1);
4900        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4901        assert_eq!(current.status, MandateStatus::Active);
4902        assert!(current.objective_control.is_none());
4903        assert!(current.suspension.is_none());
4904    }
4905
4906    #[tokio::test]
4907    async fn structured_signal_wakes_only_matching_autopilot_once() {
4908        let (store, _database) = test_store().await;
4909        let (goal, mut mandate) = controller("owner-session", 0);
4910        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
4911        mandate.objective_control = Some(objective_control());
4912        mandate.authority = MandateAuthority::from_operation_scopes(
4913            true,
4914            vec![MandateOperationScope {
4915                tool: "http_request".to_string(),
4916                operation: ToolCallOperation::Get,
4917                kind: MandateOperationKind::Observation,
4918                target_prefixes: vec![
4919                    "https://api.example.test/v1/mentions".to_string(),
4920                    "auth_profile:synthetic-social".to_string(),
4921                    "account:synthetic-1".to_string(),
4922                ],
4923                allowed_query_params: vec!["since_id".to_string()],
4924                mutation_effects: Vec::new(),
4925            }],
4926            0,
4927            0,
4928            0,
4929        );
4930        mandate.next_review_at = (chrono::Utc::now() + chrono::Duration::hours(3)).to_rfc3339();
4931        store
4932            .create_mandate_controller(&goal, &mandate)
4933            .await
4934            .unwrap();
4935        let signal = MandateWakeSignal {
4936            kind: MandateWakeSignalKind::Mention,
4937            source: "synthetic_social".to_string(),
4938            target_url: "https://api.example.test/v1/mentions?since_id=42".to_string(),
4939            account_id: Some("account:synthetic-1".to_string()),
4940            dedupe_key: "mention:42".to_string(),
4941            occurred_at: chrono::Utc::now().to_rfc3339(),
4942        };
4943
4944        assert_eq!(
4945            store.wake_mandates_for_signal(&signal).await.unwrap(),
4946            vec![mandate.id.clone()]
4947        );
4948        let awakened = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4949        assert!(
4950            chrono::DateTime::parse_from_rfc3339(&awakened.next_review_at).unwrap()
4951                <= chrono::Utc::now() + chrono::Duration::seconds(1)
4952        );
4953        assert!(
4954            store
4955                .wake_mandates_for_signal(&signal)
4956                .await
4957                .unwrap()
4958                .is_empty()
4959        );
4960
4961        let mut wrong_account = signal;
4962        wrong_account.dedupe_key = "mention:43".to_string();
4963        wrong_account.account_id = Some("account:synthetic-2".to_string());
4964        assert!(
4965            store
4966                .wake_mandates_for_signal(&wrong_account)
4967                .await
4968                .unwrap()
4969                .is_empty()
4970        );
4971    }
4972
4973    fn review_root(goal: &Goal, run_id: &str, task_id: &str) -> Task {
4974        Task {
4975            id: task_id.to_string(),
4976            goal_id: goal.id.clone(),
4977            description: format!("Mandate review: test controller for goal run {run_id}"),
4978            status: "pending".to_string(),
4979            priority: goal.priority.clone(),
4980            task_order: 0,
4981            parallel_group: None,
4982            depends_on: None,
4983            agent_id: None,
4984            context: None,
4985            result: None,
4986            error: None,
4987            blocker: None,
4988            idempotent: false,
4989            retry_count: 0,
4990            max_retries: 0,
4991            created_at: chrono::Utc::now().to_rfc3339(),
4992            started_at: None,
4993            completed_at: None,
4994        }
4995    }
4996
4997    async fn claim_and_start_run(
4998        store: &SqliteWorkStore,
4999        goal: &Goal,
5000        mandate: &Mandate,
5001    ) -> crate::traits::GoalRun {
5002        store
5003            .create_mandate_controller(goal, mandate)
5004            .await
5005            .unwrap();
5006        let claimed = store
5007            .claim_due_mandates(1, "test-heartbeat", 300)
5008            .await
5009            .unwrap();
5010        assert_eq!(claimed.len(), 1);
5011        let root_task_id = uuid::Uuid::new_v4().to_string();
5012        let run = store
5013            .start_goal_run(&goal.id, "mandate", None, Some(&root_task_id))
5014            .await
5015            .unwrap();
5016        store
5017            .create_task(&review_root(goal, &run.id, &root_task_id))
5018            .await
5019            .unwrap();
5020        // Goal runs now remain pending until a worker claim transitions them.
5021        // These storage tests exercise post-claim mandate invariants without a
5022        // task worker, so model that already-claimed state explicitly.
5023        sqlx::query("UPDATE goal_runs SET status = 'running' WHERE id = ?")
5024            .bind(&run.id)
5025            .execute(&store.pool)
5026            .await
5027            .unwrap();
5028        run
5029    }
5030
5031    struct MutationFence {
5032        root_attempt: crate::traits::TaskAttempt,
5033        worker_task: Task,
5034        worker_attempt: crate::traits::TaskAttempt,
5035    }
5036
5037    async fn claim_mutation_fence(
5038        store: &SqliteWorkStore,
5039        goal: &Goal,
5040        mandate: &Mandate,
5041        run: &GoalRun,
5042    ) -> MutationFence {
5043        let root_task_id = run.root_task_id.as_deref().unwrap();
5044        let root_attempt = store
5045            .claim_task_with_lease(
5046                root_task_id,
5047                "root-worker",
5048                Some("profile-task-lead"),
5049                7_200,
5050            )
5051            .await
5052            .unwrap()
5053            .unwrap();
5054        let worker_task_id = uuid::Uuid::new_v4().to_string();
5055        let mut worker_task = review_root(goal, &run.id, &worker_task_id);
5056        worker_task.description = "Perform one governed HTTP mutation".to_string();
5057        worker_task.task_order = 1;
5058        assert!(
5059            store
5060                .create_mandate_task_from_attempt(
5061                    &worker_task,
5062                    &mandate.id,
5063                    mandate.version,
5064                    &run.id,
5065                    &root_attempt.id,
5066                    16,
5067                )
5068                .await
5069                .unwrap()
5070        );
5071        let worker_attempt = store
5072            .claim_mandate_task_from_attempt(
5073                &worker_task_id,
5074                "executor-worker",
5075                &mandate.id,
5076                mandate.version,
5077                &run.id,
5078                &root_attempt.id,
5079                7_200,
5080            )
5081            .await
5082            .unwrap()
5083            .unwrap();
5084        MutationFence {
5085            root_attempt,
5086            worker_task,
5087            worker_attempt,
5088        }
5089    }
5090
5091    fn reservation(
5092        mandate: &Mandate,
5093        decision: &MandateDecisionCycle,
5094        run: &GoalRun,
5095        fence: &MutationFence,
5096        reserved_action_attempt: i64,
5097        sequence: u64,
5098        reserved_at: chrono::DateTime<chrono::Utc>,
5099    ) -> MandateMutationReservation {
5100        MandateMutationReservation {
5101            grant: crate::traits::MandateAuthorityGrant {
5102                mandate_id: mandate.id.clone(),
5103                mandate_version: mandate.version,
5104                owner_principal_id: mandate.owner_principal_id.clone(),
5105                decision_cycle_id: decision.id.clone(),
5106                action_digest: format!("{sequence:064x}"),
5107                counts_toward_cycle_budget: true,
5108                reserved_action_attempt,
5109                tool_call_id: Some(format!("tool-call-{sequence}")),
5110            },
5111            goal_run_id: run.id.clone(),
5112            root_task_id: run.root_task_id.clone().unwrap(),
5113            root_task_attempt_id: fence.root_attempt.id.clone(),
5114            task_id: fence.worker_task.id.clone(),
5115            task_attempt_id: fence.worker_attempt.id.clone(),
5116            tool_call_id: format!("tool-call-{sequence}"),
5117            tool_name: "http_request".to_string(),
5118            mutation_effects: vec!["external_delivery".to_string()],
5119            targets: vec![MandateMutationTarget {
5120                kind: "url".to_string(),
5121                identifier: "https://api.x.com/2/tweets".to_string(),
5122            }],
5123            account_identifiers: Vec::new(),
5124            reserved_at: reserved_at.to_rfc3339(),
5125        }
5126    }
5127
5128    fn dispatch_claim(
5129        reservation: &MandateMutationReservation,
5130        claimed_at: chrono::DateTime<chrono::Utc>,
5131    ) -> MandateMutationDispatchClaim {
5132        MandateMutationDispatchClaim {
5133            grant: reservation.grant.clone(),
5134            goal_run_id: reservation.goal_run_id.clone(),
5135            root_task_id: reservation.root_task_id.clone(),
5136            root_task_attempt_id: reservation.root_task_attempt_id.clone(),
5137            task_id: reservation.task_id.clone(),
5138            task_attempt_id: reservation.task_attempt_id.clone(),
5139            tool_call_id: reservation.tool_call_id.clone(),
5140            tool_name: reservation.tool_name.clone(),
5141            claimed_at: claimed_at.to_rfc3339(),
5142        }
5143    }
5144
5145    async fn complete_mutation_fence(store: &SqliteWorkStore, fence: &MutationFence) {
5146        let complete = crate::traits::TaskAttemptPatch {
5147            status: "completed".to_string(),
5148            result: Some("verified".to_string()),
5149            ..Default::default()
5150        };
5151        assert!(
5152            store
5153                .patch_task_from_attempt(
5154                    &fence.worker_attempt.id,
5155                    &fence.worker_attempt.lease_token,
5156                    &complete,
5157                )
5158                .await
5159                .unwrap()
5160        );
5161        assert!(
5162            store
5163                .patch_task_from_attempt(
5164                    &fence.root_attempt.id,
5165                    &fence.root_attempt.lease_token,
5166                    &complete,
5167                )
5168                .await
5169                .unwrap()
5170        );
5171    }
5172
5173    #[tokio::test]
5174    async fn controller_and_mandate_are_created_atomically() {
5175        let (store, _database) = test_store().await;
5176        let (goal, mandate) = controller("owner-session", 2);
5177        store
5178            .create_mandate_controller(&goal, &mandate)
5179            .await
5180            .unwrap();
5181
5182        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5183        assert_eq!(loaded.goal_id, goal.id);
5184        assert_eq!(loaded.version, 1);
5185        assert!(loaded.review_lease_token.is_none());
5186        assert!(store.get_goal(&goal.id).await.unwrap().is_some());
5187        let channel_links: i64 = sqlx::query_scalar(
5188            "SELECT COUNT(*) FROM work_channel_links WHERE goal_id = ? AND channel_session_id = ?",
5189        )
5190        .bind(&goal.id)
5191        .bind(&goal.session_id)
5192        .fetch_one(&store.pool)
5193        .await
5194        .unwrap();
5195        assert_eq!(channel_links, 1);
5196
5197        let pending_goal = Goal::new_continuous_pending(
5198            "Mandate awaiting confirmation",
5199            "owner-session",
5200            None,
5201            None,
5202        );
5203        let mut pending_mandate = Mandate::new(
5204            &pending_goal.id,
5205            None,
5206            "Await explicit owner confirmation",
5207            "owner-session",
5208            authority(0),
5209            60,
5210            3_600,
5211            300,
5212        );
5213        pending_mandate.status = MandateStatus::Paused;
5214        pending_mandate.confirmed_at = None;
5215        store
5216            .create_mandate_controller(&pending_goal, &pending_mandate)
5217            .await
5218            .unwrap();
5219        assert_eq!(
5220            store
5221                .get_goal(&pending_goal.id)
5222                .await
5223                .unwrap()
5224                .unwrap()
5225                .status,
5226            "pending_confirmation"
5227        );
5228        assert_eq!(
5229            store
5230                .get_mandate(&pending_mandate.id)
5231                .await
5232                .unwrap()
5233                .unwrap()
5234                .status,
5235            MandateStatus::Paused
5236        );
5237
5238        let (bad_goal, mut bad_mandate) = controller("owner-session", 2);
5239        bad_mandate.source_goal_id = Some("missing-personal-goal".to_string());
5240        assert!(
5241            store
5242                .create_mandate_controller(&bad_goal, &bad_mandate)
5243                .await
5244                .is_err()
5245        );
5246        assert!(store.get_goal(&bad_goal.id).await.unwrap().is_none());
5247
5248        let same_owner_source = Goal::new_personal("Grow an audience", "owner-session");
5249        store.create_goal(&same_owner_source).await.unwrap();
5250        let (linked_goal, mut linked_mandate) = controller("owner-session", 2);
5251        linked_mandate.source_goal_id = Some(same_owner_source.id);
5252        store
5253            .create_mandate_controller(&linked_goal, &linked_mandate)
5254            .await
5255            .unwrap();
5256        assert!(store.get_goal(&linked_goal.id).await.unwrap().is_some());
5257
5258        let foreign_source = Goal::new_personal("Grow an audience", "different-owner-session");
5259        store.create_goal(&foreign_source).await.unwrap();
5260        let (foreign_goal, mut foreign_mandate) = controller("owner-session", 2);
5261        foreign_mandate.source_goal_id = Some(foreign_source.id);
5262        assert!(
5263            store
5264                .create_mandate_controller(&foreign_goal, &foreign_mandate)
5265                .await
5266                .is_err()
5267        );
5268        assert!(store.get_goal(&foreign_goal.id).await.unwrap().is_none());
5269    }
5270
5271    #[tokio::test]
5272    async fn verified_private_owner_is_authorized_across_bot_routes() {
5273        let (store, _database) = test_store().await;
5274        let (goal, mandate) = controller("alpha_bot:12345", 1);
5275        assert_eq!(mandate.owner_principal_id, "principal:telegram:12345");
5276        store
5277            .create_mandate_controller(&goal, &mandate)
5278            .await
5279            .unwrap();
5280
5281        assert!(
5282            store
5283                .is_mandate_session_authorized(&mandate.id, "beta_bot:12345")
5284                .await
5285                .unwrap()
5286        );
5287        assert_eq!(
5288            store
5289                .list_mandates(Some("beta_bot:12345"), false)
5290                .await
5291                .unwrap()
5292                .iter()
5293                .map(|item| item.id.as_str())
5294                .collect::<Vec<_>>(),
5295            [mandate.id.as_str()]
5296        );
5297        assert!(
5298            !store
5299                .is_mandate_session_authorized(&mandate.id, "beta_bot:67890")
5300                .await
5301                .unwrap()
5302        );
5303
5304        let (group_goal, group_mandate) = controller("alpha_bot:-10012345", 1);
5305        assert_ne!(
5306            group_mandate.owner_principal_id,
5307            "principal:telegram:-10012345"
5308        );
5309        store
5310            .create_mandate_controller(&group_goal, &group_mandate)
5311            .await
5312            .unwrap();
5313        assert!(
5314            !store
5315                .is_mandate_session_authorized(&group_mandate.id, "beta_bot:-10012345")
5316                .await
5317                .unwrap()
5318        );
5319    }
5320
5321    #[tokio::test]
5322    async fn objective_measurements_require_current_run_structured_receipts() {
5323        let (store, _database) = test_store().await;
5324        let (goal, mut mandate) = controller("owner-session", 1);
5325        mandate.objective_control = Some(objective_control());
5326        let run = claim_and_start_run(&store, &goal, &mandate).await;
5327        let receipt_id = "synthetic-metric-receipt";
5328        let task_id = run.root_task_id.as_deref().unwrap();
5329        sqlx::query(
5330            "INSERT INTO events
5331                (session_id, event_type, data, created_at, task_id, tool_name)
5332             VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
5333        )
5334        .bind("owner-session")
5335        .bind(
5336            serde_json::json!({
5337                "task_id": task_id,
5338                "tool_call_id": receipt_id,
5339                "name": "http_request",
5340                "result": "synthetic metric value",
5341                "success": true,
5342                "duration_ms": 1,
5343                "receipt": {
5344                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
5345                    "outcome_status": "succeeded",
5346                    "outcome_evidence": "structured_metadata"
5347                }
5348            })
5349            .to_string(),
5350        )
5351        .bind(chrono::Utc::now().to_rfc3339())
5352        .bind(task_id)
5353        .execute(&store.pool)
5354        .await
5355        .unwrap();
5356
5357        let measurement = MandateObjectiveMeasurement::new(
5358            &mandate.id,
5359            mandate.version,
5360            &run.id,
5361            12_000_000,
5362            9_500,
5363            vec![receipt_id.to_string()],
5364            &chrono::Utc::now().to_rfc3339(),
5365        );
5366        store
5367            .record_mandate_objective_measurement(&measurement)
5368            .await
5369            .unwrap();
5370        assert_eq!(
5371            store
5372                .list_mandate_objective_measurements(&mandate.id, 10)
5373                .await
5374                .unwrap(),
5375            vec![measurement]
5376        );
5377
5378        let unproven = MandateObjectiveMeasurement::new(
5379            &mandate.id,
5380            mandate.version,
5381            &run.id,
5382            13_000_000,
5383            9_500,
5384            vec!["receipt-from-another-run".to_string()],
5385            &chrono::Utc::now().to_rfc3339(),
5386        );
5387        assert!(
5388            store
5389                .record_mandate_objective_measurement(&unproven)
5390                .await
5391                .is_err()
5392        );
5393    }
5394
5395    #[tokio::test]
5396    async fn persistence_rejects_text_bound_bypasses_before_writing() {
5397        let (store, _database) = test_store().await;
5398        let (bad_goal, mut bad_mandate) = controller("owner-session", 2);
5399        bad_mandate.objective = "é".repeat(1_025);
5400        assert!(
5401            store
5402                .create_mandate_controller(&bad_goal, &bad_mandate)
5403                .await
5404                .is_err()
5405        );
5406        assert!(store.get_goal(&bad_goal.id).await.unwrap().is_none());
5407
5408        let (goal, mandate) = controller("owner-session", 2);
5409        let run = claim_and_start_run(&store, &goal, &mandate).await;
5410        let oversized_decision = MandateDecisionCycle::new(
5411            &mandate.id,
5412            &run.id,
5413            MandateDecisionOutcome::Wait,
5414            &"é".repeat(1_025),
5415            mandate.version,
5416        );
5417        assert!(
5418            store
5419                .record_mandate_decision(&oversized_decision, None, None)
5420                .await
5421                .is_err()
5422        );
5423
5424        let act = MandateDecisionCycle::new(
5425            &mandate.id,
5426            &run.id,
5427            MandateDecisionOutcome::Act,
5428            "A bounded governed action is useful",
5429            mandate.version,
5430        );
5431        let oversized_intention = Intention::new(
5432            &mandate.id,
5433            &act.id,
5434            &run.id,
5435            &"é".repeat(513),
5436            "A bounded governed action is useful",
5437        );
5438        assert!(
5439            store
5440                .record_mandate_decision(&act, Some(&oversized_intention), None)
5441                .await
5442                .is_err()
5443        );
5444        assert!(
5445            store
5446                .get_mandate_decision_for_run(&run.id)
5447                .await
5448                .unwrap()
5449                .is_none()
5450        );
5451    }
5452
5453    #[tokio::test]
5454    async fn owner_update_is_cas_and_clears_a_live_lease() {
5455        let (store, _database) = test_store().await;
5456        let (goal, mandate) = controller("owner-session", 2);
5457        store
5458            .create_mandate_controller(&goal, &mandate)
5459            .await
5460            .unwrap();
5461        assert_eq!(
5462            store
5463                .claim_due_mandates(1, "heartbeat", 300)
5464                .await
5465                .unwrap()
5466                .len(),
5467            1
5468        );
5469
5470        let mut update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5471        update.version += 1;
5472        update.objective = "Updated owner objective".to_string();
5473        store.update_mandate(&update).await.unwrap();
5474
5475        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5476        assert_eq!(loaded.version, 2);
5477        assert_eq!(loaded.objective, "Updated owner objective");
5478        assert!(loaded.review_lease_token.is_none());
5479        assert!(store.update_mandate(&update).await.is_err());
5480
5481        let mut attempted_pause = loaded;
5482        attempted_pause.version += 1;
5483        attempted_pause.status = MandateStatus::Paused;
5484        assert!(store.update_mandate(&attempted_pause).await.is_err());
5485        assert!(
5486            store
5487                .transition_mandate_status(
5488                    &mandate.id,
5489                    MandateStatus::Active,
5490                    MandateStatus::Paused,
5491                )
5492                .await
5493                .unwrap()
5494        );
5495        assert_eq!(
5496            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5497            "paused"
5498        );
5499    }
5500
5501    #[tokio::test]
5502    async fn confirmation_is_durable_atomic_and_required_for_activation() {
5503        let (store, _database) = test_store().await;
5504        let goal = Goal::new_continuous_pending(
5505            "Mandate awaiting owner confirmation",
5506            "owner-session",
5507            None,
5508            None,
5509        );
5510        let mut mandate = Mandate::new(
5511            &goal.id,
5512            None,
5513            "Await explicit owner confirmation",
5514            "owner-session",
5515            authority(0),
5516            60,
5517            3_600,
5518            300,
5519        );
5520        mandate.status = MandateStatus::Paused;
5521        mandate.confirmed_at = None;
5522        store
5523            .create_mandate_controller(&goal, &mandate)
5524            .await
5525            .unwrap();
5526
5527        assert!(
5528            !store
5529                .transition_mandate_status(
5530                    &mandate.id,
5531                    MandateStatus::Paused,
5532                    MandateStatus::Active,
5533                )
5534                .await
5535                .unwrap()
5536        );
5537        // Confirmation is a CAS against the exact policy version displayed to
5538        // the owner; a stale or speculative callback cannot activate it.
5539        assert!(
5540            !store
5541                .confirm_mandate(&mandate.id, mandate.version + 1, None)
5542                .await
5543                .unwrap()
5544        );
5545        assert_eq!(
5546            store
5547                .get_mandate(&mandate.id)
5548                .await
5549                .unwrap()
5550                .unwrap()
5551                .status,
5552            MandateStatus::Paused
5553        );
5554        assert!(
5555            store
5556                .confirm_mandate(&mandate.id, mandate.version, None)
5557                .await
5558                .unwrap()
5559        );
5560        assert!(
5561            !store
5562                .confirm_mandate(&mandate.id, mandate.version, None)
5563                .await
5564                .unwrap()
5565        );
5566
5567        let confirmed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5568        assert_eq!(confirmed.status, MandateStatus::Active);
5569        assert_eq!(confirmed.version, 2);
5570        assert!(confirmed.confirmed_at.is_some());
5571        assert!(confirmed.is_active());
5572        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
5573        assert_eq!(controller.status, "active");
5574        assert_eq!(controller.dispatch_failures, 0);
5575    }
5576
5577    #[tokio::test]
5578    async fn stale_confirmation_cleanup_cancels_linked_mandate_and_cannot_activate_it() {
5579        let (store, _database) = test_store().await;
5580        let goal =
5581            Goal::new_continuous_pending("Stale mandate confirmation", "owner-session", None, None);
5582        let mut mandate = Mandate::new(
5583            &goal.id,
5584            None,
5585            "Never activate without confirmation",
5586            "owner-session",
5587            authority(0),
5588            60,
5589            3_600,
5590            300,
5591        );
5592        mandate.status = MandateStatus::Paused;
5593        mandate.confirmed_at = None;
5594        store
5595            .create_mandate_controller(&goal, &mandate)
5596            .await
5597            .unwrap();
5598        sqlx::query("UPDATE goals SET created_at = ? WHERE id = ?")
5599            .bind((chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339())
5600            .bind(&goal.id)
5601            .execute(&store.pool)
5602            .await
5603            .unwrap();
5604
5605        assert_eq!(
5606            store
5607                .cancel_stale_pending_confirmation_goals(3_600)
5608                .await
5609                .unwrap(),
5610            1
5611        );
5612        let cancelled = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5613        assert_eq!(cancelled.status, MandateStatus::Cancelled);
5614        assert!(cancelled.confirmed_at.is_none());
5615        assert_eq!(
5616            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5617            "cancelled"
5618        );
5619        assert!(
5620            !store
5621                .confirm_mandate(&mandate.id, mandate.version, None)
5622                .await
5623                .unwrap()
5624        );
5625        assert!(
5626            !store
5627                .transition_mandate_status(
5628                    &mandate.id,
5629                    MandateStatus::Cancelled,
5630                    MandateStatus::Active,
5631                )
5632                .await
5633                .unwrap()
5634        );
5635    }
5636
5637    #[tokio::test]
5638    async fn atomic_review_creation_rolls_back_run_when_root_insert_fails() {
5639        let (store, _database) = test_store().await;
5640        let (goal, mandate) = controller("owner-session", 1);
5641        store
5642            .create_mandate_controller(&goal, &mandate)
5643            .await
5644            .unwrap();
5645        let claimed = store
5646            .claim_due_mandates(1, "test-heartbeat", 300)
5647            .await
5648            .unwrap();
5649        let lease = claimed[0].review_lease_token.as_deref().unwrap();
5650
5651        let other_goal = Goal::new_finite("Existing task owner", "owner-session");
5652        store.create_goal(&other_goal).await.unwrap();
5653        let existing_task = review_root(&other_goal, "other-run", "duplicate-root-id");
5654        store.create_task(&existing_task).await.unwrap();
5655
5656        let attempted_run_id = uuid::Uuid::new_v4().to_string();
5657        let duplicate_root = review_root(&goal, &attempted_run_id, "duplicate-root-id");
5658        assert!(
5659            store
5660                .create_mandate_review_run(&mandate.id, lease, &attempted_run_id, &duplicate_root,)
5661                .await
5662                .is_err()
5663        );
5664        let orphan_count =
5665            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM goal_runs WHERE id = ?")
5666                .bind(&attempted_run_id)
5667                .fetch_one(&store.pool)
5668                .await
5669                .unwrap();
5670        assert_eq!(orphan_count, 0);
5671
5672        let successful_run_id = uuid::Uuid::new_v4().to_string();
5673        let fresh_root = review_root(&goal, &successful_run_id, &uuid::Uuid::new_v4().to_string());
5674        let run = store
5675            .create_mandate_review_run(&mandate.id, lease, &successful_run_id, &fresh_root)
5676            .await
5677            .unwrap();
5678        assert_eq!(run.root_task_id.as_deref(), Some(fresh_root.id.as_str()));
5679        assert_eq!(
5680            store.get_tasks_for_goal_run(&run.id).await.unwrap().len(),
5681            1
5682        );
5683    }
5684
5685    #[tokio::test]
5686    async fn claiming_recovers_pre_atomic_run_created_without_a_root_task() {
5687        let (store, _database) = test_store().await;
5688        let (goal, mandate) = controller("owner-session", 1);
5689        store
5690            .create_mandate_controller(&goal, &mandate)
5691            .await
5692            .unwrap();
5693        let first_claim = store
5694            .claim_due_mandates(1, "old-heartbeat", 300)
5695            .await
5696            .unwrap();
5697        assert_eq!(first_claim.len(), 1);
5698        let interrupted = store
5699            .start_goal_run(&goal.id, "mandate", None, Some("missing-root"))
5700            .await
5701            .unwrap();
5702
5703        let recovered = store
5704            .claim_due_mandates(1, "new-heartbeat", 300)
5705            .await
5706            .unwrap();
5707        assert_eq!(recovered.len(), 1);
5708        let old_run = store
5709            .get_goal_runs(&goal.id)
5710            .await
5711            .unwrap()
5712            .into_iter()
5713            .find(|run| run.id == interrupted.id)
5714            .unwrap();
5715        assert_eq!(old_run.status, "failed");
5716        assert!(
5717            old_run
5718                .outcome_summary
5719                .as_deref()
5720                .unwrap()
5721                .contains("interrupted mandate dispatch")
5722        );
5723
5724        let run_id = uuid::Uuid::new_v4().to_string();
5725        let root = review_root(&goal, &run_id, &uuid::Uuid::new_v4().to_string());
5726        let new_run = store
5727            .create_mandate_review_run(
5728                &mandate.id,
5729                recovered[0].review_lease_token.as_deref().unwrap(),
5730                &run_id,
5731                &root,
5732            )
5733            .await
5734            .unwrap();
5735        assert_eq!(
5736            store
5737                .get_tasks_for_goal_run(&new_run.id)
5738                .await
5739                .unwrap()
5740                .len(),
5741            1
5742        );
5743    }
5744
5745    #[tokio::test]
5746    async fn completed_root_crash_without_dispatch_retries_after_grace_and_cancels_pending_child() {
5747        let (store, _database) = test_store().await;
5748        let (goal, mandate) = controller("owner-session", 1);
5749        let run = claim_and_start_run(&store, &goal, &mandate).await;
5750        let root_task_id = run.root_task_id.as_deref().unwrap();
5751        let root_attempt = store
5752            .claim_task_with_lease(
5753                root_task_id,
5754                "crashing-root",
5755                Some("profile-task-lead"),
5756                7_200,
5757            )
5758            .await
5759            .unwrap()
5760            .unwrap();
5761        let act = MandateDecisionCycle::new(
5762            &mandate.id,
5763            &run.id,
5764            MandateDecisionOutcome::Act,
5765            "One bounded child should perform the action",
5766            mandate.version,
5767        );
5768        let intention = Intention::new(
5769            &mandate.id,
5770            &act.id,
5771            &run.id,
5772            "Perform the bounded child action",
5773            "It advances the mandate",
5774        );
5775        store
5776            .record_mandate_decision(&act, Some(&intention), Some(&root_attempt.id))
5777            .await
5778            .unwrap();
5779        let child_id = uuid::Uuid::new_v4().to_string();
5780        let mut child = review_root(&goal, &run.id, &child_id);
5781        child.task_order = 1;
5782        child.description = "Pending governed child".to_string();
5783        assert!(
5784            store
5785                .create_mandate_task_from_attempt(
5786                    &child,
5787                    &mandate.id,
5788                    mandate.version,
5789                    &run.id,
5790                    &root_attempt.id,
5791                    16,
5792                )
5793                .await
5794                .unwrap()
5795        );
5796        assert!(
5797            store
5798                .patch_task_from_attempt(
5799                    &root_attempt.id,
5800                    &root_attempt.lease_token,
5801                    &crate::traits::TaskAttemptPatch {
5802                        status: "completed".to_string(),
5803                        result: Some("decision recorded; child queued".to_string()),
5804                        ..Default::default()
5805                    },
5806                )
5807                .await
5808                .unwrap()
5809        );
5810
5811        // The immediate finalizer gets a short uncontended window.
5812        assert!(
5813            store
5814                .claim_due_mandates(1, "grace-probe", 300)
5815                .await
5816                .unwrap()
5817                .is_empty()
5818        );
5819        assert_eq!(
5820            store
5821                .get_mandate(&mandate.id)
5822                .await
5823                .unwrap()
5824                .unwrap()
5825                .status,
5826            MandateStatus::Active
5827        );
5828        assert_eq!(
5829            store.get_task(&child_id).await.unwrap().unwrap().status,
5830            "pending"
5831        );
5832
5833        let stale_completion = (chrono::Utc::now() - chrono::Duration::seconds(61)).to_rfc3339();
5834        sqlx::query("UPDATE tasks SET completed_at = ? WHERE id = ?")
5835            .bind(&stale_completion)
5836            .bind(root_task_id)
5837            .execute(&store.pool)
5838            .await
5839            .unwrap();
5840        assert!(
5841            store
5842                .claim_due_mandates(1, "reconciliation-probe", 300)
5843                .await
5844                .unwrap()
5845                .is_empty()
5846        );
5847
5848        // The child never reserved a mutation, so nothing external can have
5849        // happened: the run fails and the mandate retries, unsuspended.
5850        assert_eq!(
5851            store
5852                .get_mandate(&mandate.id)
5853                .await
5854                .unwrap()
5855                .unwrap()
5856                .status,
5857            MandateStatus::Active
5858        );
5859        assert_eq!(
5860            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5861            "active"
5862        );
5863        assert_eq!(
5864            store.get_task(&child_id).await.unwrap().unwrap().status,
5865            "cancelled"
5866        );
5867        assert_eq!(
5868            store.get_goal_runs(&goal.id).await.unwrap()[0]
5869                .outcome_summary
5870                .as_deref(),
5871            Some("mandate_review_failed:act_interrupted_before_dispatch")
5872        );
5873        let notification_message: String = sqlx::query_scalar(
5874            "SELECT message FROM notification_queue
5875             WHERE goal_id = ? AND notification_type = 'mandate_review_failed'
5876               AND priority = 'critical' AND expires_at IS NULL
5877             LIMIT 1",
5878        )
5879        .bind(&goal.id)
5880        .fetch_one(&store.pool)
5881        .await
5882        .unwrap();
5883        assert!(
5884            notification_message.contains("decided to act"),
5885            "{notification_message}"
5886        );
5887        assert!(
5888            notification_message.contains("interrupted before any action was dispatched"),
5889            "{notification_message}"
5890        );
5891        assert!(!notification_message.contains("stopped before it finished"));
5892        assert!(notification_message.contains("will retry automatically"));
5893        let intention_status =
5894            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
5895                .bind(&intention.id)
5896                .fetch_one(&store.pool)
5897                .await
5898                .unwrap();
5899        assert_eq!(intention_status, "suspended");
5900    }
5901
5902    /// An ACT committed by a root whose daemon then stopped: no action task,
5903    /// no reservation, root attempt gone.
5904    async fn orphan_act_without_task(
5905        store: &SqliteWorkStore,
5906    ) -> (Goal, Mandate, crate::traits::GoalRun, Intention) {
5907        let (goal, mandate) = controller("owner-session", 1);
5908        let run = claim_and_start_run(store, &goal, &mandate).await;
5909        let root_task_id = run.root_task_id.clone().unwrap();
5910        let root_attempt = store
5911            .claim_task_with_lease(
5912                &root_task_id,
5913                "crashing-root",
5914                Some("profile-task-lead"),
5915                600,
5916            )
5917            .await
5918            .unwrap()
5919            .unwrap();
5920        let act = MandateDecisionCycle::new(
5921            &mandate.id,
5922            &run.id,
5923            MandateDecisionOutcome::Act,
5924            "Post the drafted update",
5925            mandate.version,
5926        );
5927        let intention = Intention::new(
5928            &mandate.id,
5929            &act.id,
5930            &run.id,
5931            "Publish: Synthetic launch note for Acme Corp",
5932            "It advances the mandate",
5933        );
5934        store
5935            .record_mandate_decision(&act, Some(&intention), Some(&root_attempt.id))
5936            .await
5937            .unwrap();
5938        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
5939            .bind((chrono::Utc::now() - chrono::Duration::seconds(5)).to_rfc3339())
5940            .bind(&root_attempt.id)
5941            .execute(&store.pool)
5942            .await
5943            .unwrap();
5944        sqlx::query("UPDATE tasks SET status = 'interrupted' WHERE id = ?")
5945            .bind(&root_task_id)
5946            .execute(&store.pool)
5947            .await
5948            .unwrap();
5949        (goal, mandate, run, intention)
5950    }
5951
5952    async fn recover(store: &SqliteWorkStore) {
5953        let _ = store
5954            .claim_due_mandates(1, "recovery-probe", 300)
5955            .await
5956            .unwrap();
5957    }
5958
5959    #[tokio::test]
5960    async fn orphaned_act_without_task_resumes_once_with_saved_intention() {
5961        let (store, _database) = test_store().await;
5962        let (goal, mandate, run, intention) = orphan_act_without_task(&store).await;
5963        recover(&store).await;
5964        let root = store
5965            .get_task(run.root_task_id.as_deref().unwrap())
5966            .await
5967            .unwrap()
5968            .unwrap();
5969        assert_eq!(root.status, "pending");
5970        assert_eq!(root.retry_count, 1);
5971        assert!(
5972            root.description.contains(&intention.description),
5973            "{}",
5974            root.description
5975        );
5976        let runs = store.get_goal_runs(&goal.id).await.unwrap();
5977        assert_eq!(runs.len(), 1);
5978        assert_eq!(runs[0].status, "pending");
5979        assert_eq!(
5980            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
5981                .bind(&intention.id)
5982                .fetch_one(&store.pool)
5983                .await
5984                .unwrap(),
5985            "committed"
5986        );
5987        assert_eq!(
5988            store
5989                .get_mandate(&mandate.id)
5990                .await
5991                .unwrap()
5992                .unwrap()
5993                .status,
5994            MandateStatus::Active
5995        );
5996        // A second recovery while it waits for dispatch changes nothing.
5997        recover(&store).await;
5998        let tasks = store.get_tasks_for_goal_run(&run.id).await.unwrap();
5999        assert_eq!(tasks.len(), 1);
6000        assert_eq!(tasks[0].status, "pending");
6001        assert_eq!(store.get_goal_runs(&goal.id).await.unwrap().len(), 1);
6002    }
6003
6004    #[tokio::test]
6005    async fn resumed_act_interrupted_again_falls_back_instead_of_resuming_twice() {
6006        let (store, _database) = test_store().await;
6007        let (goal, _mandate, run, intention) = orphan_act_without_task(&store).await;
6008        let root_task_id = run.root_task_id.clone().unwrap();
6009        recover(&store).await;
6010        // The resumed lead is interrupted too, again before any task.
6011        let attempt = store
6012            .claim_task_with_lease(
6013                &root_task_id,
6014                "resumed-root",
6015                Some("profile-task-lead"),
6016                600,
6017            )
6018            .await
6019            .unwrap()
6020            .unwrap();
6021        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
6022            .bind((chrono::Utc::now() - chrono::Duration::seconds(5)).to_rfc3339())
6023            .bind(&attempt.id)
6024            .execute(&store.pool)
6025            .await
6026            .unwrap();
6027        sqlx::query("UPDATE tasks SET status = 'interrupted' WHERE id = ?")
6028            .bind(&root_task_id)
6029            .execute(&store.pool)
6030            .await
6031            .unwrap();
6032        recover(&store).await;
6033        assert_eq!(
6034            store.get_goal_runs(&goal.id).await.unwrap()[0]
6035                .outcome_summary
6036                .as_deref(),
6037            Some("mandate_review_failed:act_interrupted_before_dispatch")
6038        );
6039        assert_eq!(
6040            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
6041                .bind(&intention.id)
6042                .fetch_one(&store.pool)
6043                .await
6044                .unwrap(),
6045            "suspended"
6046        );
6047    }
6048
6049    #[tokio::test]
6050    async fn orphaned_act_with_existing_action_task_is_not_resumed() {
6051        let (store, _database) = test_store().await;
6052        let (goal, _mandate, run, _intention) = orphan_act_without_task(&store).await;
6053        // An action task already exists for the cycle: never resume.
6054        sqlx::query("UPDATE tasks SET retry_count = 0 WHERE id = ?")
6055            .bind(run.root_task_id.as_deref().unwrap())
6056            .execute(&store.pool)
6057            .await
6058            .unwrap();
6059        let child_id = uuid::Uuid::new_v4().to_string();
6060        let mut child = review_root(&goal, &run.id, &child_id);
6061        child.task_order = 1;
6062        store.create_task(&child).await.unwrap();
6063        recover(&store).await;
6064        let runs = store.get_goal_runs(&goal.id).await.unwrap();
6065        assert_ne!(runs[0].status, "pending");
6066        assert_eq!(
6067            runs[0].outcome_summary.as_deref(),
6068            Some("mandate_review_failed:act_interrupted_before_dispatch")
6069        );
6070    }
6071
6072    #[tokio::test]
6073    async fn stale_or_version_changed_act_is_not_resumed() {
6074        for case in ["stale", "version"] {
6075            let (store, _database) = test_store().await;
6076            let (goal, mandate, run, _intention) = orphan_act_without_task(&store).await;
6077            match case {
6078                "stale" => {
6079                    sqlx::query(
6080                        "UPDATE mandate_decision_cycles SET created_at = ? WHERE goal_run_id = ?",
6081                    )
6082                    .bind((chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339())
6083                    .bind(&run.id)
6084                    .execute(&store.pool)
6085                    .await
6086                    .unwrap();
6087                }
6088                _ => {
6089                    sqlx::query("UPDATE mandates SET version = version + 1 WHERE id = ?")
6090                        .bind(&mandate.id)
6091                        .execute(&store.pool)
6092                        .await
6093                        .unwrap();
6094                }
6095            }
6096            recover(&store).await;
6097            let root = store
6098                .get_task(run.root_task_id.as_deref().unwrap())
6099                .await
6100                .unwrap()
6101                .unwrap();
6102            assert_eq!(root.retry_count, 0, "{case}");
6103            assert_ne!(root.status, "pending", "{case}");
6104            if case == "stale" {
6105                assert_eq!(
6106                    store.get_goal_runs(&goal.id).await.unwrap()[0]
6107                        .outcome_summary
6108                        .as_deref(),
6109                    Some("mandate_review_failed:act_interrupted_before_dispatch")
6110                );
6111            }
6112        }
6113    }
6114
6115    #[tokio::test]
6116    async fn orphaned_review_without_decision_retries_without_reconciliation_pause() {
6117        let (store, _database) = test_store().await;
6118        let (goal, mandate) = controller("owner-session", 1);
6119        let run = claim_and_start_run(&store, &goal, &mandate).await;
6120        let root_attempt = store
6121            .claim_task_with_lease(
6122                run.root_task_id.as_deref().unwrap(),
6123                "crashing-reviewer",
6124                Some("profile-task-lead"),
6125                180,
6126            )
6127            .await
6128            .unwrap()
6129            .unwrap();
6130        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
6131            .bind((chrono::Utc::now() - chrono::Duration::seconds(1)).to_rfc3339())
6132            .bind(&root_attempt.id)
6133            .execute(&store.pool)
6134            .await
6135            .unwrap();
6136
6137        assert!(
6138            store
6139                .claim_due_mandates(1, "orphan-recovery", 300)
6140                .await
6141                .unwrap()
6142                .is_empty()
6143        );
6144
6145        let recovered_mandate = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6146        assert_eq!(recovered_mandate.status, MandateStatus::Active);
6147        assert!(recovered_mandate.next_review_at > chrono::Utc::now().to_rfc3339());
6148        assert_eq!(
6149            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6150            "active"
6151        );
6152        let recovered_run = store
6153            .get_goal_runs(&goal.id)
6154            .await
6155            .unwrap()
6156            .into_iter()
6157            .find(|candidate| candidate.id == run.id)
6158            .unwrap();
6159        assert_eq!(recovered_run.status, "failed");
6160        assert_eq!(
6161            recovered_run.outcome_summary.as_deref(),
6162            Some("mandate_review_failed:decision_missing")
6163        );
6164
6165        let root = store
6166            .get_task(run.root_task_id.as_deref().unwrap())
6167            .await
6168            .unwrap()
6169            .unwrap();
6170        assert_eq!(root.status, "cancelled");
6171        let notification: (String, String) = sqlx::query_as(
6172            "SELECT notification_type, message FROM notification_queue
6173             WHERE id = ?",
6174        )
6175        .bind(format!("mandate-run-notice:{}", run.id))
6176        .fetch_one(&store.pool)
6177        .await
6178        .unwrap();
6179        assert_eq!(notification.0, "mandate_review_failed");
6180        assert!(notification.1.contains("before it decided anything"));
6181        assert!(!notification.1.contains("decision missing"));
6182        assert!(notification.1.contains("Nothing was done"));
6183        assert!(!notification.1.contains("check the account"));
6184    }
6185
6186    #[tokio::test]
6187    async fn stale_controller_repair_cannot_revive_an_owner_cancellation() {
6188        let (store, _database) = test_store().await;
6189        let (goal, mandate) = controller("owner-session", 1);
6190        store
6191            .create_mandate_controller(&goal, &mandate)
6192            .await
6193            .unwrap();
6194        assert!(
6195            store
6196                .transition_mandate_status(
6197                    &mandate.id,
6198                    MandateStatus::Active,
6199                    MandateStatus::Cancelled,
6200                )
6201                .await
6202                .unwrap()
6203        );
6204
6205        assert!(
6206            !store
6207                .keep_mandate_controller_active(&mandate.id, mandate.version)
6208                .await
6209                .unwrap()
6210        );
6211        assert_eq!(
6212            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6213            "cancelled"
6214        );
6215    }
6216
6217    /// An executor's blocker is input to the task lead, which owns the run's
6218    /// outcome: the mandate run stays running so the lead can still call the
6219    /// model (budget fence) and finalize. The lead's own blocker still blocks.
6220    #[tokio::test]
6221    async fn executor_blocker_leaves_the_mandate_run_to_its_task_lead() {
6222        let (store, _database) = test_store().await;
6223        let (goal, mandate) = controller("owner-session", 2);
6224        let run = claim_and_start_run(&store, &goal, &mandate).await;
6225        let act = MandateDecisionCycle::new(
6226            &mandate.id,
6227            &run.id,
6228            MandateDecisionOutcome::Act,
6229            "One bounded note is warranted",
6230            mandate.version,
6231        );
6232        let intention = Intention::new(
6233            &mandate.id,
6234            &act.id,
6235            &run.id,
6236            "Post one bounded note",
6237            "It advances the mandate",
6238        );
6239        store
6240            .record_mandate_decision(&act, Some(&intention), None)
6241            .await
6242            .unwrap();
6243        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6244        let blocked = |reason: &str| crate::traits::TaskAttemptPatch {
6245            status: "blocked".to_string(),
6246            result: None,
6247            error: None,
6248            blocker: Some(reason.to_string()),
6249            context: None,
6250            handoff: None,
6251        };
6252        async fn run_status(store: &SqliteWorkStore, run_id: &str) -> String {
6253            sqlx::query_scalar::<_, String>("SELECT status FROM goal_runs WHERE id = ?")
6254                .bind(run_id)
6255                .fetch_one(&store.pool)
6256                .await
6257                .unwrap()
6258        }
6259
6260        assert!(
6261            store
6262                .patch_task_from_attempt(
6263                    &fence.worker_attempt.id,
6264                    &fence.worker_attempt.lease_token,
6265                    &blocked("the target is unreachable"),
6266                )
6267                .await
6268                .unwrap()
6269        );
6270        assert_eq!(run_status(&store, &run.id).await, "running");
6271
6272        assert!(
6273            store
6274                .patch_task_from_attempt(
6275                    &fence.root_attempt.id,
6276                    &fence.root_attempt.lease_token,
6277                    &blocked("the lead cannot continue"),
6278                )
6279                .await
6280                .unwrap()
6281        );
6282        assert_eq!(run_status(&store, &run.id).await, "blocked");
6283    }
6284
6285    #[tokio::test]
6286    async fn lifecycle_transition_revokes_open_cycle_and_stale_owner_snapshot() {
6287        let (store, _database) = test_store().await;
6288        let (goal, mandate) = controller("owner-session", 2);
6289        let run = claim_and_start_run(&store, &goal, &mandate).await;
6290        let act = MandateDecisionCycle::new(
6291            &mandate.id,
6292            &run.id,
6293            MandateDecisionOutcome::Act,
6294            "A bounded action was justified before the pause",
6295            mandate.version,
6296        );
6297        let intention = Intention::new(
6298            &mandate.id,
6299            &act.id,
6300            &run.id,
6301            "Perform one bounded action",
6302            "It advances the mandate",
6303        );
6304        store
6305            .record_mandate_decision(&act, Some(&intention), None)
6306            .await
6307            .unwrap();
6308        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6309
6310        let mut stale_update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6311        stale_update.version += 1;
6312        stale_update.objective = "A stale owner snapshot".to_string();
6313
6314        assert!(
6315            store
6316                .transition_mandate_status(
6317                    &mandate.id,
6318                    MandateStatus::Active,
6319                    MandateStatus::Paused,
6320                )
6321                .await
6322                .unwrap()
6323        );
6324        let paused = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6325        assert_eq!(paused.status, MandateStatus::Paused);
6326        assert_eq!(paused.version, mandate.version + 1);
6327        assert!(
6328            store
6329                .get_current_goal_run(&goal.id)
6330                .await
6331                .unwrap()
6332                .is_none()
6333        );
6334        assert_eq!(
6335            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
6336            "cancelled"
6337        );
6338        assert_eq!(
6339            store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
6340            IntentionStatus::Suspended
6341        );
6342        assert!(
6343            store
6344                .reserve_mandate_action_attempt(&reservation(
6345                    &mandate,
6346                    &act,
6347                    &run,
6348                    &fence,
6349                    1,
6350                    1,
6351                    chrono::Utc::now(),
6352                ))
6353                .await
6354                .unwrap()
6355                .is_none()
6356        );
6357
6358        assert!(
6359            store
6360                .transition_mandate_status(
6361                    &mandate.id,
6362                    MandateStatus::Paused,
6363                    MandateStatus::Active,
6364                )
6365                .await
6366                .unwrap()
6367        );
6368        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6369        assert_eq!(resumed.version, mandate.version + 2);
6370        assert!(
6371            store
6372                .get_current_goal_run(&goal.id)
6373                .await
6374                .unwrap()
6375                .is_none()
6376        );
6377
6378        // The update was prepared before the lifecycle epoch changed, so its
6379        // CAS must fail instead of restoring its stale active status/policy.
6380        assert!(store.update_mandate(&stale_update).await.is_err());
6381
6382        let mut stale_cancel_racer = resumed;
6383        stale_cancel_racer.version += 1;
6384        stale_cancel_racer.objective = "Must not resurrect after cancel".to_string();
6385        assert!(
6386            store
6387                .transition_mandate_status(
6388                    &mandate.id,
6389                    MandateStatus::Active,
6390                    MandateStatus::Cancelled,
6391                )
6392                .await
6393                .unwrap()
6394        );
6395        assert!(store.update_mandate(&stale_cancel_racer).await.is_err());
6396        let cancelled = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6397        assert_eq!(cancelled.status, MandateStatus::Cancelled);
6398        assert_eq!(cancelled.version, mandate.version + 3);
6399    }
6400
6401    #[tokio::test]
6402    async fn policy_update_marks_unclaimed_reservation_never_dispatched_and_releases_rolling_quota()
6403    {
6404        let (store, _database) = test_store().await;
6405        let (goal, mandate) = controller("owner-session", 2);
6406        let run = claim_and_start_run(&store, &goal, &mandate).await;
6407        let act = MandateDecisionCycle::new(
6408            &mandate.id,
6409            &run.id,
6410            MandateDecisionOutcome::Act,
6411            "A bounded action was justified before the policy update",
6412            mandate.version,
6413        );
6414        let intention = Intention::new(
6415            &mandate.id,
6416            &act.id,
6417            &run.id,
6418            "Perform one bounded action",
6419            "It tests pre-dispatch invalidation",
6420        );
6421        store
6422            .record_mandate_decision(&act, Some(&intention), None)
6423            .await
6424            .unwrap();
6425        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6426        let now = chrono::Utc::now();
6427        let unclaimed = reservation(&mandate, &act, &run, &fence, 1, 41, now);
6428        assert!(
6429            store
6430                .reserve_mandate_action_attempt(&unclaimed)
6431                .await
6432                .unwrap()
6433                .is_some()
6434        );
6435
6436        let mut updated = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6437        updated.version += 1;
6438        updated
6439            .constraints
6440            .push("Owner narrowed the policy".to_string());
6441        store.update_mandate(&updated).await.unwrap();
6442
6443        let attempts = store
6444            .list_mandate_mutation_attempts_for_run(&run.id)
6445            .await
6446            .unwrap();
6447        assert_eq!(attempts.len(), 1);
6448        assert_eq!(
6449            attempts[0].status,
6450            MandateMutationAttemptStatus::NeverDispatched
6451        );
6452        assert!(attempts[0].completed_at.is_some());
6453        let quota = store
6454            .get_mandate_mutation_quota_state(
6455                &mandate.id,
6456                &(now + chrono::Duration::seconds(1)).to_rfc3339(),
6457            )
6458            .await
6459            .unwrap()
6460            .unwrap();
6461        assert_eq!(quota.reserved_in_rolling_24h, 0);
6462        assert_eq!(quota.remaining_in_rolling_24h, 24);
6463    }
6464
6465    #[tokio::test]
6466    async fn pause_marks_claimed_unresolved_reservation_ambiguous_and_run_reconciliation_required()
6467    {
6468        let (store, _database) = test_store().await;
6469        let (goal, mandate) = controller("owner-session", 1);
6470        let run = claim_and_start_run(&store, &goal, &mandate).await;
6471        let act = MandateDecisionCycle::new(
6472            &mandate.id,
6473            &run.id,
6474            MandateDecisionOutcome::Act,
6475            "One mutation was authorized before the pause",
6476            mandate.version,
6477        );
6478        let intention = Intention::new(
6479            &mandate.id,
6480            &act.id,
6481            &run.id,
6482            "Perform one bounded action",
6483            "It tests claimed-dispatch invalidation",
6484        );
6485        store
6486            .record_mandate_decision(&act, Some(&intention), None)
6487            .await
6488            .unwrap();
6489        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6490        let now = chrono::Utc::now();
6491        let claimed = reservation(&mandate, &act, &run, &fence, 1, 42, now);
6492        assert!(
6493            store
6494                .reserve_mandate_action_attempt(&claimed)
6495                .await
6496                .unwrap()
6497                .is_some()
6498        );
6499        assert!(
6500            store
6501                .claim_mandate_mutation_dispatch(&dispatch_claim(
6502                    &claimed,
6503                    now + chrono::Duration::milliseconds(1),
6504                ))
6505                .await
6506                .unwrap()
6507        );
6508
6509        assert!(
6510            store
6511                .transition_mandate_status(
6512                    &mandate.id,
6513                    MandateStatus::Active,
6514                    MandateStatus::Paused,
6515                )
6516                .await
6517                .unwrap()
6518        );
6519        let attempts = store
6520            .list_mandate_mutation_attempts_for_run(&run.id)
6521            .await
6522            .unwrap();
6523        assert_eq!(attempts.len(), 1);
6524        assert_eq!(attempts[0].status, MandateMutationAttemptStatus::Ambiguous);
6525        assert!(attempts[0].completed_at.is_some());
6526        let closed_run = store
6527            .get_goal_runs(&goal.id)
6528            .await
6529            .unwrap()
6530            .into_iter()
6531            .find(|candidate| candidate.id == run.id)
6532            .unwrap();
6533        assert_eq!(closed_run.status, "cancelled");
6534        assert_eq!(
6535            closed_run.outcome_summary.as_deref(),
6536            Some("mandate_reconciliation_required:lifecycle_invalidated_after_dispatch_claim")
6537        );
6538        let notice_count: i64 = sqlx::query_scalar(
6539            "SELECT COUNT(*) FROM notification_queue
6540             WHERE id = ? AND notification_type = 'mandate_reconciliation_required'
6541               AND priority = 'critical' AND expires_at IS NULL",
6542        )
6543        .bind(format!("mandate-run-notice:{}", run.id))
6544        .fetch_one(&store.pool)
6545        .await
6546        .unwrap();
6547        assert_eq!(notice_count, 1);
6548        let suspended = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6549        assert_eq!(suspended.status, MandateStatus::AwaitingInput);
6550        assert_eq!(
6551            suspended.suspension.as_ref().map(|value| value.kind),
6552            Some(MandateSuspensionKind::ReconciliationRequired)
6553        );
6554        assert!(
6555            store
6556                .resolve_mandate_suspension(
6557                    &mandate.id,
6558                    suspended.version,
6559                    MandateSuspensionKind::ReconciliationRequired,
6560                    None,
6561                    Some(MandateReconciliationResolution::ConfirmedNoEffect),
6562                    "I inspected the exact target and confirmed no effect occurred.",
6563                    "owner-session",
6564                )
6565                .await
6566                .unwrap()
6567        );
6568        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6569        assert_eq!(resumed.status, MandateStatus::Active);
6570        assert!(resumed.suspension.is_none());
6571        let reconciliations: i64 = sqlx::query_scalar(
6572            "SELECT COUNT(*) FROM mandate_reconciliations
6573             WHERE mandate_id = ? AND resolution = 'confirmed_no_effect'",
6574        )
6575        .bind(&mandate.id)
6576        .fetch_one(&store.pool)
6577        .await
6578        .unwrap();
6579        assert_eq!(reconciliations, 1);
6580    }
6581
6582    #[tokio::test]
6583    async fn policy_update_with_claimed_unresolved_mutation_lands_awaiting_input() {
6584        let (store, _database) = test_store().await;
6585        let (goal, mandate) = controller("owner-session", 1);
6586        let run = claim_and_start_run(&store, &goal, &mandate).await;
6587        let act = MandateDecisionCycle::new(
6588            &mandate.id,
6589            &run.id,
6590            MandateDecisionOutcome::Act,
6591            "One action was authorized under the old policy",
6592            mandate.version,
6593        );
6594        let intention = Intention::new(
6595            &mandate.id,
6596            &act.id,
6597            &run.id,
6598            "Perform one bounded action",
6599            "It tests policy-race reconciliation",
6600        );
6601        store
6602            .record_mandate_decision(&act, Some(&intention), None)
6603            .await
6604            .unwrap();
6605        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6606        let now = chrono::Utc::now();
6607        let claimed = reservation(&mandate, &act, &run, &fence, 1, 43, now);
6608        assert!(
6609            store
6610                .reserve_mandate_action_attempt(&claimed)
6611                .await
6612                .unwrap()
6613                .is_some()
6614        );
6615        assert!(
6616            store
6617                .claim_mandate_mutation_dispatch(&dispatch_claim(
6618                    &claimed,
6619                    now + chrono::Duration::milliseconds(1),
6620                ))
6621                .await
6622                .unwrap()
6623        );
6624
6625        let mut updated = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6626        updated.version += 1;
6627        updated
6628            .constraints
6629            .push("Owner narrowed the policy after dispatch".to_string());
6630        store.update_mandate(&updated).await.unwrap();
6631
6632        let stored = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6633        assert_eq!(stored.version, updated.version);
6634        assert_eq!(stored.status, MandateStatus::AwaitingInput);
6635        assert_eq!(
6636            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6637            "paused"
6638        );
6639        assert_eq!(
6640            store
6641                .list_mandate_mutation_attempts_for_run(&run.id)
6642                .await
6643                .unwrap()[0]
6644                .status,
6645            MandateMutationAttemptStatus::Ambiguous
6646        );
6647        let notices: i64 =
6648            sqlx::query_scalar("SELECT COUNT(*) FROM notification_queue WHERE id = ?")
6649                .bind(format!("mandate-run-notice:{}", run.id))
6650                .fetch_one(&store.pool)
6651                .await
6652                .unwrap();
6653        assert_eq!(notices, 1);
6654    }
6655
6656    #[tokio::test]
6657    async fn due_review_lease_has_one_winner_and_requires_its_token_to_release() {
6658        let (store, _database) = test_store().await;
6659        let (goal, mandate) = controller("owner-session", 2);
6660        store
6661            .create_mandate_controller(&goal, &mandate)
6662            .await
6663            .unwrap();
6664
6665        let (left, right) = tokio::join!(
6666            store.claim_due_mandates(1, "heartbeat-a", 300),
6667            store.claim_due_mandates(1, "heartbeat-b", 300)
6668        );
6669        let mut winners = left.unwrap();
6670        winners.extend(right.unwrap());
6671        assert_eq!(winners.len(), 1);
6672        let lease_token = winners[0].review_lease_token.clone().unwrap();
6673        assert!(
6674            !store
6675                .release_mandate_review_lease(
6676                    &mandate.id,
6677                    "wrong-token",
6678                    &(chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339(),
6679                )
6680                .await
6681                .unwrap()
6682        );
6683
6684        let retry_at = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
6685        assert!(
6686            store
6687                .release_mandate_review_lease(&mandate.id, &lease_token, &retry_at)
6688                .await
6689                .unwrap()
6690        );
6691        let released = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6692        assert_eq!(released.next_review_at, retry_at);
6693        assert!(released.review_lease_token.is_none());
6694        assert!(
6695            store
6696                .claim_due_mandates(1, "heartbeat-c", 300)
6697                .await
6698                .unwrap()
6699                .is_empty()
6700        );
6701    }
6702
6703    #[tokio::test]
6704    async fn claiming_reviews_atomically_closes_expired_mandates_and_controllers() {
6705        let (store, _database) = test_store().await;
6706        let (goal, mut mandate) = controller("owner-session", 2);
6707        mandate.expires_at = Some((chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339());
6708        store
6709            .create_mandate_controller(&goal, &mandate)
6710            .await
6711            .unwrap();
6712
6713        assert!(
6714            store
6715                .claim_due_mandates(1, "heartbeat", 300)
6716                .await
6717                .unwrap()
6718                .is_empty()
6719        );
6720        assert_eq!(
6721            store
6722                .get_mandate(&mandate.id)
6723                .await
6724                .unwrap()
6725                .unwrap()
6726                .status,
6727            MandateStatus::Completed
6728        );
6729        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
6730        assert_eq!(controller.status, "completed");
6731        assert!(controller.completed_at.is_some());
6732    }
6733
6734    #[tokio::test]
6735    async fn decision_validates_policy_version_and_commits_transition_atomically() {
6736        let (store, _database) = test_store().await;
6737        let (goal, mandate) = controller("owner-session", 2);
6738        let run = claim_and_start_run(&store, &goal, &mandate).await;
6739
6740        let stale = MandateDecisionCycle::new(
6741            &mandate.id,
6742            &run.id,
6743            MandateDecisionOutcome::Wait,
6744            "Nothing useful yet",
6745            mandate.version + 1,
6746        );
6747        assert!(
6748            store
6749                .record_mandate_decision(&stale, None, None)
6750                .await
6751                .is_err()
6752        );
6753        assert!(
6754            store
6755                .get_mandate_decision_for_run(&run.id)
6756                .await
6757                .unwrap()
6758                .is_none()
6759        );
6760        assert!(
6761            store
6762                .get_mandate(&mandate.id)
6763                .await
6764                .unwrap()
6765                .unwrap()
6766                .review_lease_token
6767                .is_some()
6768        );
6769
6770        let mut wait = MandateDecisionCycle::new(
6771            &mandate.id,
6772            &run.id,
6773            MandateDecisionOutcome::Wait,
6774            "No action clears the quality threshold",
6775            mandate.version,
6776        );
6777        wait.reconsider_at = Some((chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339());
6778        let before = chrono::Utc::now();
6779        store
6780            .record_mandate_decision(&wait, None, None)
6781            .await
6782            .unwrap();
6783
6784        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6785        assert_eq!(loaded.status, MandateStatus::Active);
6786        assert!(loaded.review_lease_token.is_none());
6787        let next = chrono::DateTime::parse_from_rfc3339(&loaded.next_review_at)
6788            .unwrap()
6789            .with_timezone(&chrono::Utc);
6790        assert!(next >= before + chrono::Duration::seconds(mandate.min_review_secs - 1));
6791        let stored_decision = store
6792            .get_mandate_decision_for_run(&run.id)
6793            .await
6794            .unwrap()
6795            .unwrap();
6796        assert_eq!(stored_decision.mandate_version, mandate.version);
6797        assert_eq!(stored_decision.reconsider_at, Some(loaded.next_review_at));
6798        let history = store.list_mandate_decisions(&mandate.id, 10).await.unwrap();
6799        assert_eq!(history.len(), 1);
6800        assert_eq!(history[0].id, stored_decision.id);
6801        assert_eq!(history[0].outcome, MandateDecisionOutcome::Wait);
6802    }
6803
6804    /// A bounded mandate's objective control is advisory: its decisions do
6805    /// not wait on a measurement. Autopilot keeps the measured control loop.
6806    #[tokio::test]
6807    async fn bounded_mandate_with_objective_control_decides_without_a_measurement() {
6808        for (mode, gated) in [
6809            (MandateAutonomyMode::Bounded, false),
6810            (MandateAutonomyMode::Autopilot, true),
6811        ] {
6812            let (store, _database) = test_store().await;
6813            let (goal, mut mandate) = controller("owner-session", 1);
6814            mandate.autonomy_mode = mode;
6815            mandate.objective_control = Some(objective_control());
6816            let run = claim_and_start_run(&store, &goal, &mandate).await;
6817            let wait = MandateDecisionCycle::new(
6818                &mandate.id,
6819                &run.id,
6820                MandateDecisionOutcome::Wait,
6821                "Nothing new is worth acting on yet",
6822                mandate.version,
6823            );
6824            let result = store.record_mandate_decision(&wait, None, None).await;
6825            if gated {
6826                let error = result.expect_err("autopilot decisions need a measurement");
6827                assert!(
6828                    error
6829                        .to_string()
6830                        .contains("receipt-backed metric measurement"),
6831                    "{error}"
6832                );
6833            } else {
6834                result.expect("a bounded mandate decides without a measurement");
6835                let stored = store
6836                    .get_mandate_decision_for_run(&run.id)
6837                    .await
6838                    .unwrap()
6839                    .expect("decision stored");
6840                assert_eq!(stored.outcome, MandateDecisionOutcome::Wait);
6841            }
6842        }
6843    }
6844
6845    #[tokio::test]
6846    async fn act_for_value_contract_requires_exact_owner_criterion_and_full_judgment() {
6847        let (store, _database) = test_store().await;
6848        let (goal, mut mandate) = controller("owner-session", 1);
6849        mandate.success_criteria = vec![
6850            "Each intervention provides verified useful information to the audience".to_string(),
6851        ];
6852        let run = claim_and_start_run(&store, &goal, &mandate).await;
6853        let act = MandateDecisionCycle::new(
6854            &mandate.id,
6855            &run.id,
6856            MandateDecisionOutcome::Act,
6857            "Current evidence supports one bounded useful intervention",
6858            mandate.version,
6859        );
6860        let mut intention = Intention::new(
6861            &mandate.id,
6862            &act.id,
6863            &run.id,
6864            "Provide one verified useful update",
6865            "The intervention advances the confirmed value criterion",
6866        );
6867        intention.value_criterion = Some("Publish something on every review".to_string());
6868        intention.expected_benefit =
6869            Some("Give the audience current, grounded information".to_string());
6870        intention.risk = Some("Low volume limits attention and reputation costs".to_string());
6871        intention.invalidation_criteria =
6872            Some("The information is stale, duplicate, or unsupported".to_string());
6873
6874        let error = store
6875            .record_mandate_decision(&act, Some(&intention), None)
6876            .await
6877            .unwrap_err();
6878        assert!(
6879            error
6880                .to_string()
6881                .contains("not an exact owner-authored success criterion")
6882        );
6883
6884        intention.value_criterion = mandate.success_criteria.first().cloned();
6885        store
6886            .record_mandate_decision(&act, Some(&intention), None)
6887            .await
6888            .unwrap();
6889        assert_eq!(
6890            store.list_intentions(&mandate.id, 1).await.unwrap()[0],
6891            intention
6892        );
6893    }
6894
6895    #[tokio::test]
6896    async fn action_reservations_require_a_unique_live_proof_and_respect_the_cycle_cap() {
6897        let (store, _database) = test_store().await;
6898        let (goal, mandate) = controller("owner-session", 2);
6899        let run = claim_and_start_run(&store, &goal, &mandate).await;
6900        let act = MandateDecisionCycle::new(
6901            &mandate.id,
6902            &run.id,
6903            MandateDecisionOutcome::Act,
6904            "A sourced reply is timely and useful",
6905            mandate.version,
6906        );
6907        let intention = Intention::new(
6908            &mandate.id,
6909            &act.id,
6910            &run.id,
6911            "Post one sourced reply",
6912            "It contributes concrete information",
6913        );
6914        store
6915            .record_mandate_decision(&act, Some(&intention), None)
6916            .await
6917            .unwrap();
6918        assert_eq!(
6919            store.list_intentions(&mandate.id, 10).await.unwrap(),
6920            vec![intention]
6921        );
6922        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6923        let now = chrono::Utc::now();
6924        let first = reservation(&mandate, &act, &run, &fence, 1, 10, now);
6925
6926        assert!(
6927            store
6928                .reserve_mandate_action_attempt(&first)
6929                .await
6930                .unwrap()
6931                .is_some()
6932        );
6933        assert!(
6934            store
6935                .reserve_mandate_action_attempt(&first)
6936                .await
6937                .unwrap()
6938                .is_none()
6939        );
6940        assert!(
6941            store
6942                .reserve_mandate_action_attempt(&reservation(
6943                    &mandate,
6944                    &act,
6945                    &run,
6946                    &fence,
6947                    2,
6948                    11,
6949                    now + chrono::Duration::seconds(901),
6950                ))
6951                .await
6952                .unwrap()
6953                .is_some()
6954        );
6955        assert!(
6956            store
6957                .reserve_mandate_action_attempt(&reservation(
6958                    &mandate,
6959                    &act,
6960                    &run,
6961                    &fence,
6962                    3,
6963                    12,
6964                    now + chrono::Duration::seconds(1_802),
6965                ))
6966                .await
6967                .unwrap()
6968                .is_none()
6969        );
6970    }
6971
6972    #[tokio::test]
6973    async fn owner_policy_update_invalidates_an_existing_action_budget() {
6974        let (store, _database) = test_store().await;
6975        let (goal, mandate) = controller("owner-session", 3);
6976        let run = claim_and_start_run(&store, &goal, &mandate).await;
6977        let act = MandateDecisionCycle::new(
6978            &mandate.id,
6979            &run.id,
6980            MandateDecisionOutcome::Act,
6981            "One action currently fits the policy",
6982            mandate.version,
6983        );
6984        let intention = Intention::new(
6985            &mandate.id,
6986            &act.id,
6987            &run.id,
6988            "Perform the authorized action",
6989            "It advances the mandate",
6990        );
6991        store
6992            .record_mandate_decision(&act, Some(&intention), None)
6993            .await
6994            .unwrap();
6995        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6996        let now = chrono::Utc::now();
6997        assert!(
6998            store
6999                .reserve_mandate_action_attempt(&reservation(
7000                    &mandate, &act, &run, &fence, 1, 20, now,
7001                ))
7002                .await
7003                .unwrap()
7004                .is_some()
7005        );
7006
7007        let mut owner_update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7008        owner_update.version += 1;
7009        owner_update
7010            .constraints
7011            .push("New owner constraint".to_string());
7012        store.update_mandate(&owner_update).await.unwrap();
7013
7014        assert!(
7015            store
7016                .reserve_mandate_action_attempt(&reservation(
7017                    &mandate,
7018                    &act,
7019                    &run,
7020                    &fence,
7021                    2,
7022                    21,
7023                    now + chrono::Duration::seconds(901),
7024                ))
7025                .await
7026                .unwrap()
7027                .is_none()
7028        );
7029    }
7030
7031    #[tokio::test]
7032    async fn concurrent_reservations_have_one_last_slot_winner() {
7033        let (store, _database) = test_store().await;
7034        let (goal, mut mandate) = controller("owner-session", 1);
7035        mandate.authority.max_mutating_actions_per_rolling_24h = 1;
7036        let run = claim_and_start_run(&store, &goal, &mandate).await;
7037        let act = MandateDecisionCycle::new(
7038            &mandate.id,
7039            &run.id,
7040            MandateDecisionOutcome::Act,
7041            "One exact action is justified",
7042            mandate.version,
7043        );
7044        let intention = Intention::new(
7045            &mandate.id,
7046            &act.id,
7047            &run.id,
7048            "Perform exactly one action",
7049            "It tests the atomic quota fence",
7050        );
7051        store
7052            .record_mandate_decision(&act, Some(&intention), None)
7053            .await
7054            .unwrap();
7055        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7056        let now = chrono::Utc::now();
7057        let left = reservation(&mandate, &act, &run, &fence, 1, 101, now);
7058        let right = reservation(&mandate, &act, &run, &fence, 1, 102, now);
7059        let (left, right) = tokio::join!(
7060            store.reserve_mandate_action_attempt(&left),
7061            store.reserve_mandate_action_attempt(&right),
7062        );
7063        let winners = [left.unwrap(), right.unwrap()]
7064            .into_iter()
7065            .filter(Option::is_some)
7066            .count();
7067        assert_eq!(winners, 1);
7068        let attempts = store
7069            .list_mandate_mutation_attempts_for_run(&run.id)
7070            .await
7071            .unwrap();
7072        assert_eq!(attempts.len(), 1);
7073    }
7074
7075    async fn record_refused_receipt(
7076        store: &SqliteWorkStore,
7077        task_id: &str,
7078        reason_code: &str,
7079        effect: &str,
7080    ) {
7081        let data = serde_json::json!({
7082            "task_id": task_id,
7083            "receipt": {
7084                "invocation_stage": "rejected_before_dispatch",
7085                "outcome_status": "blocked",
7086                "access_denial": {"reason_code": reason_code},
7087                "semantics": {"effect": effect},
7088            },
7089        });
7090        sqlx::query(
7091            "INSERT INTO events (session_id, event_type, data, created_at, task_id)
7092             VALUES ('owner-session', 'tool_result', ?, ?, ?)",
7093        )
7094        .bind(data.to_string())
7095        .bind(chrono::Utc::now().to_rfc3339())
7096        .bind(task_id)
7097        .execute(&store.pool)
7098        .await
7099        .unwrap();
7100    }
7101
7102    /// An ACT whose worker was refused before dispatch and reported success.
7103    /// `receipt` is the refusal's (reason code, effect), when there is one.
7104    async fn finalize_refused_act(
7105        receipt: Option<(&str, &str)>,
7106    ) -> (
7107        SqliteWorkStore,
7108        tempfile::NamedTempFile,
7109        Task,
7110        GoalRun,
7111        MandateRunFinalizationResult,
7112    ) {
7113        let (store, database) = test_store().await;
7114        let (goal, mandate) = controller("owner-session", 1);
7115        let run = claim_and_start_run(&store, &goal, &mandate).await;
7116        let act = MandateDecisionCycle::new(
7117            &mandate.id,
7118            &run.id,
7119            MandateDecisionOutcome::Act,
7120            "Post one update",
7121            mandate.version,
7122        );
7123        let intention = Intention::new(&mandate.id, &act.id, &run.id, "Post", "Useful");
7124        store
7125            .record_mandate_decision(&act, Some(&intention), None)
7126            .await
7127            .unwrap();
7128        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7129        if let Some((reason_code, effect)) = receipt {
7130            record_refused_receipt(&store, &fence.worker_task.id, reason_code, effect).await;
7131        }
7132        complete_mutation_fence(&store, &fence).await;
7133        let result = store
7134            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7135                mandate_id: mandate.id.clone(),
7136                expected_mandate_version: mandate.version,
7137                goal_run_id: run.id.clone(),
7138                finalized_at: chrono::Utc::now().to_rfc3339(),
7139            })
7140            .await
7141            .unwrap();
7142        (store, database, fence.worker_task, run, result)
7143    }
7144
7145    #[tokio::test]
7146    async fn a_mutation_refused_before_dispatch_names_its_gate() {
7147        let (store, _database, worker, run, result) =
7148            finalize_refused_act(Some(("untrusted_egress_denied", "Mutation"))).await;
7149
7150        let gate = MandateDispatchGate::UntrustedContentCheck;
7151        let reason = MandateReconciliationReason::ActBlockedBeforeDispatch { gate };
7152        let MandateRunFinalizationResult::ReconciliationRequired {
7153            reason: actual,
7154            counts,
7155        } = result
7156        else {
7157            panic!("expected reconciliation, got {result:?}");
7158        };
7159        assert_eq!(actual, reason);
7160        assert_eq!(counts.mutation_reservations, 0);
7161        assert_eq!(counts.failed_or_blocked_tasks, 1, "{counts:?}");
7162
7163        let (status, blocker): (String, Option<String>) =
7164            sqlx::query_as("SELECT status, blocker FROM tasks WHERE id = ?")
7165                .bind(&worker.id)
7166                .fetch_one(&store.pool)
7167                .await
7168                .unwrap();
7169        assert_eq!(status, "blocked");
7170        assert!(
7171            blocker.unwrap().contains(gate.owner_label()),
7172            "the task records its gate"
7173        );
7174        let outcome: String =
7175            sqlx::query_scalar("SELECT outcome_summary FROM goal_runs WHERE id = ?")
7176                .bind(&run.id)
7177                .fetch_one(&store.pool)
7178                .await
7179                .unwrap();
7180        assert_eq!(
7181            outcome,
7182            "mandate_reconciliation_required:act_blocked_before_dispatch:untrusted_content_check"
7183        );
7184    }
7185
7186    /// Without a refused mutation on a receipt there is no gate to name: a
7187    /// refused read, or no receipt at all, leaves an ACT whose ledger proves
7188    /// it changed nothing, which is retried without asking the owner.
7189    #[tokio::test]
7190    async fn only_a_refused_mutation_counts_as_blocked_before_dispatch() {
7191        for receipt in [None, Some(("untrusted_egress_denied", "ReadOnly"))] {
7192            let (store, _database, worker, run, result) = finalize_refused_act(receipt).await;
7193            assert_eq!(
7194                result,
7195                MandateRunFinalizationResult::Rejected {
7196                    reason: MandateFinalizationRejectReason::ActChangedNothing,
7197                },
7198                "{receipt:?}"
7199            );
7200            let (mandate_status, intention_status): (String, String) = sqlx::query_as(
7201                "SELECT m.status, i.status FROM goal_runs r
7202                 JOIN mandates m ON m.goal_id = r.goal_id
7203                 JOIN intentions i ON i.goal_run_id = r.id
7204                 WHERE r.id = ?",
7205            )
7206            .bind(&run.id)
7207            .fetch_one(&store.pool)
7208            .await
7209            .unwrap();
7210            assert_eq!(mandate_status, "active", "no owner reconciliation");
7211            assert_eq!(intention_status, "failed");
7212            let status: String = sqlx::query_scalar("SELECT status FROM tasks WHERE id = ?")
7213                .bind(&worker.id)
7214                .fetch_one(&store.pool)
7215                .await
7216                .unwrap();
7217            assert_eq!(status, "completed");
7218        }
7219    }
7220
7221    #[test]
7222    fn the_owner_notice_names_the_gate_and_says_nothing_went_out() {
7223        let notice = crate::traits::MandateRunNotification::new(
7224            "mandate-synthetic",
7225            1,
7226            "goal-synthetic",
7227            "run-synthetic",
7228            "owner-session",
7229            crate::traits::MandateRunNotificationKind::ReconciliationRequired {
7230                reason: MandateReconciliationReason::ActBlockedBeforeDispatch {
7231                    gate: MandateDispatchGate::UntrustedContentCheck,
7232                },
7233            },
7234            MandateRunProofCounts::default(),
7235            "2026-11-10T00:00:00Z",
7236        );
7237
7238        let message = notice.message();
7239
7240        assert!(message.contains("nothing was published"), "{message}");
7241        assert!(
7242            message.contains("untrusted-content safety check"),
7243            "{message}"
7244        );
7245    }
7246
7247    #[tokio::test]
7248    async fn proof_distinguishes_never_dispatched_from_claimed_ambiguity() {
7249        for claim_before_finalization in [false, true] {
7250            let (store, _database) = test_store().await;
7251            let (goal, mandate) = controller("owner-session", 1);
7252            let run = claim_and_start_run(&store, &goal, &mandate).await;
7253            let act = MandateDecisionCycle::new(
7254                &mandate.id,
7255                &run.id,
7256                MandateDecisionOutcome::Act,
7257                "Exercise the finalizer crash-window classification",
7258                mandate.version,
7259            );
7260            let intention = Intention::new(
7261                &mandate.id,
7262                &act.id,
7263                &run.id,
7264                "Attempt one governed mutation",
7265                "The proof must classify its exact dispatch state",
7266            );
7267            store
7268                .record_mandate_decision(&act, Some(&intention), None)
7269                .await
7270                .unwrap();
7271            let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7272            let now = chrono::Utc::now();
7273            let reserved = reservation(&mandate, &act, &run, &fence, 1, 451, now);
7274            assert!(
7275                store
7276                    .reserve_mandate_action_attempt(&reserved)
7277                    .await
7278                    .unwrap()
7279                    .is_some()
7280            );
7281            if claim_before_finalization {
7282                assert!(
7283                    store
7284                        .claim_mandate_mutation_dispatch(&dispatch_claim(
7285                            &reserved,
7286                            now + chrono::Duration::milliseconds(1),
7287                        ))
7288                        .await
7289                        .unwrap()
7290                );
7291            }
7292            complete_mutation_fence(&store, &fence).await;
7293
7294            let result = store
7295                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7296                    mandate_id: mandate.id.clone(),
7297                    expected_mandate_version: mandate.version,
7298                    goal_run_id: run.id.clone(),
7299                    finalized_at: (now + chrono::Duration::seconds(1)).to_rfc3339(),
7300                })
7301                .await
7302                .unwrap();
7303            if claim_before_finalization {
7304                let MandateRunFinalizationResult::ReconciliationRequired { reason, counts } =
7305                    result
7306                else {
7307                    panic!("a claimed dispatch with no outcome must fail closed: {result:?}")
7308                };
7309                assert_eq!(
7310                    reason,
7311                    MandateReconciliationReason::MutationOutcomeAmbiguous
7312                );
7313                assert_eq!(counts.ambiguous_or_reserved_mutations, 1);
7314                assert_eq!(counts.never_dispatched_mutations, 0);
7315            } else {
7316                // Reserved but never dispatched: provably no effect.
7317                assert_eq!(
7318                    result,
7319                    MandateRunFinalizationResult::Rejected {
7320                        reason: MandateFinalizationRejectReason::ActChangedNothing,
7321                    }
7322                );
7323            }
7324            let attempts = store
7325                .list_mandate_mutation_attempts_for_run(&run.id)
7326                .await
7327                .unwrap();
7328            assert_eq!(attempts.len(), 1);
7329            assert_eq!(
7330                attempts[0].status,
7331                if claim_before_finalization {
7332                    MandateMutationAttemptStatus::Ambiguous
7333                } else {
7334                    MandateMutationAttemptStatus::NeverDispatched
7335                }
7336            );
7337        }
7338    }
7339
7340    #[tokio::test]
7341    async fn evidence_receipts_accept_either_tool_call_id_or_receipt_result_id() {
7342        let (store, _database) = test_store().await;
7343        let (goal, mut mandate) = controller("owner-session", 1);
7344        mandate.objective_control = Some(objective_control());
7345        let run = claim_and_start_run(&store, &goal, &mandate).await;
7346        let task_id = run.root_task_id.as_deref().unwrap();
7347        sqlx::query(
7348            "INSERT INTO events
7349                (session_id, event_type, data, created_at, task_id, tool_name)
7350             VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
7351        )
7352        .bind("owner-session")
7353        .bind(
7354            serde_json::json!({
7355                "task_id": task_id,
7356                "tool_call_id": "call_synthetic_metric",
7357                "name": "http_request",
7358                "result": "synthetic metric value",
7359                "success": true,
7360                "duration_ms": 1,
7361                "receipt": {
7362                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
7363                    "outcome_status": "succeeded",
7364                    "outcome_evidence": "structured_metadata",
7365                    "result_provenance": { "result_id": "sha256:synthetic-metric-digest" }
7366                }
7367            })
7368            .to_string(),
7369        )
7370        .bind(chrono::Utc::now().to_rfc3339())
7371        .bind(task_id)
7372        .execute(&store.pool)
7373        .await
7374        .unwrap();
7375
7376        for receipt_id in ["call_synthetic_metric", "sha256:synthetic-metric-digest"] {
7377            let measurement = MandateObjectiveMeasurement::new(
7378                &mandate.id,
7379                mandate.version,
7380                &run.id,
7381                12_000_000,
7382                9_500,
7383                vec![receipt_id.to_string()],
7384                &chrono::Utc::now().to_rfc3339(),
7385            );
7386            store
7387                .record_mandate_objective_measurement(&measurement)
7388                .await
7389                .unwrap_or_else(|error| panic!("{receipt_id} should be accepted: {error}"));
7390        }
7391        let invented = MandateObjectiveMeasurement::new(
7392            &mandate.id,
7393            mandate.version,
7394            &run.id,
7395            12_000_000,
7396            9_500,
7397            vec!["sha256:not-a-receipt".to_string()],
7398            &chrono::Utc::now().to_rfc3339(),
7399        );
7400        assert!(
7401            store
7402                .record_mandate_objective_measurement(&invented)
7403                .await
7404                .is_err()
7405        );
7406    }
7407
7408    #[tokio::test]
7409    async fn runtime_fallback_wait_bypasses_semantic_gates_and_finalizes_as_deliberator_failure() {
7410        let (store, _database) = test_store().await;
7411        let (goal, mut mandate) = controller("owner-session", 1);
7412        // The measured control loop (gate, stagnation) is autopilot's.
7413        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
7414        mandate.objective_control = Some(objective_control());
7415        let run = claim_and_start_run(&store, &goal, &mandate).await;
7416
7417        // A model-authored WAIT on a controlled mandate still needs a
7418        // current-run measurement.
7419        let model_wait = MandateDecisionCycle::new(
7420            &mandate.id,
7421            &run.id,
7422            MandateDecisionOutcome::Wait,
7423            "model decided to wait without measuring",
7424            mandate.version,
7425        );
7426        let error = store
7427            .record_mandate_decision(&model_wait, None, None)
7428            .await
7429            .unwrap_err();
7430        assert!(error.to_string().contains("metric measurement"), "{error}");
7431
7432        // The runtime fallback carries no authority and must always persist,
7433        // regardless of objective control state.
7434        let fallback =
7435            MandateDecisionCycle::runtime_fallback_wait(&mandate, &run.id, chrono::Utc::now());
7436        assert!(fallback.is_runtime_fallback());
7437        store
7438            .record_mandate_decision(&fallback, None, None)
7439            .await
7440            .unwrap();
7441        let mut spoofed = fallback.clone();
7442        spoofed.id = uuid::Uuid::new_v4().to_string();
7443        spoofed.evidence_receipt_ids = vec!["call_anything".to_string()];
7444        assert!(
7445            store
7446                .record_mandate_decision(&spoofed, None, None)
7447                .await
7448                .is_err()
7449        );
7450
7451        let root_attempt = store
7452            .claim_task_with_lease(
7453                run.root_task_id.as_deref().unwrap(),
7454                "fallback-root",
7455                Some("profile-task-lead"),
7456                7_200,
7457            )
7458            .await
7459            .unwrap()
7460            .unwrap();
7461        assert!(
7462            store
7463                .patch_task_from_attempt(
7464                    &root_attempt.id,
7465                    &root_attempt.lease_token,
7466                    &crate::traits::TaskAttemptPatch {
7467                        status: "completed".to_string(),
7468                        result: Some("task lead returned without a decision".to_string()),
7469                        ..Default::default()
7470                    },
7471                )
7472                .await
7473                .unwrap()
7474        );
7475        let result = store
7476            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7477                mandate_id: mandate.id.clone(),
7478                expected_mandate_version: mandate.version,
7479                goal_run_id: run.id.clone(),
7480                finalized_at: chrono::Utc::now().to_rfc3339(),
7481            })
7482            .await
7483            .unwrap();
7484        assert_eq!(
7485            result,
7486            MandateRunFinalizationResult::Rejected {
7487                reason: MandateFinalizationRejectReason::DeliberatorFailed
7488            }
7489        );
7490        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7491        assert_eq!(current.status, MandateStatus::Active);
7492        assert_eq!(
7493            store.get_goal_runs(&goal.id).await.unwrap()[0]
7494                .outcome_summary
7495                .as_deref(),
7496            Some("mandate_review_failed:deliberator_failed")
7497        );
7498    }
7499
7500    #[tokio::test]
7501    async fn missing_decision_closes_run_schedules_retry_and_commits_review_failed_notice() {
7502        let (store, _database) = test_store().await;
7503        let (goal, mandate) = controller("owner-session", 1);
7504        let run = claim_and_start_run(&store, &goal, &mandate).await;
7505        let root_attempt = store
7506            .claim_task_with_lease(
7507                run.root_task_id.as_deref().unwrap(),
7508                "decision-missing-root",
7509                Some("profile-task-lead"),
7510                7_200,
7511            )
7512            .await
7513            .unwrap()
7514            .unwrap();
7515        assert!(
7516            store
7517                .patch_task_from_attempt(
7518                    &root_attempt.id,
7519                    &root_attempt.lease_token,
7520                    &crate::traits::TaskAttemptPatch {
7521                        status: "completed".to_string(),
7522                        result: Some("task lead returned without a decision".to_string()),
7523                        ..Default::default()
7524                    },
7525                )
7526                .await
7527                .unwrap()
7528        );
7529        let finalized_at = chrono::Utc::now();
7530
7531        let result = store
7532            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7533                mandate_id: mandate.id.clone(),
7534                expected_mandate_version: mandate.version,
7535                goal_run_id: run.id.clone(),
7536                finalized_at: finalized_at.to_rfc3339(),
7537            })
7538            .await
7539            .unwrap();
7540        assert_eq!(
7541            result,
7542            MandateRunFinalizationResult::Rejected {
7543                reason: MandateFinalizationRejectReason::DecisionMissing
7544            }
7545        );
7546        assert_eq!(
7547            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
7548            "failed"
7549        );
7550        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7551        assert_eq!(current.status, MandateStatus::Active);
7552        assert!(
7553            chrono::DateTime::parse_from_rfc3339(&current.next_review_at)
7554                .unwrap()
7555                .with_timezone(&chrono::Utc)
7556                >= finalized_at + chrono::Duration::seconds(mandate.min_review_secs)
7557        );
7558        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
7559        assert_eq!(controller.status, "active");
7560        assert_eq!(controller.dispatch_failures, 1);
7561        let queued: i64 = sqlx::query_scalar(
7562            "SELECT COUNT(*) FROM notification_queue
7563             WHERE id = ? AND notification_type = 'mandate_review_failed'
7564               AND priority = 'critical' AND expires_at IS NULL",
7565        )
7566        .bind(format!("mandate-run-notice:{}", run.id))
7567        .fetch_one(&store.pool)
7568        .await
7569        .unwrap();
7570        assert_eq!(queued, 1);
7571    }
7572
7573    #[tokio::test]
7574    async fn invalid_decision_state_pauses_controller_and_commits_review_failed_notice() {
7575        let (store, _database) = test_store().await;
7576        let (goal, mandate) = controller("owner-session", 1);
7577        let run = claim_and_start_run(&store, &goal, &mandate).await;
7578        let root_attempt = store
7579            .claim_task_with_lease(
7580                run.root_task_id.as_deref().unwrap(),
7581                "invalid-decision-root",
7582                Some("profile-task-lead"),
7583                7_200,
7584            )
7585            .await
7586            .unwrap()
7587            .unwrap();
7588        let decision = MandateDecisionCycle::new(
7589            &mandate.id,
7590            &run.id,
7591            MandateDecisionOutcome::Act,
7592            "Persist a valid row before simulating corruption",
7593            mandate.version,
7594        );
7595        let intention = Intention::new(
7596            &mandate.id,
7597            &decision.id,
7598            &run.id,
7599            "A committed intention that cannot belong to WAIT",
7600            "It creates a valid but inconsistent persisted decision state",
7601        );
7602        store
7603            .record_mandate_decision(&decision, Some(&intention), Some(&root_attempt.id))
7604            .await
7605            .unwrap();
7606        sqlx::query("UPDATE mandate_decision_cycles SET outcome = 'wait' WHERE id = ?")
7607            .bind(&decision.id)
7608            .execute(&store.pool)
7609            .await
7610            .unwrap();
7611        assert!(
7612            store
7613                .patch_task_from_attempt(
7614                    &root_attempt.id,
7615                    &root_attempt.lease_token,
7616                    &crate::traits::TaskAttemptPatch {
7617                        status: "completed".to_string(),
7618                        result: Some("invalid decision state simulated".to_string()),
7619                        ..Default::default()
7620                    },
7621                )
7622                .await
7623                .unwrap()
7624        );
7625
7626        let result = store
7627            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7628                mandate_id: mandate.id.clone(),
7629                expected_mandate_version: mandate.version,
7630                goal_run_id: run.id.clone(),
7631                finalized_at: chrono::Utc::now().to_rfc3339(),
7632            })
7633            .await
7634            .unwrap();
7635        assert_eq!(
7636            result,
7637            MandateRunFinalizationResult::Rejected {
7638                reason: MandateFinalizationRejectReason::InvalidDecisionState
7639            }
7640        );
7641        assert_eq!(
7642            store
7643                .get_mandate(&mandate.id)
7644                .await
7645                .unwrap()
7646                .unwrap()
7647                .status,
7648            MandateStatus::AwaitingInput
7649        );
7650        assert_eq!(
7651            store.get_goal(&goal.id).await.unwrap().unwrap().status,
7652            "paused"
7653        );
7654        assert_eq!(
7655            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
7656            "failed"
7657        );
7658        let queued: i64 = sqlx::query_scalar(
7659            "SELECT COUNT(*) FROM notification_queue
7660             WHERE id = ? AND notification_type = 'mandate_review_failed'
7661               AND priority = 'critical' AND expires_at IS NULL",
7662        )
7663        .bind(format!("mandate-run-notice:{}", run.id))
7664        .fetch_one(&store.pool)
7665        .await
7666        .unwrap();
7667        assert_eq!(queued, 1);
7668    }
7669
7670    #[tokio::test]
7671    async fn ask_and_stop_atomically_change_mandate_and_controller_status() {
7672        for (outcome, expected_mandate, expected_goal) in [
7673            (
7674                MandateDecisionOutcome::Ask,
7675                MandateStatus::AwaitingInput,
7676                "paused",
7677            ),
7678            (
7679                MandateDecisionOutcome::Stop,
7680                MandateStatus::Completed,
7681                "completed",
7682            ),
7683        ] {
7684            let (store, _database) = test_store().await;
7685            let (goal, mandate) = controller("owner-session", 1);
7686            let run = claim_and_start_run(&store, &goal, &mandate).await;
7687            let root_attempt = store
7688                .claim_task_with_lease(
7689                    run.root_task_id.as_deref().unwrap(),
7690                    "non-action-root",
7691                    Some("profile-task-lead"),
7692                    7_200,
7693                )
7694                .await
7695                .unwrap()
7696                .unwrap();
7697            let mut decision = MandateDecisionCycle::new(
7698                &mandate.id,
7699                &run.id,
7700                outcome,
7701                "The mandate cannot safely proceed",
7702                mandate.version,
7703            );
7704            if outcome == MandateDecisionOutcome::Ask {
7705                decision.question = Some("May I broaden the allowed target?".to_string());
7706            } else {
7707                decision.termination_kind = Some(MandateTerminationKind::SafetyTermination);
7708            }
7709            store
7710                .record_mandate_decision(&decision, None, Some(&root_attempt.id))
7711                .await
7712                .unwrap();
7713            assert_eq!(
7714                store
7715                    .get_mandate(&mandate.id)
7716                    .await
7717                    .unwrap()
7718                    .unwrap()
7719                    .status,
7720                MandateStatus::Active,
7721                "the lifecycle transition remains provisional until proof finalization"
7722            );
7723            assert_eq!(
7724                store.get_goal(&goal.id).await.unwrap().unwrap().status,
7725                "active"
7726            );
7727            assert!(
7728                store
7729                    .patch_task_from_attempt(
7730                        &root_attempt.id,
7731                        &root_attempt.lease_token,
7732                        &crate::traits::TaskAttemptPatch {
7733                            status: "completed".to_string(),
7734                            result: Some("non-action decision durably recorded".to_string()),
7735                            ..Default::default()
7736                        },
7737                    )
7738                    .await
7739                    .unwrap()
7740            );
7741            let result = store
7742                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7743                    mandate_id: mandate.id.clone(),
7744                    expected_mandate_version: mandate.version,
7745                    goal_run_id: run.id.clone(),
7746                    finalized_at: chrono::Utc::now().to_rfc3339(),
7747                })
7748                .await
7749                .unwrap();
7750            assert!(matches!(
7751                result,
7752                MandateRunFinalizationResult::NonActionSatisfied {
7753                    outcome: finalized_outcome,
7754                    ..
7755                } if finalized_outcome == outcome
7756            ));
7757            assert_eq!(
7758                store
7759                    .get_mandate(&mandate.id)
7760                    .await
7761                    .unwrap()
7762                    .unwrap()
7763                    .status,
7764                expected_mandate
7765            );
7766            assert_eq!(
7767                store.get_goal(&goal.id).await.unwrap().unwrap().status,
7768                expected_goal
7769            );
7770        }
7771    }
7772
7773    #[tokio::test]
7774    async fn receipt_backed_stop_and_learning_are_same_mandate_only() {
7775        let (store, _database) = test_store().await;
7776        let (goal, mut mandate) = controller("owner-session", 0);
7777        mandate.success_criteria = vec!["Account stewardship is no longer needed".to_string()];
7778        let run = claim_and_start_run(&store, &goal, &mandate).await;
7779        let root_task_id = run.root_task_id.as_deref().unwrap();
7780        let root_attempt = store
7781            .claim_task_with_lease(
7782                root_task_id,
7783                "receipt-backed-stop",
7784                Some("profile-task-lead"),
7785                7_200,
7786            )
7787            .await
7788            .unwrap()
7789            .unwrap();
7790
7791        let receipt = aidaemon_events::ToolReceiptV1::from_metadata(
7792            &crate::traits::ToolCallMetadata {
7793                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
7794                semantics: crate::traits::ToolCallSemantics::observation(),
7795                ..Default::default()
7796            },
7797            crate::traits::ToolOutcomeStatus::Succeeded,
7798            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
7799            None,
7800        );
7801        let result = aidaemon_events::ToolResultData {
7802            message_id: None,
7803            tool_call_id: "observation-receipt-1".to_string(),
7804            name: "web_fetch".to_string(),
7805            result: "bounded observation".to_string(),
7806            success: true,
7807            duration_ms: 1,
7808            error: None,
7809            task_id: Some(root_task_id.to_string()),
7810            annotations: vec![],
7811            turn_id: None,
7812            attachments: vec![],
7813            receipt: Some(receipt),
7814        };
7815        sqlx::query(
7816            "INSERT INTO events (session_id, event_type, data, created_at, task_id, tool_name)
7817             VALUES (?, 'tool_result', ?, ?, ?, 'web_fetch')",
7818        )
7819        .bind("specialist:mandate")
7820        .bind(serde_json::to_string(&result).unwrap())
7821        .bind(chrono::Utc::now().to_rfc3339())
7822        .bind(root_task_id)
7823        .execute(&store.pool)
7824        .await
7825        .unwrap();
7826
7827        let mut decision = MandateDecisionCycle::new(
7828            &mandate.id,
7829            &run.id,
7830            MandateDecisionOutcome::Stop,
7831            "A current structured observation proves the owner criterion",
7832            mandate.version,
7833        );
7834        decision.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
7835        decision.activity_level = MandateActivityLevel::Urgent;
7836        decision.termination_match = mandate.success_criteria.first().cloned();
7837        decision.evidence_receipt_ids = vec!["observation-receipt-1".to_string()];
7838        let note = MandateLearningNote::new(
7839            &mandate.id,
7840            mandate.version,
7841            &decision.id,
7842            "Explicit verification is more reliable than inferred completion",
7843            vec!["observation-receipt-1".to_string()],
7844        );
7845        store
7846            .record_mandate_decision_with_updates(
7847                &decision,
7848                None,
7849                Some(&MandateOperatingUpdates {
7850                    learning_note: Some(note.clone()),
7851                }),
7852                Some(&root_attempt.id),
7853            )
7854            .await
7855            .unwrap();
7856        assert_eq!(
7857            store
7858                .list_mandate_learning_notes(&mandate.id, 10)
7859                .await
7860                .unwrap(),
7861            vec![note]
7862        );
7863        assert_eq!(
7864            store
7865                .get_mandate_decision_for_run(&run.id)
7866                .await
7867                .unwrap()
7868                .unwrap()
7869                .activity_level,
7870            MandateActivityLevel::Urgent
7871        );
7872
7873        assert!(
7874            store
7875                .patch_task_from_attempt(
7876                    &root_attempt.id,
7877                    &root_attempt.lease_token,
7878                    &crate::traits::TaskAttemptPatch {
7879                        status: "completed".to_string(),
7880                        result: Some("receipt-backed STOP recorded".to_string()),
7881                        ..Default::default()
7882                    },
7883                )
7884                .await
7885                .unwrap()
7886        );
7887        let finalized = store
7888            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7889                mandate_id: mandate.id.clone(),
7890                expected_mandate_version: mandate.version,
7891                goal_run_id: run.id,
7892                finalized_at: chrono::Utc::now().to_rfc3339(),
7893            })
7894            .await
7895            .unwrap();
7896        assert!(matches!(
7897            finalized,
7898            MandateRunFinalizationResult::NonActionSatisfied {
7899                outcome: MandateDecisionOutcome::Stop,
7900                ..
7901            }
7902        ));
7903    }
7904
7905    #[tokio::test]
7906    async fn ask_and_stop_crashes_remain_reconcilable_until_proof_finalization() {
7907        for outcome in [MandateDecisionOutcome::Ask, MandateDecisionOutcome::Stop] {
7908            let (store, _database) = test_store().await;
7909            let (goal, mandate) = controller("owner-session", 1);
7910            let run = claim_and_start_run(&store, &goal, &mandate).await;
7911            let root_attempt = store
7912                .claim_task_with_lease(
7913                    run.root_task_id.as_deref().unwrap(),
7914                    "crashing-non-action-root",
7915                    Some("profile-task-lead"),
7916                    7_200,
7917                )
7918                .await
7919                .unwrap()
7920                .unwrap();
7921            let mut decision = MandateDecisionCycle::new(
7922                &mandate.id,
7923                &run.id,
7924                outcome,
7925                "Record the non-action decision before the simulated crash",
7926                mandate.version,
7927            );
7928            if outcome == MandateDecisionOutcome::Ask {
7929                decision.question = Some("May I broaden the exact target?".to_string());
7930            } else {
7931                decision.termination_kind = Some(MandateTerminationKind::SafetyTermination);
7932            }
7933            store
7934                .record_mandate_decision(&decision, None, Some(&root_attempt.id))
7935                .await
7936                .unwrap();
7937            assert_eq!(
7938                store
7939                    .get_mandate(&mandate.id)
7940                    .await
7941                    .unwrap()
7942                    .unwrap()
7943                    .status,
7944                MandateStatus::Active
7945            );
7946            sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
7947                .bind((chrono::Utc::now() - chrono::Duration::seconds(1)).to_rfc3339())
7948                .bind(&root_attempt.id)
7949                .execute(&store.pool)
7950                .await
7951                .unwrap();
7952
7953            assert!(
7954                store
7955                    .claim_due_mandates(1, "post-crash-reconciler", 300)
7956                    .await
7957                    .unwrap()
7958                    .is_empty()
7959            );
7960            assert_eq!(
7961                store
7962                    .get_mandate(&mandate.id)
7963                    .await
7964                    .unwrap()
7965                    .unwrap()
7966                    .status,
7967                MandateStatus::AwaitingInput
7968            );
7969            assert_eq!(
7970                store.get_goal(&goal.id).await.unwrap().unwrap().status,
7971                "paused"
7972            );
7973            assert_eq!(
7974                store.get_goal_runs(&goal.id).await.unwrap()[0].status,
7975                "cancelled"
7976            );
7977        }
7978    }
7979
7980    #[tokio::test]
7981    async fn mandate_schema_and_rows_survive_an_idempotent_reopen() {
7982        let (store, database) = test_store().await;
7983        let (goal, mandate) = controller("owner-session", 1);
7984        store
7985            .create_mandate_controller(&goal, &mandate)
7986            .await
7987            .unwrap();
7988        store.pool.close().await;
7989        drop(store);
7990
7991        let reopened = open_for_tests(database.path().to_str().unwrap()).await;
7992        let loaded = reopened.get_mandate(&mandate.id).await.unwrap().unwrap();
7993        assert_eq!(loaded.goal_id, goal.id);
7994        assert_eq!(loaded.version, mandate.version);
7995        assert_eq!(loaded.next_review_at, mandate.next_review_at);
7996    }
7997
7998    /// Seed one objective reading on a closed prior review run, as the
7999    /// history of an earlier cycle would leave it.
8000    async fn seed_prior_measurement(
8001        store: &SqliteWorkStore,
8002        mandate: &Mandate,
8003        current_run: &GoalRun,
8004        value_micros: i64,
8005        confidence_bps: i64,
8006        hours_ago: i64,
8007    ) {
8008        let run_id = uuid::Uuid::new_v4().to_string();
8009        sqlx::query(
8010            "INSERT INTO goal_runs (id, project_id, goal_id, trigger_type, status)
8011             SELECT ?, project_id, goal_id, 'mandate', 'completed' FROM goal_runs WHERE id = ?",
8012        )
8013        .bind(&run_id)
8014        .bind(&current_run.id)
8015        .execute(&store.pool)
8016        .await
8017        .unwrap();
8018        seed_measurement_on_run(
8019            store,
8020            mandate,
8021            &run_id,
8022            value_micros,
8023            confidence_bps,
8024            hours_ago,
8025        )
8026        .await;
8027    }
8028
8029    async fn seed_measurement_on_run(
8030        store: &SqliteWorkStore,
8031        mandate: &Mandate,
8032        run_id: &str,
8033        value_micros: i64,
8034        confidence_bps: i64,
8035        hours_ago: i64,
8036    ) {
8037        let observed_at = (chrono::Utc::now() - chrono::Duration::hours(hours_ago)).to_rfc3339();
8038        sqlx::query(
8039            "INSERT INTO mandate_objective_measurements
8040                (id, mandate_id, mandate_version, goal_run_id, value_micros, confidence_bps,
8041                 evidence_receipt_ids_json, attributed_intention_ids_json, observed_at, created_at)
8042             VALUES (?, ?, ?, ?, ?, ?, '[\"call_synthetic_seed\"]', '[]', ?, ?)",
8043        )
8044        .bind(uuid::Uuid::new_v4().to_string())
8045        .bind(&mandate.id)
8046        .bind(mandate.version)
8047        .bind(run_id)
8048        .bind(value_micros)
8049        .bind(confidence_bps)
8050        .bind(&observed_at)
8051        .bind(&observed_at)
8052        .execute(&store.pool)
8053        .await
8054        .unwrap();
8055    }
8056
8057    /// Measurements are read, not judged: flat (or unreadable) readings
8058    /// never refuse a WAIT; whether to change course is the reviewer's call.
8059    #[tokio::test]
8060    async fn flat_measurements_never_refuse_a_wait() {
8061        let (store, _database) = test_store().await;
8062        let (goal, mut mandate) = controller("owner-session", 1);
8063        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
8064        mandate.objective_control = Some(objective_control());
8065        let run = claim_and_start_run(&store, &goal, &mandate).await;
8066        for hours_ago in 2..=5 {
8067            seed_prior_measurement(&store, &mandate, &run, 10_000_000, 9_000, hours_ago).await;
8068        }
8069        seed_prior_measurement(&store, &mandate, &run, 0, 0, 1).await;
8070        seed_measurement_on_run(&store, &mandate, &run.id, 10_000_000, 9_000, 0).await;
8071
8072        let wait = MandateDecisionCycle::new(
8073            &mandate.id,
8074            &run.id,
8075            MandateDecisionOutcome::Wait,
8076            "no change observed",
8077            mandate.version,
8078        );
8079        store
8080            .record_mandate_decision(&wait, None, None)
8081            .await
8082            .expect("a flat metric must not force the mandate out of WAIT");
8083    }
8084
8085    #[tokio::test]
8086    async fn success_stop_requires_a_credible_current_measurement() {
8087        let (store, _database) = test_store().await;
8088        let (goal, mut mandate) = controller("owner-session", 1);
8089        // STOP on target is part of autopilot's measured control loop.
8090        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
8091        let control = objective_control();
8092        let target = control.target_micros;
8093        mandate.objective_control = Some(control);
8094        mandate.success_criteria = vec!["Synthetic interactions reach the target".to_string()];
8095        let run = claim_and_start_run(&store, &goal, &mandate).await;
8096        seed_measurement_on_run(&store, &mandate, &run.id, target, 0, 0).await;
8097
8098        let mut stop = MandateDecisionCycle::new(
8099            &mandate.id,
8100            &run.id,
8101            MandateDecisionOutcome::Stop,
8102            "target reached",
8103            mandate.version,
8104        );
8105        stop.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
8106        stop.termination_match = Some("Synthetic interactions reach the target".to_string());
8107        stop.evidence_receipt_ids = vec![];
8108        let error = store
8109            .record_mandate_decision(&stop, None, None)
8110            .await
8111            .unwrap_err();
8112        assert!(error.to_string().contains("credible"), "{error}");
8113    }
8114
8115    /// A bounded mandate's advisory control does not gate a success STOP on
8116    /// a target-reaching measurement; the owner criterion match still does.
8117    #[tokio::test]
8118    async fn bounded_success_stop_does_not_require_a_target_measurement() {
8119        let (store, _database) = test_store().await;
8120        let (goal, mut mandate) = controller("owner-session", 1);
8121        mandate.objective_control = Some(objective_control());
8122        mandate.success_criteria = vec!["One grounded note is posted".to_string()];
8123        let run = claim_and_start_run(&store, &goal, &mandate).await;
8124        let mut stop = MandateDecisionCycle::new(
8125            &mandate.id,
8126            &run.id,
8127            MandateDecisionOutcome::Stop,
8128            "the note is posted",
8129            mandate.version,
8130        );
8131        stop.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
8132        stop.termination_match = Some("One grounded note is posted".to_string());
8133        let root_task_id = run.root_task_id.clone().expect("review root task");
8134        let receipt = aidaemon_events::ToolReceiptV1::from_metadata(
8135            &crate::traits::ToolCallMetadata {
8136                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
8137                semantics: crate::traits::ToolCallSemantics::observation(),
8138                ..Default::default()
8139            },
8140            crate::traits::ToolOutcomeStatus::Succeeded,
8141            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
8142            None,
8143        );
8144        let result = aidaemon_events::ToolResultData {
8145            message_id: None,
8146            tool_call_id: "call_read_notes".to_string(),
8147            name: "http_request".to_string(),
8148            result: "one note posted".to_string(),
8149            success: true,
8150            duration_ms: 1,
8151            error: None,
8152            task_id: Some(root_task_id.clone()),
8153            annotations: vec![],
8154            turn_id: None,
8155            attachments: vec![],
8156            receipt: Some(receipt),
8157        };
8158        sqlx::query(
8159            "INSERT INTO events (session_id, event_type, data, created_at, task_id, tool_name)
8160             VALUES ('specialist:mandate', 'tool_result', ?, ?, ?, 'http_request')",
8161        )
8162        .bind(serde_json::to_string(&result).unwrap())
8163        .bind(chrono::Utc::now().to_rfc3339())
8164        .bind(&root_task_id)
8165        .execute(&store.pool)
8166        .await
8167        .unwrap();
8168        stop.evidence_receipt_ids = vec!["call_read_notes".to_string()];
8169        store
8170            .record_mandate_decision(&stop, None, None)
8171            .await
8172            .expect("a bounded mandate stops on its criterion");
8173    }
8174
8175    /// Drive one review to a finalized ASK exactly as the task lead would,
8176    /// leaving the mandate parked in `awaiting_input` with its question.
8177    async fn park_mandate_on_ask(
8178        store: &SqliteWorkStore,
8179        goal: &Goal,
8180        mandate: &Mandate,
8181        question: &str,
8182    ) -> GoalRun {
8183        let run = claim_and_start_run(store, goal, mandate).await;
8184        let root_attempt = store
8185            .claim_task_with_lease(
8186                run.root_task_id.as_deref().unwrap(),
8187                "ask-root",
8188                Some("profile-task-lead"),
8189                7_200,
8190            )
8191            .await
8192            .unwrap()
8193            .unwrap();
8194        let mut decision = MandateDecisionCycle::new(
8195            &mandate.id,
8196            &run.id,
8197            MandateDecisionOutcome::Ask,
8198            "owner judgment requested",
8199            mandate.version,
8200        );
8201        decision.question = Some(question.to_string());
8202        store
8203            .record_mandate_decision(&decision, None, Some(&root_attempt.id))
8204            .await
8205            .unwrap();
8206        assert!(
8207            store
8208                .patch_task_from_attempt(
8209                    &root_attempt.id,
8210                    &root_attempt.lease_token,
8211                    &crate::traits::TaskAttemptPatch {
8212                        status: "completed".to_string(),
8213                        result: Some("ASK recorded".to_string()),
8214                        ..Default::default()
8215                    },
8216                )
8217                .await
8218                .unwrap()
8219        );
8220        store
8221            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
8222                mandate_id: mandate.id.clone(),
8223                expected_mandate_version: mandate.version,
8224                goal_run_id: run.id.clone(),
8225                finalized_at: chrono::Utc::now().to_rfc3339(),
8226            })
8227            .await
8228            .unwrap();
8229        let parked = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8230        assert_eq!(parked.status, MandateStatus::AwaitingInput);
8231        run
8232    }
8233
8234    async fn make_review_due(store: &SqliteWorkStore, mandate: &Mandate) {
8235        sqlx::query("UPDATE mandates SET next_review_at = ? WHERE id = ?")
8236            .bind((chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339())
8237            .bind(&mandate.id)
8238            .execute(&store.pool)
8239            .await
8240            .unwrap();
8241    }
8242
8243    /// Drive one review to a finalized WAIT carrying `owner_alert`, as the
8244    /// task lead would. Returns the commit error when the decision is refused.
8245    async fn finalize_wait_with_alert(
8246        store: &SqliteWorkStore,
8247        goal: &Goal,
8248        mandate: &Mandate,
8249        alert: &str,
8250    ) -> anyhow::Result<()> {
8251        let run = claim_and_start_run(store, goal, mandate).await;
8252        let root_attempt = store
8253            .claim_task_with_lease(
8254                run.root_task_id.as_deref().unwrap(),
8255                "alert-root",
8256                Some("profile-task-lead"),
8257                7_200,
8258            )
8259            .await
8260            .unwrap()
8261            .unwrap();
8262        let mut decision = MandateDecisionCycle::new(
8263            &mandate.id,
8264            &run.id,
8265            MandateDecisionOutcome::Wait,
8266            "the watched page answered 503",
8267            mandate.version,
8268        );
8269        decision.owner_alert = Some(alert.to_string());
8270        store
8271            .record_mandate_decision(&decision, None, Some(&root_attempt.id))
8272            .await?;
8273        assert!(
8274            store
8275                .patch_task_from_attempt(
8276                    &root_attempt.id,
8277                    &root_attempt.lease_token,
8278                    &crate::traits::TaskAttemptPatch {
8279                        status: "completed".to_string(),
8280                        result: Some("WAIT recorded".to_string()),
8281                        ..Default::default()
8282                    },
8283                )
8284                .await
8285                .unwrap()
8286        );
8287        store
8288            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
8289                mandate_id: mandate.id.clone(),
8290                expected_mandate_version: mandate.version,
8291                goal_run_id: run.id.clone(),
8292                finalized_at: chrono::Utc::now().to_rfc3339(),
8293            })
8294            .await
8295            .unwrap();
8296        Ok(())
8297    }
8298
8299    #[tokio::test]
8300    async fn a_granted_owner_alert_reaches_the_owner_and_the_mandate_keeps_running() {
8301        let (store, _database) = test_store().await;
8302        let (goal, mut mandate) = controller("owner-session", 0);
8303        mandate.authority.owner_alerts = true;
8304        finalize_wait_with_alert(
8305            &store,
8306            &goal,
8307            &mandate,
8308            "The watched page is down (HTTP 503).",
8309        )
8310        .await
8311        .expect("a granted alert commits with its WAIT");
8312        let message = sqlx::query_scalar::<_, String>(
8313            "SELECT message FROM notification_queue
8314             WHERE goal_id = ? AND notification_type = 'mandate_alert'",
8315        )
8316        .bind(&goal.id)
8317        .fetch_one(&store.pool)
8318        .await
8319        .unwrap();
8320        assert!(
8321            message.contains("The watched page is down (HTTP 503)."),
8322            "{message}"
8323        );
8324        let after = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8325        assert_eq!(after.status, MandateStatus::Active);
8326    }
8327
8328    #[tokio::test]
8329    async fn an_owner_alert_without_the_grant_is_refused() {
8330        let (store, _database) = test_store().await;
8331        let (goal, mandate) = controller("owner-session", 0);
8332        assert!(!mandate.authority.owner_alerts);
8333        let refused =
8334            finalize_wait_with_alert(&store, &goal, &mandate, "The watched page is down.").await;
8335        assert!(refused.is_err(), "an alert needs the owner's grant");
8336        let alerts = sqlx::query_scalar::<_, i64>(
8337            "SELECT COUNT(*) FROM notification_queue WHERE notification_type = 'mandate_alert'",
8338        )
8339        .fetch_one(&store.pool)
8340        .await
8341        .unwrap();
8342        assert_eq!(alerts, 0);
8343    }
8344
8345    #[tokio::test]
8346    async fn ask_notice_carries_the_generated_question_for_the_owner() {
8347        let (store, _database) = test_store().await;
8348        let (goal, mandate) = controller("owner-session", 1);
8349        park_mandate_on_ask(&store, &goal, &mandate, "May I also read reply counts?").await;
8350        let message = sqlx::query_scalar::<_, String>(
8351            "SELECT message FROM notification_queue
8352             WHERE goal_id = ? AND notification_type = 'mandate_ask'",
8353        )
8354        .bind(&goal.id)
8355        .fetch_one(&store.pool)
8356        .await
8357        .unwrap();
8358        assert!(
8359            message.contains("May I also read reply counts?"),
8360            "{message}"
8361        );
8362    }
8363
8364    #[tokio::test]
8365    async fn unanswered_ask_resumes_within_existing_authority_at_its_reconsider_time() {
8366        let (store, _database) = test_store().await;
8367        let (goal, mandate) = controller("owner-session", 1);
8368        park_mandate_on_ask(&store, &goal, &mandate, "May I also read reply counts?").await;
8369
8370        // Not yet due: the owner still has the full reconsider window.
8371        assert!(
8372            store
8373                .claim_due_mandates(10, "synthetic-heartbeat", 300)
8374                .await
8375                .unwrap()
8376                .is_empty()
8377        );
8378        assert_eq!(
8379            store
8380                .get_mandate(&mandate.id)
8381                .await
8382                .unwrap()
8383                .unwrap()
8384                .status,
8385            MandateStatus::AwaitingInput
8386        );
8387
8388        make_review_due(&store, &mandate).await;
8389        let claimed = store
8390            .claim_due_mandates(10, "synthetic-heartbeat", 300)
8391            .await
8392            .unwrap();
8393        assert_eq!(claimed.len(), 1, "an unanswered ASK must not park forever");
8394        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8395        assert_eq!(resumed.status, MandateStatus::Active);
8396        assert!(resumed.suspension.is_none());
8397        assert_eq!(
8398            resumed.authority, mandate.authority,
8399            "resuming without an answer must not change authority"
8400        );
8401        assert_eq!(
8402            store.get_goal(&goal.id).await.unwrap().unwrap().status,
8403            "active"
8404        );
8405        let notice = sqlx::query_scalar::<_, String>(
8406            "SELECT message FROM notification_queue
8407             WHERE goal_id = ? AND notification_type = 'mandate_ask_timeout'",
8408        )
8409        .bind(&goal.id)
8410        .fetch_one(&store.pool)
8411        .await
8412        .unwrap();
8413        assert!(notice.contains("May I also read reply counts?"), "{notice}");
8414        // Named by the objective the owner confirmed, in plain language.
8415        assert!(notice.starts_with("Your automation \""), "{notice}");
8416        assert!(notice.contains("No reply is needed"), "{notice}");
8417        assert!(!notice.contains("within its current authority"), "{notice}");
8418    }
8419
8420    #[tokio::test]
8421    async fn safety_suspensions_never_auto_resume() {
8422        let (store, _database) = test_store().await;
8423        let (goal, mandate) = controller("owner-session", 1);
8424        store
8425            .create_mandate_controller(&goal, &mandate)
8426            .await
8427            .unwrap();
8428        let suspension = MandateSuspension::new(
8429            MandateSuspensionKind::ReconciliationRequired,
8430            Some("synthetic".to_string()),
8431        );
8432        sqlx::query(
8433            "UPDATE mandates SET status = 'awaiting_input', suspension_json = ?,
8434                 confirmed_at = COALESCE(confirmed_at, ?)
8435             WHERE id = ?",
8436        )
8437        .bind(serde_json::to_string(&suspension).unwrap())
8438        .bind(chrono::Utc::now().to_rfc3339())
8439        .bind(&mandate.id)
8440        .execute(&store.pool)
8441        .await
8442        .unwrap();
8443        make_review_due(&store, &mandate).await;
8444        assert!(
8445            store
8446                .claim_due_mandates(10, "synthetic-heartbeat", 300)
8447                .await
8448                .unwrap()
8449                .is_empty()
8450        );
8451        assert_eq!(
8452            store
8453                .get_mandate(&mandate.id)
8454                .await
8455                .unwrap()
8456                .unwrap()
8457                .status,
8458            MandateStatus::AwaitingInput
8459        );
8460    }
8461
8462    async fn start_existing_claimed_run(
8463        store: &SqliteWorkStore,
8464        goal: &Goal,
8465        mandate: &Mandate,
8466    ) -> GoalRun {
8467        let claimed = store
8468            .claim_due_mandates(1, "test-heartbeat-next", 300)
8469            .await
8470            .unwrap();
8471        assert_eq!(claimed.len(), 1);
8472        assert_eq!(claimed[0].id, mandate.id);
8473        let root_task_id = uuid::Uuid::new_v4().to_string();
8474        let run = store
8475            .start_goal_run(&goal.id, "mandate", None, Some(&root_task_id))
8476            .await
8477            .unwrap();
8478        store
8479            .create_task(&review_root(goal, &run.id, &root_task_id))
8480            .await
8481            .unwrap();
8482        sqlx::query("UPDATE goal_runs SET status = 'running' WHERE id = ?")
8483            .bind(&run.id)
8484            .execute(&store.pool)
8485            .await
8486            .unwrap();
8487        run
8488    }
8489
8490    /// Settle a dispatched attempt with an explicit completion time, as the
8491    /// canonical tool-result append does at its own event time. Quota and
8492    /// cooldown tests need the time chosen; the transition is the same.
8493    async fn finish_attempt(
8494        store: &SqliteWorkStore,
8495        reservation: &MandateMutationReservation,
8496        status: MandateMutationAttemptStatus,
8497        http_status: Option<u16>,
8498        completed_at: chrono::DateTime<chrono::Utc>,
8499    ) -> bool {
8500        sqlx::query(
8501            "UPDATE mandate_mutation_attempts
8502             SET status = ?, outcome_evidence = ?, http_status = ?, completed_at = ?
8503             WHERE mandate_id = ? AND mandate_version = ?
8504               AND decision_cycle_id = ? AND reserved_action_attempt = ?
8505               AND action_digest = ? AND goal_run_id = ?
8506               AND task_id = ? AND task_attempt_id = ? AND tool_call_id = ?
8507               AND status = 'reserved' AND dispatch_claimed_at IS NOT NULL",
8508        )
8509        .bind(match status {
8510            MandateMutationAttemptStatus::Succeeded => "succeeded",
8511            MandateMutationAttemptStatus::Failed => "failed",
8512            MandateMutationAttemptStatus::Ambiguous => "ambiguous",
8513            other => panic!("not a post-dispatch outcome: {other:?}"),
8514        })
8515        .bind("structured_metadata")
8516        .bind(http_status.map(i64::from))
8517        .bind(completed_at.to_rfc3339())
8518        .bind(&reservation.grant.mandate_id)
8519        .bind(reservation.grant.mandate_version)
8520        .bind(&reservation.grant.decision_cycle_id)
8521        .bind(reservation.grant.reserved_action_attempt)
8522        .bind(&reservation.grant.action_digest)
8523        .bind(&reservation.goal_run_id)
8524        .bind(&reservation.task_id)
8525        .bind(&reservation.task_attempt_id)
8526        .bind(&reservation.tool_call_id)
8527        .execute(&store.pool)
8528        .await
8529        .unwrap()
8530        .rows_affected()
8531            == 1
8532    }
8533
8534    #[tokio::test]
8535    async fn cooldown_failure_and_rolling_expiry_are_cross_cycle_safety_state() {
8536        let (store, _database) = test_store().await;
8537        let (goal, mut mandate) = controller("owner-session", 2);
8538        mandate.authority.max_mutating_actions_per_rolling_24h = 2;
8539        let run = claim_and_start_run(&store, &goal, &mandate).await;
8540        let act = MandateDecisionCycle::new(
8541            &mandate.id,
8542            &run.id,
8543            MandateDecisionOutcome::Act,
8544            "Two spaced actions fit the envelope",
8545            mandate.version,
8546        );
8547        let intention = Intention::new(
8548            &mandate.id,
8549            &act.id,
8550            &run.id,
8551            "Perform two governed actions",
8552            "It tests rolling quota semantics",
8553        );
8554        store
8555            .record_mandate_decision(&act, Some(&intention), None)
8556            .await
8557            .unwrap();
8558        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
8559        let base = chrono::Utc::now();
8560        let first = reservation(&mandate, &act, &run, &fence, 1, 201, base);
8561        assert!(
8562            store
8563                .reserve_mandate_action_attempt(&first)
8564                .await
8565                .unwrap()
8566                .is_some()
8567        );
8568        assert!(
8569            store
8570                .claim_mandate_mutation_dispatch(&dispatch_claim(
8571                    &first,
8572                    base + chrono::Duration::milliseconds(1),
8573                ))
8574                .await
8575                .unwrap()
8576        );
8577        assert!(
8578            !store
8579                .claim_mandate_mutation_dispatch(&dispatch_claim(
8580                    &first,
8581                    base + chrono::Duration::milliseconds(2),
8582                ))
8583                .await
8584                .unwrap()
8585        );
8586        assert!(
8587            finish_attempt(
8588                &store,
8589                &first,
8590                MandateMutationAttemptStatus::Failed,
8591                Some(400),
8592                base + chrono::Duration::seconds(1)
8593            )
8594            .await
8595        );
8596        let too_soon = reservation(
8597            &mandate,
8598            &act,
8599            &run,
8600            &fence,
8601            2,
8602            202,
8603            base + chrono::Duration::seconds(899),
8604        );
8605        assert!(
8606            store
8607                .reserve_mandate_action_attempt(&too_soon)
8608                .await
8609                .unwrap()
8610                .is_none()
8611        );
8612        let cooldown = store
8613            .get_mandate_mutation_quota_state(
8614                &mandate.id,
8615                &(base + chrono::Duration::seconds(899)).to_rfc3339(),
8616            )
8617            .await
8618            .unwrap()
8619            .unwrap();
8620        assert_eq!(
8621            cooldown.block_reason,
8622            Some(MandateMutationQuotaBlockReason::Cooldown)
8623        );
8624        assert_eq!(cooldown.reserved_in_rolling_24h, 1);
8625
8626        let second = reservation(
8627            &mandate,
8628            &act,
8629            &run,
8630            &fence,
8631            2,
8632            203,
8633            base + chrono::Duration::seconds(900),
8634        );
8635        assert!(
8636            store
8637                .reserve_mandate_action_attempt(&second)
8638                .await
8639                .unwrap()
8640                .is_some()
8641        );
8642        let full = store
8643            .get_mandate_mutation_quota_state(
8644                &mandate.id,
8645                &(base + chrono::Duration::seconds(901)).to_rfc3339(),
8646            )
8647            .await
8648            .unwrap()
8649            .unwrap();
8650        assert_eq!(
8651            full.block_reason,
8652            Some(MandateMutationQuotaBlockReason::Rolling24hExhausted)
8653        );
8654        assert_eq!(full.remaining_in_rolling_24h, 0);
8655
8656        let observation = crate::traits::ToolCallSemantics::observation().with_target_hint(
8657            crate::traits::ToolTargetHintKind::Url,
8658            "https://api.x.com/2/tweets",
8659        );
8660        assert!(
8661            crate::authority::authorize_mandate_observation(
8662                &mandate,
8663                "http_request",
8664                r#"{"method":"GET","url":"https://api.x.com/2/tweets"}"#,
8665                &observation,
8666                &(base + chrono::Duration::seconds(901)),
8667            )
8668            .is_ok()
8669        );
8670
8671        let expired = store
8672            .get_mandate_mutation_quota_state(
8673                &mandate.id,
8674                &(base + chrono::Duration::hours(24) + chrono::Duration::seconds(1)).to_rfc3339(),
8675            )
8676            .await
8677            .unwrap()
8678            .unwrap();
8679        assert_eq!(expired.reserved_in_rolling_24h, 1);
8680        assert_eq!(expired.remaining_in_rolling_24h, 1);
8681        assert!(expired.available_now);
8682    }
8683
8684    #[tokio::test]
8685    async fn rolling_quota_survives_policy_versions_pause_resume_and_new_cycles() {
8686        let (store, _database) = test_store().await;
8687        let (goal, mut mandate) = controller("owner-session", 1);
8688        mandate.authority.max_mutating_actions_per_rolling_24h = 1;
8689        let first_run = claim_and_start_run(&store, &goal, &mandate).await;
8690        let first_act = MandateDecisionCycle::new(
8691            &mandate.id,
8692            &first_run.id,
8693            MandateDecisionOutcome::Act,
8694            "Use the sole daily slot",
8695            mandate.version,
8696        );
8697        let first_intention = Intention::new(
8698            &mandate.id,
8699            &first_act.id,
8700            &first_run.id,
8701            "Use one daily action",
8702            "It tests cross-cycle accounting",
8703        );
8704        store
8705            .record_mandate_decision(&first_act, Some(&first_intention), None)
8706            .await
8707            .unwrap();
8708        let first_fence = claim_mutation_fence(&store, &goal, &mandate, &first_run).await;
8709        let base = chrono::Utc::now();
8710        let first = reservation(&mandate, &first_act, &first_run, &first_fence, 1, 301, base);
8711        assert!(
8712            store
8713                .reserve_mandate_action_attempt(&first)
8714                .await
8715                .unwrap()
8716                .is_some()
8717        );
8718        assert!(
8719            store
8720                .claim_mandate_mutation_dispatch(&dispatch_claim(
8721                    &first,
8722                    base + chrono::Duration::milliseconds(1),
8723                ))
8724                .await
8725                .unwrap()
8726        );
8727        assert!(
8728            finish_attempt(
8729                &store,
8730                &first,
8731                MandateMutationAttemptStatus::Failed,
8732                Some(400),
8733                base + chrono::Duration::seconds(1)
8734            )
8735            .await
8736        );
8737        assert!(
8738            store
8739                .transition_mandate_status(
8740                    &mandate.id,
8741                    MandateStatus::Active,
8742                    MandateStatus::Paused,
8743                )
8744                .await
8745                .unwrap()
8746        );
8747        assert!(
8748            store
8749                .transition_mandate_status(
8750                    &mandate.id,
8751                    MandateStatus::Paused,
8752                    MandateStatus::Active,
8753                )
8754                .await
8755                .unwrap()
8756        );
8757        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8758        assert!(current.version > mandate.version);
8759        let second_run = start_existing_claimed_run(&store, &goal, &current).await;
8760        let second_act = MandateDecisionCycle::new(
8761            &current.id,
8762            &second_run.id,
8763            MandateDecisionOutcome::Act,
8764            "A new cycle still sees the old reservation",
8765            current.version,
8766        );
8767        let second_intention = Intention::new(
8768            &current.id,
8769            &second_act.id,
8770            &second_run.id,
8771            "Try another action",
8772            "The daily ledger must reject it",
8773        );
8774        // The new cycle's ACT is refused when it is committed: the store
8775        // reads the same rolling ledger across policy versions.
8776        let refused = store
8777            .record_mandate_decision(&second_act, Some(&second_intention), None)
8778            .await
8779            .expect_err("ACT must be refused while the rolling quota is used up");
8780        assert!(
8781            refused
8782                .to_string()
8783                .starts_with("mandate_mutation_quota_unavailable: choose WAIT"),
8784            "{refused}"
8785        );
8786        let quota = store
8787            .get_mandate_mutation_quota_state(
8788                &current.id,
8789                &(base + chrono::Duration::seconds(901)).to_rfc3339(),
8790            )
8791            .await
8792            .unwrap()
8793            .unwrap();
8794        assert_eq!(quota.reserved_in_rolling_24h, 1);
8795        assert_eq!(
8796            quota.block_reason,
8797            Some(MandateMutationQuotaBlockReason::Rolling24hExhausted)
8798        );
8799    }
8800
8801    #[tokio::test]
8802    async fn canonical_tool_result_atomically_projects_the_mandate_ledger() {
8803        let (store, _database) = test_store().await;
8804        let (goal, mandate) = controller("owner-session", 1);
8805        let run = claim_and_start_run(&store, &goal, &mandate).await;
8806        let decision = MandateDecisionCycle::new(
8807            &mandate.id,
8808            &run.id,
8809            MandateDecisionOutcome::Act,
8810            "Exercise atomic receipt projection",
8811            mandate.version,
8812        );
8813        let intention = Intention::new(
8814            &mandate.id,
8815            &decision.id,
8816            &run.id,
8817            "Issue one governed request",
8818            "The event and ledger must commit together",
8819        );
8820        store
8821            .record_mandate_decision(&decision, Some(&intention), None)
8822            .await
8823            .unwrap();
8824        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
8825        let now = chrono::Utc::now();
8826        let reservation = reservation(&mandate, &decision, &run, &fence, 1, 777, now);
8827        store
8828            .reserve_mandate_action_attempt(&reservation)
8829            .await
8830            .unwrap()
8831            .expect("reserved mutation");
8832        assert!(
8833            store
8834                .claim_mandate_mutation_dispatch(&dispatch_claim(
8835                    &reservation,
8836                    now + chrono::Duration::milliseconds(1),
8837                ))
8838                .await
8839                .unwrap()
8840        );
8841
8842        let semantics = crate::traits::ToolCallSemantics::mutation_with(
8843            crate::traits::ToolMutationEffects::EXTERNAL_DELIVERY,
8844        );
8845        let mut receipt = aidaemon_events::ToolReceiptV1::from_metadata(
8846            &crate::traits::ToolCallMetadata {
8847                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
8848                http_status: Some(201),
8849                semantics,
8850                ..Default::default()
8851            },
8852            crate::traits::ToolOutcomeStatus::Succeeded,
8853            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
8854            Some("mandate-atomic-receipt".to_string()),
8855        );
8856        receipt.mandate_authority = Some(reservation.grant.clone());
8857        let result = aidaemon_events::ToolResultData {
8858            message_id: None,
8859            tool_call_id: reservation.tool_call_id.clone(),
8860            name: "http_request".to_string(),
8861            result: "created".to_string(),
8862            success: true,
8863            duration_ms: 1,
8864            error: None,
8865            task_id: Some(fence.worker_task.id.clone()),
8866            annotations: vec![],
8867            turn_id: None,
8868            attachments: vec![],
8869            receipt: Some(receipt),
8870        };
8871        let event_store = aidaemon_events::EventStore::on_paths(
8872            store.pool(),
8873            aidaemon_tools::LexicalPaths::daemon_host(),
8874            Arc::new(aidaemon_events::NoEventHost),
8875        )
8876        .await
8877        .unwrap();
8878        event_store
8879            .append(aidaemon_events::Event::new(
8880                "specialist:mandate",
8881                aidaemon_events::EventType::ToolResult,
8882                serde_json::to_value(result).unwrap(),
8883            ))
8884            .await
8885            .unwrap();
8886
8887        let attempts = store
8888            .list_mandate_mutation_attempts_for_run(&run.id)
8889            .await
8890            .unwrap();
8891        assert_eq!(attempts.len(), 1);
8892        assert_eq!(attempts[0].status, MandateMutationAttemptStatus::Succeeded);
8893    }
8894
8895    #[tokio::test]
8896    async fn strict_receipts_finalize_act_and_mixed_failure_fails_closed() {
8897        for include_failure in [false, true] {
8898            let (store, _database) = test_store().await;
8899            let cycle_cap = if include_failure { 2 } else { 1 };
8900            let (goal, mut mandate) = controller("owner-session", cycle_cap);
8901            mandate.authority.max_mutating_actions_per_rolling_24h = cycle_cap;
8902            let run = claim_and_start_run(&store, &goal, &mandate).await;
8903            let act = MandateDecisionCycle::new(
8904                &mandate.id,
8905                &run.id,
8906                MandateDecisionOutcome::Act,
8907                "Execute and prove the governed action",
8908                mandate.version,
8909            );
8910            let intention = Intention::new(
8911                &mandate.id,
8912                &act.id,
8913                &run.id,
8914                "Execute governed mutation",
8915                "Strict receipts determine completion",
8916            );
8917            store
8918                .record_mandate_decision(&act, Some(&intention), None)
8919                .await
8920                .unwrap();
8921            let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
8922            let base = chrono::Utc::now();
8923            let first = reservation(&mandate, &act, &run, &fence, 1, 401, base);
8924            assert!(
8925                store
8926                    .reserve_mandate_action_attempt(&first)
8927                    .await
8928                    .unwrap()
8929                    .is_some()
8930            );
8931            assert!(
8932                store
8933                    .claim_mandate_mutation_dispatch(&dispatch_claim(
8934                        &first,
8935                        base + chrono::Duration::milliseconds(1),
8936                    ))
8937                    .await
8938                    .unwrap()
8939            );
8940            assert!(
8941                finish_attempt(
8942                    &store,
8943                    &first,
8944                    MandateMutationAttemptStatus::Succeeded,
8945                    Some(200),
8946                    base + chrono::Duration::seconds(1)
8947                )
8948                .await
8949            );
8950            if include_failure {
8951                let second = reservation(
8952                    &mandate,
8953                    &act,
8954                    &run,
8955                    &fence,
8956                    2,
8957                    402,
8958                    base + chrono::Duration::seconds(900),
8959                );
8960                assert!(
8961                    store
8962                        .reserve_mandate_action_attempt(&second)
8963                        .await
8964                        .unwrap()
8965                        .is_some()
8966                );
8967                assert!(
8968                    store
8969                        .claim_mandate_mutation_dispatch(&dispatch_claim(
8970                            &second,
8971                            base + chrono::Duration::milliseconds(900_001),
8972                        ))
8973                        .await
8974                        .unwrap()
8975                );
8976                assert!(
8977                    finish_attempt(
8978                        &store,
8979                        &second,
8980                        MandateMutationAttemptStatus::Failed,
8981                        Some(400),
8982                        base + chrono::Duration::seconds(901)
8983                    )
8984                    .await
8985                );
8986            }
8987            complete_mutation_fence(&store, &fence).await;
8988            let result = store
8989                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
8990                    mandate_id: mandate.id.clone(),
8991                    expected_mandate_version: mandate.version,
8992                    goal_run_id: run.id.clone(),
8993                    finalized_at: (base + chrono::Duration::seconds(1_000)).to_rfc3339(),
8994                })
8995                .await
8996                .unwrap();
8997            if include_failure {
8998                assert!(matches!(
8999                    result,
9000                    MandateRunFinalizationResult::ReconciliationRequired {
9001                        reason: MandateReconciliationReason::MutationOutcomeFailed,
9002                        ..
9003                    }
9004                ));
9005                assert_eq!(
9006                    store.get_goal_runs(&goal.id).await.unwrap()[0].status,
9007                    "failed"
9008                );
9009                assert!(
9010                    store
9011                        .get_current_goal_run(&goal.id)
9012                        .await
9013                        .unwrap()
9014                        .is_none()
9015                );
9016                assert_eq!(
9017                    store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
9018                    IntentionStatus::Suspended
9019                );
9020                assert_eq!(
9021                    store
9022                        .get_mandate(&mandate.id)
9023                        .await
9024                        .unwrap()
9025                        .unwrap()
9026                        .status,
9027                    MandateStatus::AwaitingInput
9028                );
9029                assert_eq!(
9030                    store.get_goal(&goal.id).await.unwrap().unwrap().status,
9031                    "paused"
9032                );
9033            } else {
9034                assert!(matches!(
9035                    result,
9036                    MandateRunFinalizationResult::ActSatisfied { .. }
9037                ));
9038                assert_eq!(
9039                    store.get_goal_runs(&goal.id).await.unwrap()[0].status,
9040                    "completed"
9041                );
9042                assert_eq!(
9043                    store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
9044                    IntentionStatus::Satisfied
9045                );
9046            }
9047        }
9048    }
9049}