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        let root_dependencies = root_task.dependency_ids().map_err(anyhow::Error::msg)?;
2310        super::goals::replace_task_dependencies(&mut tx, &root_task.id, &root_dependencies).await?;
2311
2312        tx.commit().await?;
2313        Ok(run)
2314    }
2315
2316    async fn keep_mandate_controller_active(
2317        &self,
2318        mandate_id: &str,
2319        expected_version: i64,
2320    ) -> anyhow::Result<bool> {
2321        anyhow::ensure!(expected_version > 0, "mandate version must be positive");
2322        let now = chrono::Utc::now().to_rfc3339();
2323        let result = sqlx::query(
2324            "UPDATE goals
2325             SET status = 'active', completed_at = NULL, dispatch_failures = 0, updated_at = ?
2326             WHERE id = (
2327                 SELECT goal_id FROM mandates
2328                 WHERE id = ? AND status = 'active' AND confirmed_at IS NOT NULL
2329                   AND version = ?
2330             )
2331               AND domain = 'orchestration' AND goal_type = 'continuous'",
2332        )
2333        .bind(&now)
2334        .bind(mandate_id)
2335        .bind(expected_version)
2336        .execute(self.work_pool())
2337        .await?;
2338        Ok(result.rows_affected() == 1)
2339    }
2340
2341    async fn claim_due_mandates(
2342        &self,
2343        limit: i64,
2344        lease_owner: &str,
2345        lease_secs: i64,
2346    ) -> anyhow::Result<Vec<Mandate>> {
2347        if limit <= 0 {
2348            return Ok(Vec::new());
2349        }
2350        anyhow::ensure!(!lease_owner.trim().is_empty(), "lease owner is required");
2351        anyhow::ensure!(
2352            (1..=86_400).contains(&lease_secs),
2353            "review lease duration must be between 1 second and 24 hours"
2354        );
2355        let now = chrono::Utc::now();
2356        let now_string = now.to_rfc3339();
2357        let lease_expires_at = (now + chrono::Duration::seconds(lease_secs)).to_rfc3339();
2358        let lease_token = format!("{}:{}", lease_owner.trim(), uuid::Uuid::new_v4());
2359        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2360
2361        // Recover the only crash state produced by the pre-atomic dispatcher:
2362        // an open mandate run whose root task was never inserted. No work can
2363        // have executed in such a run, so close it and make the mandate due in
2364        // the same transaction before selecting claims.
2365        sqlx::query(
2366            "UPDATE mandates
2367             SET next_review_at = ?, review_lease_token = NULL,
2368                 review_lease_expires_at = NULL, updated_at = ?
2369             WHERE status = 'active' AND confirmed_at IS NOT NULL
2370               AND EXISTS (
2371                   SELECT 1 FROM goal_runs gr
2372                   WHERE gr.goal_id = mandates.goal_id
2373                     AND gr.trigger_type = 'mandate'
2374                     AND gr.status IN ('pending', 'running', 'blocked')
2375                     AND NOT EXISTS (
2376                         SELECT 1 FROM tasks t WHERE t.goal_run_id = gr.id
2377                     )
2378               )",
2379        )
2380        .bind(&now_string)
2381        .bind(&now_string)
2382        .execute(&mut *tx)
2383        .await?;
2384        sqlx::query(
2385            "UPDATE goal_runs
2386             SET status = 'failed',
2387                 outcome_summary = 'Recovered an interrupted mandate dispatch before its root task was created.',
2388                 completed_at = COALESCE(completed_at, ?), updated_at = ?
2389             WHERE trigger_type = 'mandate'
2390               AND status IN ('pending', 'running', 'blocked')
2391               AND NOT EXISTS (
2392                   SELECT 1 FROM tasks t WHERE t.goal_run_id = goal_runs.id
2393               )",
2394        )
2395        .bind(&now_string)
2396        .bind(&now_string)
2397        .execute(&mut *tx)
2398        .await?;
2399
2400        // A root whose execution lease vanished may have performed an
2401        // externally visible effect before crashing. Never auto-retry that
2402        // ambiguous cycle: atomically pause it for owner reconciliation.
2403        reconcile_orphaned_mandate_runs(&mut tx, &now_string).await?;
2404
2405        // An agent question is a request for owner judgment, not a safety
2406        // fence. Once its bounded reconsider time passes without an answer,
2407        // the mandate continues within its unchanged authority instead of
2408        // parking forever; the question stays visible in decision history.
2409        resume_unanswered_agent_questions(&mut tx, &now_string).await?;
2410
2411        // Expiry is a hard authority boundary, not merely a query filter. Keep
2412        // the visible lifecycle coherent so an expired mandate cannot remain
2413        // labelled active indefinitely with an active backing controller. It
2414        // revokes attempts/runs/intentions in the same transaction, exactly as
2415        // an explicit lifecycle transition does.
2416        let expired_goal_ids = sqlx::query_scalar::<_, String>(
2417            "SELECT goal_id FROM mandates
2418             WHERE status = 'active' AND expires_at IS NOT NULL
2419               AND julianday(expires_at) <= julianday(?)",
2420        )
2421        .bind(&now_string)
2422        .fetch_all(&mut *tx)
2423        .await?;
2424        for goal_id in &expired_goal_ids {
2425            invalidate_open_mandate_runs(&mut tx, goal_id, &now_string).await?;
2426        }
2427        sqlx::query(
2428            "UPDATE goals
2429             SET status = 'completed', completed_at = COALESCE(completed_at, ?), updated_at = ?
2430             WHERE id IN (
2431                 SELECT goal_id FROM mandates
2432                 WHERE status = 'active' AND expires_at IS NOT NULL
2433                   AND julianday(expires_at) <= julianday(?)
2434             )",
2435        )
2436        .bind(&now_string)
2437        .bind(&now_string)
2438        .bind(&now_string)
2439        .execute(&mut *tx)
2440        .await?;
2441        sqlx::query(
2442            "UPDATE mandates
2443             SET status = 'completed', review_lease_token = NULL,
2444                 review_lease_expires_at = NULL, version = version + 1, updated_at = ?
2445             WHERE status = 'active' AND expires_at IS NOT NULL
2446               AND julianday(expires_at) <= julianday(?)",
2447        )
2448        .bind(&now_string)
2449        .bind(&now_string)
2450        .execute(&mut *tx)
2451        .await?;
2452        let query = format!(
2453            "UPDATE mandates
2454             SET review_lease_token = ?, review_lease_expires_at = ?, updated_at = ?
2455             WHERE id IN (
2456                 SELECT m.id
2457                 FROM mandates m
2458                 JOIN goals g ON g.id = m.goal_id
2459                 WHERE m.status = 'active'
2460                   AND m.confirmed_at IS NOT NULL
2461                   AND g.domain = 'orchestration'
2462                   AND g.goal_type = 'continuous'
2463                   AND g.status = 'active'
2464                   AND julianday(m.next_review_at) <= julianday(?)
2465                   AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2466                   AND (
2467                       m.review_lease_token IS NULL
2468                       OR m.review_lease_expires_at IS NULL
2469                       OR julianday(m.review_lease_expires_at) <= julianday(?)
2470                   )
2471                   AND NOT EXISTS (
2472                       SELECT 1 FROM goal_runs gr
2473                       WHERE gr.goal_id = m.goal_id
2474                         AND gr.status IN ('pending', 'running', 'blocked')
2475                   )
2476                 ORDER BY julianday(m.next_review_at), m.id
2477                 LIMIT ?
2478             )
2479               AND status = 'active'
2480               AND confirmed_at IS NOT NULL
2481               AND (
2482                   review_lease_token IS NULL
2483                   OR review_lease_expires_at IS NULL
2484                   OR julianday(review_lease_expires_at) <= julianday(?)
2485               )
2486             RETURNING {MANDATE_COLUMNS}"
2487        );
2488        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
2489            .bind(&lease_token)
2490            .bind(&lease_expires_at)
2491            .bind(&now_string)
2492            .bind(&now_string)
2493            .bind(&now_string)
2494            .bind(&now_string)
2495            .bind(limit.min(100))
2496            .bind(&now_string)
2497            .fetch_all(&mut *tx)
2498            .await?;
2499        tx.commit().await?;
2500        let mut mandates = rows
2501            .iter()
2502            .map(mandate_from_row)
2503            .collect::<anyhow::Result<Vec<_>>>()?;
2504        mandates.sort_by(|left, right| {
2505            left.next_review_at
2506                .cmp(&right.next_review_at)
2507                .then_with(|| left.id.cmp(&right.id))
2508        });
2509        Ok(mandates)
2510    }
2511
2512    async fn release_mandate_review_lease(
2513        &self,
2514        mandate_id: &str,
2515        lease_token: &str,
2516        retry_at: &str,
2517    ) -> anyhow::Result<bool> {
2518        anyhow::ensure!(
2519            !lease_token.trim().is_empty(),
2520            "review lease token is required"
2521        );
2522        validate_timestamp("retry_at", retry_at)?;
2523        let result = sqlx::query(
2524            "UPDATE mandates
2525             SET next_review_at = ?, review_lease_token = NULL,
2526                 review_lease_expires_at = NULL, updated_at = ?
2527             WHERE id = ? AND review_lease_token = ?",
2528        )
2529        .bind(retry_at)
2530        .bind(chrono::Utc::now().to_rfc3339())
2531        .bind(mandate_id)
2532        .bind(lease_token)
2533        .execute(self.work_pool())
2534        .await?;
2535        Ok(result.rows_affected() == 1)
2536    }
2537
2538    async fn create_mandate_task_from_attempt(
2539        &self,
2540        task: &Task,
2541        mandate_id: &str,
2542        mandate_version: i64,
2543        goal_run_id: &str,
2544        root_task_attempt_id: &str,
2545        max_non_root_tasks: i64,
2546    ) -> anyhow::Result<bool> {
2547        anyhow::ensure!(mandate_version > 0, "mandate version must be positive");
2548        anyhow::ensure!(
2549            (1..=64).contains(&max_non_root_tasks),
2550            "mandate task cap must be between 1 and 64"
2551        );
2552        anyhow::ensure!(task.status == "pending", "mandate tasks must start pending");
2553        anyhow::ensure!(
2554            !task.idempotent && task.retry_count == 0 && task.max_retries == 0,
2555            "mandate tasks cannot be replayable"
2556        );
2557        anyhow::ensure!(
2558            !task.id.trim().is_empty()
2559                && !task.goal_id.trim().is_empty()
2560                && !task.description.trim().is_empty()
2561                && task.description.trim() == task.description
2562                && task.description.chars().count() <= 8_000,
2563            "mandate task identity and description must be canonical"
2564        );
2565        anyhow::ensure!(
2566            task.agent_id.is_none()
2567                && task.result.is_none()
2568                && task.error.is_none()
2569                && task.blocker.is_none()
2570                && task.started_at.is_none()
2571                && task.completed_at.is_none(),
2572            "new mandate tasks cannot carry execution state"
2573        );
2574
2575        let now = chrono::Utc::now().to_rfc3339();
2576        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2577        // First write: acquire the writer lock and prove the complete authority
2578        // chain in one CAS. A pause, policy revision, run replacement, or root
2579        // attempt replacement either linearizes before this statement (and
2580        // rejects it) or after this transaction commits.
2581        let fenced = sqlx::query(
2582            "UPDATE task_attempts
2583             SET last_heartbeat_at = datetime('now')
2584             WHERE id = ? AND goal_run_id = ?
2585               AND status IN ('claimed', 'running')
2586               AND datetime(lease_expires_at) > datetime('now')
2587               AND EXISTS (
2588                   SELECT 1
2589                   FROM tasks root
2590                   JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2591                   JOIN mandates m ON m.goal_id = gr.goal_id
2592                   JOIN goals g ON g.id = m.goal_id
2593                   JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
2594                   JOIN intentions i ON i.decision_cycle_id = dc.id
2595                   WHERE root.id = task_attempts.task_id
2596                     AND root.current_attempt_id = task_attempts.id
2597                     AND root.status IN ('claimed', 'running')
2598                     AND root.error IS NULL AND root.blocker IS NULL
2599                     AND gr.id = ? AND gr.root_task_id = root.id
2600                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2601                     AND m.id = ? AND m.goal_id = ? AND m.version = ?
2602                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
2603                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2604                     AND g.status = 'active' AND g.domain = 'orchestration'
2605                     AND g.goal_type = 'continuous'
2606                     AND dc.mandate_id = m.id AND dc.mandate_version = m.version
2607                     AND dc.outcome = 'act'
2608                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
2609                     AND i.status = 'committed'
2610               )",
2611        )
2612        .bind(root_task_attempt_id)
2613        .bind(goal_run_id)
2614        .bind(goal_run_id)
2615        .bind(mandate_id)
2616        .bind(&task.goal_id)
2617        .bind(mandate_version)
2618        .bind(&now)
2619        .execute(&mut *tx)
2620        .await?;
2621        if fenced.rows_affected() != 1 {
2622            tx.rollback().await?;
2623            return Ok(false);
2624        }
2625
2626        let task_count = sqlx::query_scalar::<_, i64>(
2627            "SELECT COUNT(*) FROM tasks
2628             WHERE goal_run_id = ?
2629               AND id != (SELECT root_task_id FROM goal_runs WHERE id = ?)",
2630        )
2631        .bind(goal_run_id)
2632        .bind(goal_run_id)
2633        .fetch_one(&mut *tx)
2634        .await?;
2635        if task_count >= max_non_root_tasks {
2636            tx.rollback().await?;
2637            return Ok(false);
2638        }
2639
2640        if let Some(raw_dependencies) = task.depends_on.as_deref() {
2641            let dependencies = serde_json::from_str::<Vec<String>>(raw_dependencies)?;
2642            let unique = dependencies
2643                .iter()
2644                .collect::<std::collections::HashSet<_>>();
2645            anyhow::ensure!(
2646                unique.len() == dependencies.len(),
2647                "mandate task dependencies must be unique"
2648            );
2649            for dependency in dependencies {
2650                let in_run = sqlx::query_scalar::<_, i64>(
2651                    "SELECT COUNT(*) FROM tasks WHERE id = ? AND goal_run_id = ?",
2652                )
2653                .bind(&dependency)
2654                .bind(goal_run_id)
2655                .fetch_one(&mut *tx)
2656                .await?;
2657                anyhow::ensure!(in_run == 1, "mandate task dependency is outside this run");
2658            }
2659        }
2660
2661        let inserted = sqlx::query(
2662            "INSERT INTO tasks (
2663                id, goal_id, goal_run_id, description, status, priority, task_order,
2664                parallel_group, depends_on, agent_id, context, result, error, blocker,
2665                idempotent, retry_count, max_retries, created_at, started_at, completed_at,
2666                updated_at
2667             ) VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL,
2668                       0, 0, 0, ?, NULL, NULL, ?)",
2669        )
2670        .bind(&task.id)
2671        .bind(&task.goal_id)
2672        .bind(goal_run_id)
2673        .bind(&task.description)
2674        .bind(&task.priority)
2675        .bind(task.task_order)
2676        .bind(&task.parallel_group)
2677        .bind(&task.depends_on)
2678        .bind(&task.created_at)
2679        .bind(&task.created_at)
2680        .execute(&mut *tx)
2681        .await?;
2682        anyhow::ensure!(
2683            inserted.rows_affected() == 1,
2684            "mandate task was not inserted"
2685        );
2686        let dependencies = task.dependency_ids().map_err(anyhow::Error::msg)?;
2687        super::goals::replace_task_dependencies(&mut tx, &task.id, &dependencies).await?;
2688        tx.commit().await?;
2689        Ok(true)
2690    }
2691
2692    async fn claim_mandate_task_from_attempt(
2693        &self,
2694        task_id: &str,
2695        worker_instance_id: &str,
2696        mandate_id: &str,
2697        mandate_version: i64,
2698        goal_run_id: &str,
2699        root_task_attempt_id: &str,
2700        lease_secs: i64,
2701    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
2702        anyhow::ensure!(mandate_version > 0, "mandate version must be positive");
2703        anyhow::ensure!(
2704            !task_id.trim().is_empty()
2705                && !worker_instance_id.trim().is_empty()
2706                && !root_task_attempt_id.trim().is_empty(),
2707            "mandate claim identity is required"
2708        );
2709        let lease_secs = lease_secs.clamp(1, 86_400);
2710        let now = chrono::Utc::now();
2711        let now_string = now.to_rfc3339();
2712        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2713        let fenced = sqlx::query(
2714            "UPDATE task_attempts
2715             SET last_heartbeat_at = datetime('now')
2716             WHERE id = ? AND goal_run_id = ?
2717               AND status IN ('claimed', 'running')
2718               AND datetime(lease_expires_at) > datetime('now')
2719               AND EXISTS (
2720                   SELECT 1
2721                   FROM tasks root
2722                   JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2723                   JOIN mandates m ON m.goal_id = gr.goal_id
2724                   JOIN goals g ON g.id = m.goal_id
2725                   JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
2726                   JOIN intentions i ON i.decision_cycle_id = dc.id
2727                   WHERE root.id = task_attempts.task_id
2728                     AND root.current_attempt_id = task_attempts.id
2729                     AND root.status IN ('claimed', 'running')
2730                     AND root.error IS NULL AND root.blocker IS NULL
2731                     AND gr.id = ? AND gr.root_task_id = root.id
2732                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2733                     AND m.id = ?
2734                     AND m.goal_id = (SELECT goal_id FROM tasks WHERE id = ?)
2735                     AND m.version = ?
2736                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
2737                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2738                     AND g.status = 'active' AND g.domain = 'orchestration'
2739                     AND g.goal_type = 'continuous'
2740                     AND dc.mandate_id = m.id AND dc.mandate_version = m.version
2741                     AND dc.outcome = 'act'
2742                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
2743                     AND i.status = 'committed'
2744               )",
2745        )
2746        .bind(root_task_attempt_id)
2747        .bind(goal_run_id)
2748        .bind(goal_run_id)
2749        .bind(mandate_id)
2750        .bind(task_id)
2751        .bind(mandate_version)
2752        .bind(&now_string)
2753        .execute(&mut *tx)
2754        .await?;
2755        if fenced.rows_affected() != 1 {
2756            tx.rollback().await?;
2757            return Ok(None);
2758        }
2759
2760        let claimable = sqlx::query_scalar::<_, String>(
2761            "SELECT t.goal_id
2762             FROM tasks t JOIN goal_runs gr ON gr.id = t.goal_run_id
2763             WHERE t.id = ? AND t.goal_run_id = ? AND t.id != gr.root_task_id
2764               AND t.status = 'pending' AND t.current_attempt_id IS NULL
2765               AND t.worker_profile_id IS NULL
2766               AND COALESCE(t.workspace_policy_explicit, 0) = 0
2767               AND NOT EXISTS (SELECT 1 FROM task_workspaces w WHERE w.task_id = t.id)",
2768        )
2769        .bind(task_id)
2770        .bind(goal_run_id)
2771        .fetch_optional(&mut *tx)
2772        .await?;
2773        if claimable.is_none() {
2774            tx.rollback().await?;
2775            return Ok(None);
2776        }
2777        let unmet = sqlx::query_scalar::<_, i64>(
2778            "SELECT COUNT(*)
2779             FROM json_each(COALESCE((SELECT depends_on FROM tasks WHERE id = ?), '[]')) dep
2780             WHERE NOT EXISTS (
2781                SELECT 1 FROM tasks d
2782                WHERE d.id = CAST(dep.value AS TEXT)
2783                  AND d.goal_run_id = ?
2784                  AND d.status IN ('completed', 'skipped', 'superseded')
2785             )",
2786        )
2787        .bind(task_id)
2788        .bind(goal_run_id)
2789        .fetch_one(&mut *tx)
2790        .await?;
2791        if unmet > 0 {
2792            tx.rollback().await?;
2793            return Ok(None);
2794        }
2795
2796        let attempt = crate::traits::TaskAttempt {
2797            id: uuid::Uuid::new_v4().to_string(),
2798            task_id: task_id.to_string(),
2799            goal_run_id: goal_run_id.to_string(),
2800            worker_profile_id: None,
2801            worker_instance_id: worker_instance_id.to_string(),
2802            lease_token: uuid::Uuid::new_v4().to_string(),
2803            status: "claimed".to_string(),
2804            lease_expires_at: (now + chrono::Duration::seconds(lease_secs)).to_rfc3339(),
2805            last_heartbeat_at: now_string.clone(),
2806            workspace_id: None,
2807            started_at: now_string,
2808            completed_at: None,
2809        };
2810        sqlx::query(
2811            "INSERT INTO task_attempts
2812                (id, task_id, goal_run_id, worker_profile_id, worker_instance_id,
2813                 lease_token, status, lease_expires_at, last_heartbeat_at,
2814                 workspace_id, started_at, completed_at)
2815             VALUES (?, ?, ?, NULL, ?, ?, 'claimed', ?, ?, NULL, ?, NULL)",
2816        )
2817        .bind(&attempt.id)
2818        .bind(&attempt.task_id)
2819        .bind(&attempt.goal_run_id)
2820        .bind(&attempt.worker_instance_id)
2821        .bind(&attempt.lease_token)
2822        .bind(&attempt.lease_expires_at)
2823        .bind(&attempt.last_heartbeat_at)
2824        .bind(&attempt.started_at)
2825        .execute(&mut *tx)
2826        .await?;
2827        let updated = sqlx::query(
2828            "UPDATE tasks
2829             SET status = 'claimed', agent_id = ?, current_attempt_id = ?,
2830                 worker_profile_id = NULL, started_at = COALESCE(started_at, datetime('now')),
2831                 result = NULL, error = NULL, blocker = NULL, completed_at = NULL,
2832                 updated_at = datetime('now'), version = version + 1
2833             WHERE id = ? AND goal_run_id = ? AND status = 'pending'
2834               AND current_attempt_id IS NULL",
2835        )
2836        .bind(worker_instance_id)
2837        .bind(&attempt.id)
2838        .bind(task_id)
2839        .bind(goal_run_id)
2840        .execute(&mut *tx)
2841        .await?;
2842        if updated.rows_affected() != 1 {
2843            tx.rollback().await?;
2844            return Ok(None);
2845        }
2846        tx.commit().await?;
2847        Ok(Some(attempt))
2848    }
2849
2850    async fn record_mandate_decision(
2851        &self,
2852        decision: &MandateDecisionCycle,
2853        intention: Option<&Intention>,
2854        task_attempt_id: Option<&str>,
2855    ) -> anyhow::Result<()> {
2856        self.record_mandate_decision_with_updates(decision, intention, None, task_attempt_id)
2857            .await
2858    }
2859
2860    async fn record_mandate_decision_with_updates(
2861        &self,
2862        decision: &MandateDecisionCycle,
2863        intention: Option<&Intention>,
2864        operating_updates: Option<&MandateOperatingUpdates>,
2865        task_attempt_id: Option<&str>,
2866    ) -> anyhow::Result<()> {
2867        decision
2868            .validate_content_bounds()
2869            .map_err(anyhow::Error::msg)?;
2870        if let Some(updates) = operating_updates
2871            && let Some(note) = updates.learning_note.as_ref()
2872        {
2873            note.validate().map_err(anyhow::Error::msg)?;
2874            anyhow::ensure!(
2875                note.mandate_id == decision.mandate_id
2876                    && note.mandate_version == decision.mandate_version
2877                    && note.learned_in_decision_cycle_id == decision.id,
2878                "learning note does not belong to this decision"
2879            );
2880            anyhow::ensure!(
2881                note.evidence_receipt_ids
2882                    .iter()
2883                    .all(|id| decision.evidence_receipt_ids.contains(id)),
2884                "learning evidence must be a subset of current decision evidence"
2885            );
2886        }
2887        anyhow::ensure!(
2888            decision.action_attempts == 0,
2889            "a new decision cannot pre-spend actions"
2890        );
2891        anyhow::ensure!(
2892            (decision.outcome == MandateDecisionOutcome::Act) == intention.is_some(),
2893            "ACT requires one intention and non-ACT outcomes must not create one"
2894        );
2895        // Reject malformed or policy-unrelated value judgments before taking
2896        // the SQLite writer lock. The same checks are repeated below against
2897        // the transaction-fenced mandate snapshot, so a racing policy update
2898        // still fails closed.
2899        if let Some(intention) = intention
2900            && let Some(mandate) = self.get_mandate(&decision.mandate_id).await?
2901        {
2902            intention
2903                .validate_value_against(&mandate)
2904                .map_err(anyhow::Error::msg)?;
2905        }
2906        if decision.outcome == MandateDecisionOutcome::Ask {
2907            anyhow::ensure!(
2908                decision
2909                    .question
2910                    .as_deref()
2911                    .is_some_and(|value| !value.trim().is_empty()),
2912                "ASK requires a concrete question"
2913            );
2914        }
2915        if let Some(alert) = decision.owner_alert.as_deref() {
2916            anyhow::ensure!(
2917                decision.outcome == MandateDecisionOutcome::Wait && !alert.trim().is_empty(),
2918                "owner_alert is a non-empty finding carried by a WAIT"
2919            );
2920        }
2921        anyhow::ensure!(
2922            decision.outcome == MandateDecisionOutcome::Stop
2923                || (decision.termination_kind.is_none() && decision.termination_match.is_none()),
2924            "termination fields are valid only for STOP"
2925        );
2926
2927        let now = chrono::Utc::now();
2928        let now_string = now.to_rfc3339();
2929        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2930        if let Some(task_attempt_id) = task_attempt_id {
2931            anyhow::ensure!(
2932                !task_attempt_id.trim().is_empty() && task_attempt_id.trim() == task_attempt_id,
2933                "task attempt id must be canonical"
2934            );
2935            // This is deliberately a write-CAS rather than a preceding read.
2936            // It acquires the SQLite writer lock while proving that the exact
2937            // dispatcher-owned root attempt is still current, live, and bound
2938            // to the pinned mandate run. Attempt replacement cannot race the
2939            // decision insert after this statement within the transaction.
2940            let fenced = sqlx::query(
2941                "UPDATE task_attempts
2942                 SET last_heartbeat_at = datetime('now')
2943                 WHERE id = ? AND goal_run_id = ?
2944                   AND status IN ('claimed', 'running')
2945                   AND datetime(lease_expires_at) > datetime('now')
2946                   AND EXISTS (
2947                       SELECT 1
2948                       FROM tasks t
2949                       JOIN goal_runs gr ON gr.id = task_attempts.goal_run_id
2950                       WHERE t.id = task_attempts.task_id
2951                         AND t.current_attempt_id = task_attempts.id
2952                         AND t.status IN ('claimed', 'running')
2953                         AND t.error IS NULL AND t.blocker IS NULL
2954                         AND gr.id = ? AND gr.root_task_id = t.id
2955                         AND gr.trigger_type = 'mandate' AND gr.status = 'running'
2956                   )",
2957            )
2958            .bind(task_attempt_id)
2959            .bind(&decision.goal_run_id)
2960            .bind(&decision.goal_run_id)
2961            .execute(&mut *tx)
2962            .await?;
2963            anyhow::ensure!(
2964                fenced.rows_affected() == 1,
2965                "mandate task-lead attempt is no longer current and executable"
2966            );
2967        }
2968        let query = format!(
2969            "SELECT {}
2970             FROM mandates m
2971             JOIN goals g ON g.id = m.goal_id
2972             JOIN goal_runs gr ON gr.goal_id = m.goal_id
2973             WHERE m.id = ? AND gr.id = ?
2974               AND m.status = 'active'
2975               AND m.confirmed_at IS NOT NULL
2976               AND m.review_lease_token IS NOT NULL
2977               AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
2978               AND g.domain = 'orchestration' AND g.goal_type = 'continuous'
2979               AND g.status = 'active'
2980               AND gr.trigger_type = 'mandate'
2981               AND gr.status = 'running'",
2982            qualified_columns("m", MANDATE_COLUMNS)
2983        );
2984        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
2985            .bind(&decision.mandate_id)
2986            .bind(&decision.goal_run_id)
2987            .bind(&now_string)
2988            .fetch_optional(&mut *tx)
2989            .await?
2990            .ok_or_else(|| anyhow::anyhow!("mandate is not actively leased for this goal run"))?;
2991        let mandate = mandate_from_row(&row)?;
2992        anyhow::ensure!(
2993            decision.mandate_version == mandate.version,
2994            "mandate version changed before the decision was committed"
2995        );
2996        anyhow::ensure!(
2997            decision.owner_alert.is_none() || mandate.authority.owner_alerts,
2998            "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"
2999        );
3000        validate_current_run_receipt_refs(
3001            &mut tx,
3002            &decision.goal_run_id,
3003            &decision.evidence_receipt_ids,
3004        )
3005        .await?;
3006        // A runtime-authored fallback is a typed review-failure marker, not a
3007        // deliberation: it carries no evidence, no intention, and no
3008        // authority, so the semantic gates below (measurement) cannot apply
3009        // to it. Structural gates (lease, version, one decision
3010        // per run) still apply.
3011        let runtime_fallback = decision.is_runtime_fallback();
3012        if runtime_fallback {
3013            anyhow::ensure!(
3014                decision.outcome == MandateDecisionOutcome::Wait
3015                    && decision.evidence_receipt_ids.is_empty()
3016                    && decision.action_attempts == 0
3017                    && intention.is_none()
3018                    && operating_updates.is_none(),
3019                "runtime fallback decisions must be bare WAIT markers"
3020            );
3021        }
3022        // Whether ACT is admissible now is decided here, in the transaction
3023        // that commits the decision, by the same rules as every other
3024        // outcome (`admissibility`), so no caller keeps its own copy.
3025        if decision.outcome == MandateDecisionOutcome::Act {
3026            let quota =
3027                mutation_quota_state_on_connection(&mut tx, &mandate.id, &now_string).await?;
3028            let block = match &quota {
3029                Some(quota) => quota.block_reason,
3030                None => Some(MandateMutationQuotaBlockReason::MutationDisabled),
3031            };
3032            let admissible =
3033                crate::admissibility::admissible_outcomes(&crate::admissibility::OutcomeState {
3034                    quota_block: block,
3035                });
3036            if !admissible.act {
3037                if block == Some(MandateMutationQuotaBlockReason::MutationDisabled) {
3038                    anyhow::bail!(
3039                        "ACT requires a positive governed mutation budget; choose WAIT, ASK, or STOP for an observation-only cycle"
3040                    );
3041                }
3042                let earliest = quota
3043                    .as_ref()
3044                    .and_then(|quota| quota.earliest_next_slot_at.as_deref())
3045                    .unwrap_or("unavailable");
3046                anyhow::bail!(
3047                    "mandate_mutation_quota_unavailable: choose WAIT; earliest_next_slot_at={earliest}"
3048                );
3049            }
3050        }
3051        let current_measurement = if mandate.objective_control.is_some()
3052            && !runtime_fallback
3053            && matches!(
3054                decision.outcome,
3055                MandateDecisionOutcome::Act
3056                    | MandateDecisionOutcome::Wait
3057                    | MandateDecisionOutcome::Stop
3058            ) {
3059            sqlx::query_as::<_, (i64, i64)>(
3060                "SELECT value_micros, confidence_bps FROM mandate_objective_measurements
3061                 WHERE mandate_id = ? AND mandate_version = ? AND goal_run_id = ?
3062                 ORDER BY julianday(observed_at) DESC, id DESC LIMIT 1",
3063            )
3064            .bind(&mandate.id)
3065            .bind(mandate.version)
3066            .bind(&decision.goal_run_id)
3067            .fetch_optional(&mut *tx)
3068            .await?
3069        } else {
3070            None
3071        };
3072        // The measured objective belongs to autopilot. A bounded mandate's
3073        // objective control is advisory: recorded measurements are kept, but
3074        // a decision never waits on one.
3075        let control_loop = mandate.autonomy_mode.is_autopilot();
3076        if control_loop
3077            && mandate.objective_control.is_some()
3078            && !runtime_fallback
3079            && matches!(
3080                decision.outcome,
3081                MandateDecisionOutcome::Act | MandateDecisionOutcome::Wait
3082            )
3083        {
3084            anyhow::ensure!(
3085                current_measurement.is_some(),
3086                "controlled mandate decisions require a receipt-backed metric measurement from the current run"
3087            );
3088        }
3089        if decision.outcome == MandateDecisionOutcome::Stop {
3090            let termination_kind = decision
3091                .termination_kind
3092                .ok_or_else(|| anyhow::anyhow!("STOP requires a typed termination_kind"))?;
3093            match termination_kind {
3094                MandateTerminationKind::SuccessCriteriaSatisfied => {
3095                    if let Some(control) =
3096                        mandate.objective_control.as_ref().filter(|_| control_loop)
3097                    {
3098                        anyhow::ensure!(
3099                            current_measurement.is_some_and(|(value, confidence)| {
3100                                confidence > 0 && control.target_reached(value)
3101                            }),
3102                            "success termination requires a credible (confidence > 0) current receipt-backed metric that reaches the owner-confirmed target"
3103                        );
3104                    }
3105                    let matched = decision.termination_match.as_deref().ok_or_else(|| {
3106                        anyhow::anyhow!("success termination requires termination_match")
3107                    })?;
3108                    anyhow::ensure!(
3109                        mandate
3110                            .success_criteria
3111                            .iter()
3112                            .any(|entry| entry == matched),
3113                        "termination_match is not an owner-authored success criterion"
3114                    );
3115                }
3116                MandateTerminationKind::StopConditionMet => {
3117                    let matched = decision.termination_match.as_deref().ok_or_else(|| {
3118                        anyhow::anyhow!("stop-condition termination requires termination_match")
3119                    })?;
3120                    anyhow::ensure!(
3121                        mandate.stop_conditions.iter().any(|entry| entry == matched),
3122                        "termination_match is not an owner-authored stop condition"
3123                    );
3124                }
3125                MandateTerminationKind::SafetyTermination => {}
3126            }
3127            anyhow::ensure!(
3128                !termination_kind.requires_receipt_evidence()
3129                    || !decision.evidence_receipt_ids.is_empty(),
3130                "evidence-dependent STOP requires at least one current-run receipt"
3131            );
3132        }
3133
3134        let mut next_review_at =
3135            clamped_next_review_at(&mandate, decision.reconsider_at.as_deref(), now)?;
3136        if decision.outcome != MandateDecisionOutcome::Stop
3137            && let Some(control) = mandate.objective_control.as_ref()
3138        {
3139            let measurement_due = now + chrono::Duration::seconds(control.measurement_cadence_secs);
3140            let selected =
3141                chrono::DateTime::parse_from_rfc3339(&next_review_at)?.with_timezone(&chrono::Utc);
3142            if selected > measurement_due {
3143                next_review_at = measurement_due.to_rfc3339();
3144            }
3145        }
3146        let persisted_reconsider_at = if decision.outcome == MandateDecisionOutcome::Stop {
3147            None
3148        } else {
3149            Some(next_review_at.as_str())
3150        };
3151        sqlx::query(
3152            "INSERT INTO mandate_decision_cycles (
3153                id, mandate_id, goal_run_id, mandate_version, outcome, origin, activity_level,
3154                rationale, belief_snapshot, evidence_receipt_ids_json, question, owner_alert,
3155                termination_kind, termination_match, reconsider_at, action_attempts, created_at,
3156                updated_at
3157             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3158        )
3159        .bind(&decision.id)
3160        .bind(&decision.mandate_id)
3161        .bind(&decision.goal_run_id)
3162        .bind(decision.mandate_version)
3163        .bind(decision.outcome.as_str())
3164        .bind(decision.origin.as_str())
3165        .bind(decision.activity_level.as_str())
3166        .bind(&decision.rationale)
3167        .bind(&decision.belief_snapshot)
3168        .bind(serde_json::to_string(&decision.evidence_receipt_ids)?)
3169        .bind(&decision.question)
3170        .bind(&decision.owner_alert)
3171        .bind(
3172            decision
3173                .termination_kind
3174                .map(MandateTerminationKind::as_str),
3175        )
3176        .bind(&decision.termination_match)
3177        .bind(persisted_reconsider_at)
3178        .bind(decision.action_attempts)
3179        .bind(&decision.created_at)
3180        .bind(&decision.updated_at)
3181        .execute(&mut *tx)
3182        .await?;
3183
3184        if let Some(intention) = intention {
3185            anyhow::ensure!(
3186                intention.mandate_id == decision.mandate_id
3187                    && intention.decision_cycle_id == decision.id
3188                    && intention.goal_run_id == decision.goal_run_id,
3189                "intention does not belong to this decision cycle"
3190            );
3191            intention
3192                .validate_content_bounds()
3193                .map_err(anyhow::Error::msg)?;
3194            intention
3195                .validate_value_against(&mandate)
3196                .map_err(anyhow::Error::msg)?;
3197            anyhow::ensure!(
3198                intention.status == IntentionStatus::Committed && intention.completed_at.is_none(),
3199                "a new intention must be committed and incomplete"
3200            );
3201            sqlx::query(
3202                "INSERT INTO intentions (
3203                    id, mandate_id, decision_cycle_id, goal_run_id, description,
3204                    rationale, value_criterion, expected_benefit, risk, invalidation_criteria,
3205                    status, created_at, updated_at, completed_at
3206                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3207            )
3208            .bind(&intention.id)
3209            .bind(&intention.mandate_id)
3210            .bind(&intention.decision_cycle_id)
3211            .bind(&intention.goal_run_id)
3212            .bind(&intention.description)
3213            .bind(&intention.rationale)
3214            .bind(&intention.value_criterion)
3215            .bind(&intention.expected_benefit)
3216            .bind(&intention.risk)
3217            .bind(&intention.invalidation_criteria)
3218            .bind(intention.status.as_str())
3219            .bind(&intention.created_at)
3220            .bind(&intention.updated_at)
3221            .bind(&intention.completed_at)
3222            .execute(&mut *tx)
3223            .await?;
3224        }
3225
3226        if let Some(updates) = operating_updates
3227            && let Some(note) = updates.learning_note.as_ref()
3228        {
3229            sqlx::query(
3230                "INSERT INTO mandate_learning_notes (
3231                        id, mandate_id, mandate_version, learned_in_decision_cycle_id,
3232                        summary, evidence_receipt_ids_json, created_at
3233                     ) VALUES (?, ?, ?, ?, ?, ?, ?)",
3234            )
3235            .bind(&note.id)
3236            .bind(&note.mandate_id)
3237            .bind(note.mandate_version)
3238            .bind(&note.learned_in_decision_cycle_id)
3239            .bind(&note.summary)
3240            .bind(serde_json::to_string(&note.evidence_receipt_ids)?)
3241            .bind(&note.created_at)
3242            .execute(&mut *tx)
3243            .await?;
3244        }
3245
3246        // The durable decision remains provisional until the root task itself
3247        // is durably successful and the proof finalizer closes the run. This
3248        // keeps every post-decision crash inside active orphan reconciliation.
3249        let transitioned = sqlx::query(
3250            "UPDATE mandates
3251             SET next_review_at = ?, review_lease_token = NULL,
3252                 review_lease_expires_at = NULL, updated_at = ?
3253             WHERE id = ? AND status = 'active' AND version = ?
3254               AND confirmed_at IS NOT NULL
3255               AND review_lease_token IS NOT NULL",
3256        )
3257        .bind(&next_review_at)
3258        .bind(&now_string)
3259        .bind(&decision.mandate_id)
3260        .bind(decision.mandate_version)
3261        .execute(&mut *tx)
3262        .await?;
3263        anyhow::ensure!(
3264            transitioned.rows_affected() == 1,
3265            "mandate changed before the decision was committed"
3266        );
3267        tx.commit().await?;
3268        Ok(())
3269    }
3270
3271    async fn get_mandate_decision_for_run(
3272        &self,
3273        goal_run_id: &str,
3274    ) -> anyhow::Result<Option<MandateDecisionCycle>> {
3275        let query =
3276            format!("SELECT {DECISION_COLUMNS} FROM mandate_decision_cycles WHERE goal_run_id = ?");
3277        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
3278            .bind(goal_run_id)
3279            .fetch_optional(self.work_pool())
3280            .await?;
3281        row.as_ref().map(decision_from_row).transpose()
3282    }
3283
3284    async fn current_run_evidence_receipt_ids(
3285        &self,
3286        goal_run_id: &str,
3287        limit: usize,
3288    ) -> anyhow::Result<Vec<String>> {
3289        // The predicate of `validate_current_run_receipt_refs`, so every id
3290        // returned here passes that check.
3291        let excluded = crate::MANDATE_PROTOCOL_TOOLS
3292            .iter()
3293            .map(|_| "?")
3294            .collect::<Vec<_>>()
3295            .join(", ");
3296        let query = format!(
3297            "SELECT json_extract(e.data, '$.tool_call_id')
3298             FROM events e
3299             JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
3300             WHERE e.event_type = 'tool_result'
3301               AND t.goal_run_id = ?
3302               AND json_extract(e.data, '$.receipt.schema_version') = ?
3303               AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
3304               AND json_extract(e.data, '$.receipt.outcome_evidence')
3305                   IN ('tool_reported', 'structured_metadata')
3306               AND json_extract(e.data, '$.tool_call_id') IS NOT NULL
3307               AND json_extract(e.data, '$.name') NOT IN ({excluded})
3308             ORDER BY e.id DESC
3309             LIMIT ?"
3310        );
3311        let mut statement = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*query))
3312            .bind(goal_run_id)
3313            .bind(i64::from(aidaemon_events::ToolReceiptV1::SCHEMA_VERSION));
3314        for tool in crate::MANDATE_PROTOCOL_TOOLS {
3315            statement = statement.bind(*tool);
3316        }
3317        Ok(statement
3318            .bind(i64::try_from(limit).unwrap_or(i64::MAX))
3319            .fetch_all(self.work_pool())
3320            .await?)
3321    }
3322
3323    async fn list_mandate_decisions(
3324        &self,
3325        mandate_id: &str,
3326        limit: i64,
3327    ) -> anyhow::Result<Vec<MandateDecisionCycle>> {
3328        let query = format!(
3329            "SELECT {DECISION_COLUMNS} FROM mandate_decision_cycles
3330             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3331        );
3332        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3333            .bind(mandate_id)
3334            .bind(limit.clamp(1, 200))
3335            .fetch_all(self.work_pool())
3336            .await?;
3337        rows.iter().map(decision_from_row).collect()
3338    }
3339
3340    async fn list_intentions(
3341        &self,
3342        mandate_id: &str,
3343        limit: i64,
3344    ) -> anyhow::Result<Vec<Intention>> {
3345        let query = format!(
3346            "SELECT {INTENTION_COLUMNS} FROM intentions
3347             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3348        );
3349        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3350            .bind(mandate_id)
3351            .bind(limit.clamp(1, 200))
3352            .fetch_all(self.work_pool())
3353            .await?;
3354        rows.iter().map(intention_from_row).collect()
3355    }
3356
3357    async fn record_mandate_learning_note(&self, note: &MandateLearningNote) -> anyhow::Result<()> {
3358        note.validate().map_err(anyhow::Error::msg)?;
3359        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3360        let decision_exists = sqlx::query_scalar::<_, i64>(
3361            "SELECT 1
3362             FROM mandate_decision_cycles dc
3363             JOIN mandates m ON m.id = dc.mandate_id
3364             WHERE dc.id = ? AND dc.mandate_id = ? AND dc.mandate_version = ?
3365               AND m.version >= dc.mandate_version
3366             LIMIT 1",
3367        )
3368        .bind(&note.learned_in_decision_cycle_id)
3369        .bind(&note.mandate_id)
3370        .bind(note.mandate_version)
3371        .fetch_optional(&mut *tx)
3372        .await?;
3373        anyhow::ensure!(
3374            decision_exists.is_some(),
3375            "mandate learning note does not belong to its decision epoch"
3376        );
3377
3378        let mut unique = std::collections::HashSet::new();
3379        for receipt_id in &note.evidence_receipt_ids {
3380            anyhow::ensure!(
3381                unique.insert(receipt_id),
3382                "duplicate learning evidence receipt ID"
3383            );
3384            let found = sqlx::query_scalar::<_, i64>(
3385                "SELECT 1
3386                 FROM events e
3387                 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
3388                 JOIN goal_runs gr ON gr.id = t.goal_run_id
3389                 JOIN mandates m ON m.goal_id = gr.goal_id
3390                 WHERE m.id = ? AND gr.trigger_type = 'mandate'
3391                   AND e.event_type = 'tool_result'
3392                   AND json_extract(e.data, '$.tool_call_id') = ?
3393                   AND json_extract(e.data, '$.receipt.schema_version') = ?
3394                   AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
3395                   AND json_extract(e.data, '$.receipt.outcome_evidence')
3396                       IN ('tool_reported', 'structured_metadata')
3397                 LIMIT 1",
3398            )
3399            .bind(&note.mandate_id)
3400            .bind(receipt_id)
3401            .bind(i64::from(aidaemon_events::ToolReceiptV1::SCHEMA_VERSION))
3402            .fetch_optional(&mut *tx)
3403            .await?;
3404            anyhow::ensure!(
3405                found.is_some(),
3406                "learning evidence receipt `{receipt_id}` is not a same-mandate structured success"
3407            );
3408        }
3409
3410        sqlx::query(
3411            "INSERT INTO mandate_learning_notes (
3412                id, mandate_id, mandate_version, learned_in_decision_cycle_id,
3413                summary, evidence_receipt_ids_json, created_at
3414             ) VALUES (?, ?, ?, ?, ?, ?, ?)",
3415        )
3416        .bind(&note.id)
3417        .bind(&note.mandate_id)
3418        .bind(note.mandate_version)
3419        .bind(&note.learned_in_decision_cycle_id)
3420        .bind(&note.summary)
3421        .bind(serde_json::to_string(&note.evidence_receipt_ids)?)
3422        .bind(&note.created_at)
3423        .execute(&mut *tx)
3424        .await?;
3425        tx.commit().await?;
3426        Ok(())
3427    }
3428
3429    async fn list_mandate_learning_notes(
3430        &self,
3431        mandate_id: &str,
3432        limit: i64,
3433    ) -> anyhow::Result<Vec<MandateLearningNote>> {
3434        let query = format!(
3435            "SELECT {LEARNING_NOTE_COLUMNS} FROM mandate_learning_notes
3436             WHERE mandate_id = ? ORDER BY julianday(created_at) DESC, id DESC LIMIT ?"
3437        );
3438        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3439            .bind(mandate_id)
3440            .bind(limit.clamp(1, 100))
3441            .fetch_all(self.work_pool())
3442            .await?;
3443        rows.iter().map(learning_note_from_row).collect()
3444    }
3445
3446    async fn wake_mandates_for_signal(
3447        &self,
3448        signal: &MandateWakeSignal,
3449    ) -> anyhow::Result<Vec<String>> {
3450        signal.validate().map_err(anyhow::Error::msg)?;
3451        let mandates = self.list_mandates(None, false).await?;
3452        let mut target = reqwest::Url::parse(&signal.target_url)?;
3453        target.set_query(None);
3454        target.set_fragment(None);
3455        let target_url = target.to_string();
3456        let signal_digest = hex::encode(Sha256::digest(
3457            format!(
3458                "aidaemon.mandate.wake.v1\0{}\0{}\0{}\0{}\0{}",
3459                signal.kind.as_str(),
3460                signal.source,
3461                signal.target_url,
3462                signal.account_id.as_deref().unwrap_or(""),
3463                signal.dedupe_key
3464            )
3465            .as_bytes(),
3466        ));
3467        let received_at = chrono::Utc::now().to_rfc3339();
3468        let mut awakened = Vec::new();
3469        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3470        for mandate in mandates
3471            .into_iter()
3472            .filter(|mandate| crate::authority::mandate_accepts_wake_signal(mandate, signal))
3473        {
3474            let inserted = sqlx::query(
3475                "INSERT OR IGNORE INTO mandate_wake_signals (
3476                    mandate_id, mandate_version, signal_digest, kind, source,
3477                    target_url, account_id, occurred_at, received_at
3478                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
3479            )
3480            .bind(&mandate.id)
3481            .bind(mandate.version)
3482            .bind(&signal_digest)
3483            .bind(signal.kind.as_str())
3484            .bind(&signal.source)
3485            .bind(&target_url)
3486            .bind(&signal.account_id)
3487            .bind(&signal.occurred_at)
3488            .bind(&received_at)
3489            .execute(&mut *tx)
3490            .await?;
3491            if inserted.rows_affected() == 0 {
3492                continue;
3493            }
3494            let updated = sqlx::query(
3495                "UPDATE mandates
3496                 SET next_review_at = CASE
3497                        WHEN julianday(next_review_at) > julianday(?) THEN ?
3498                        ELSE next_review_at
3499                     END
3500                 WHERE id = ? AND version = ? AND status = 'active'
3501                   AND autonomy_mode = 'autopilot' AND confirmed_at IS NOT NULL",
3502            )
3503            .bind(&received_at)
3504            .bind(&received_at)
3505            .bind(&mandate.id)
3506            .bind(mandate.version)
3507            .execute(&mut *tx)
3508            .await?;
3509            if updated.rows_affected() == 1 {
3510                awakened.push(mandate.id);
3511            }
3512        }
3513        tx.commit().await?;
3514        Ok(awakened)
3515    }
3516
3517    async fn resolve_mandate_suspension(
3518        &self,
3519        mandate_id: &str,
3520        expected_version: i64,
3521        expected_kind: MandateSuspensionKind,
3522        controller_context: Option<&str>,
3523        reconciliation_resolution: Option<MandateReconciliationResolution>,
3524        owner_guidance: &str,
3525        owner_session: &str,
3526    ) -> anyhow::Result<bool> {
3527        anyhow::ensure!(
3528            !owner_guidance.trim().is_empty() && owner_guidance.trim() == owner_guidance,
3529            "owner guidance is required and must be canonical"
3530        );
3531        anyhow::ensure!(
3532            owner_guidance.chars().count() <= 1024 && owner_guidance.len() <= 1024,
3533            "owner guidance exceeds its 1 KiB bound"
3534        );
3535        anyhow::ensure!(
3536            !owner_session.trim().is_empty(),
3537            "owner session is required"
3538        );
3539        if let Some(context) = controller_context {
3540            anyhow::ensure!(
3541                context.chars().count() <= 64_000,
3542                "mandate controller context is too large"
3543            );
3544            serde_json::from_str::<serde_json::Value>(context)?;
3545        }
3546        match expected_kind {
3547            MandateSuspensionKind::AwaitingAnswer => anyhow::ensure!(
3548                reconciliation_resolution.is_none(),
3549                "non-reconciliation suspensions cannot carry a reconciliation resolution"
3550            ),
3551            MandateSuspensionKind::ReconciliationRequired
3552            | MandateSuspensionKind::ExecutionLeaseLost
3553            | MandateSuspensionKind::ReviewFailed
3554            | MandateSuspensionKind::AuthorityRevokedWithUnresolvedMutation => anyhow::ensure!(
3555                reconciliation_resolution.is_some(),
3556                "safety suspension requires a typed reconciliation resolution"
3557            ),
3558            MandateSuspensionKind::OwnerPaused => {
3559                anyhow::bail!("owner-paused mandates must use ordinary resume")
3560            }
3561        }
3562
3563        let now = chrono::Utc::now().to_rfc3339();
3564        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3565        let current = sqlx::query(
3566            "SELECT goal_id, created_by_session, suspension_json
3567             FROM mandates
3568             WHERE id = ? AND version = ? AND status = 'awaiting_input'
3569               AND confirmed_at IS NOT NULL",
3570        )
3571        .bind(mandate_id)
3572        .bind(expected_version)
3573        .fetch_optional(&mut *tx)
3574        .await?;
3575        let Some(current) = current else {
3576            tx.rollback().await?;
3577            return Ok(false);
3578        };
3579        anyhow::ensure!(
3580            current.get::<String, _>("created_by_session") == owner_session,
3581            "mandate does not belong to this owner session"
3582        );
3583        let suspension: MandateSuspension = serde_json::from_str(
3584            &current
3585                .get::<Option<String>, _>("suspension_json")
3586                .ok_or_else(|| anyhow::anyhow!("awaiting-input mandate has no typed suspension"))?,
3587        )?;
3588        anyhow::ensure!(
3589            suspension.kind == expected_kind,
3590            "mandate suspension changed before it was resolved"
3591        );
3592        let goal_id: String = current.get("goal_id");
3593
3594        if let Some(resolution) = reconciliation_resolution {
3595            sqlx::query(
3596                "INSERT INTO mandate_reconciliations (
3597                    id, mandate_id, suspended_version, suspension_kind, resolution,
3598                    owner_guidance, resolved_by_session, resolved_at
3599                 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
3600            )
3601            .bind(uuid::Uuid::new_v4().to_string())
3602            .bind(mandate_id)
3603            .bind(expected_version)
3604            .bind(expected_kind.as_str())
3605            .bind(resolution.as_str())
3606            .bind(owner_guidance)
3607            .bind(owner_session)
3608            .bind(&now)
3609            .execute(&mut *tx)
3610            .await?;
3611        }
3612
3613        let updated = sqlx::query(
3614            "UPDATE mandates
3615             SET status = 'active', suspension_json = NULL, next_review_at = ?,
3616                 review_lease_token = NULL, review_lease_expires_at = NULL,
3617                 version = version + 1, updated_at = ?
3618             WHERE id = ? AND version = ? AND status = 'awaiting_input'",
3619        )
3620        .bind(&now)
3621        .bind(&now)
3622        .bind(mandate_id)
3623        .bind(expected_version)
3624        .execute(&mut *tx)
3625        .await?;
3626        if updated.rows_affected() != 1 {
3627            tx.rollback().await?;
3628            return Ok(false);
3629        }
3630        if let Some(context) = controller_context {
3631            sqlx::query("UPDATE goals SET context = ?, updated_at = ? WHERE id = ?")
3632                .bind(context)
3633                .bind(&now)
3634                .bind(&goal_id)
3635                .execute(&mut *tx)
3636                .await?;
3637        }
3638        update_controller_status(&mut tx, &goal_id, MandateStatus::Active, &now).await?;
3639        tx.commit().await?;
3640        Ok(true)
3641    }
3642
3643    async fn reserve_mandate_action_attempt(
3644        &self,
3645        reservation: &MandateMutationReservation,
3646    ) -> anyhow::Result<Option<MandateMutationAttempt>> {
3647        let reserved_at = validate_mutation_reservation(reservation)?;
3648        let expected_attempts = reservation.grant.reserved_action_attempt - 1;
3649        let reserved_at_string = reserved_at.to_rfc3339();
3650        let mutation_effects_json = serde_json::to_string(&reservation.mutation_effects)?;
3651        let targets_json = serde_json::to_string(&reservation.targets)?;
3652        let account_identifiers_json = serde_json::to_string(&reservation.account_identifiers)?;
3653        let ledger_id = uuid::Uuid::new_v4().to_string();
3654        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3655
3656        // This UPDATE is deliberately the transaction's first database access.
3657        // SQLite therefore acquires the writer lock before evaluating the
3658        // cross-cycle counts, making the last quota slot race-free.
3659        let result = sqlx::query(
3660            "UPDATE mandate_decision_cycles AS dc
3661             SET action_attempts = action_attempts + 1, updated_at = ?
3662             WHERE dc.id = ? AND dc.outcome = 'act'
3663               AND dc.mandate_id = ? AND dc.mandate_version = ?
3664               AND dc.goal_run_id = ?
3665               AND dc.action_attempts = ?
3666               AND ? = dc.action_attempts + 1
3667               AND EXISTS (
3668                   SELECT 1
3669                   FROM mandates m
3670                   JOIN goals g ON g.id = m.goal_id
3671                   JOIN goal_runs gr ON gr.id = dc.goal_run_id AND gr.goal_id = m.goal_id
3672                   JOIN intentions i ON i.decision_cycle_id = dc.id
3673                   JOIN tasks root ON root.id = gr.root_task_id AND root.goal_run_id = gr.id
3674                   JOIN task_attempts root_attempt
3675                     ON root_attempt.id = root.current_attempt_id
3676                    AND root_attempt.task_id = root.id
3677                    AND root_attempt.goal_run_id = gr.id
3678                   JOIN tasks worker ON worker.id = ? AND worker.goal_run_id = gr.id
3679                   JOIN task_attempts worker_attempt
3680                     ON worker_attempt.id = worker.current_attempt_id
3681                    AND worker_attempt.task_id = worker.id
3682                    AND worker_attempt.goal_run_id = gr.id
3683                   WHERE m.id = dc.mandate_id
3684                     AND m.owner_principal_id = ?
3685                     AND m.status = 'active' AND g.status = 'active'
3686                     AND m.confirmed_at IS NOT NULL
3687                     AND m.version = dc.mandate_version
3688                     AND gr.trigger_type = 'mandate'
3689                     AND gr.status = 'running'
3690                     AND gr.root_task_id = ?
3691                     AND root.id != worker.id
3692                     AND root.status IN ('claimed', 'running')
3693                     AND root.current_attempt_id = ?
3694                     AND root_attempt.id = ?
3695                     AND root_attempt.status IN ('claimed', 'running')
3696                     AND julianday(root_attempt.lease_expires_at) > julianday(?)
3697                     AND worker.status IN ('claimed', 'running')
3698                     AND worker.current_attempt_id = ?
3699                     AND worker_attempt.id = ?
3700                     AND worker_attempt.status IN ('claimed', 'running')
3701                     AND julianday(worker_attempt.lease_expires_at) > julianday(?)
3702                     AND i.mandate_id = m.id AND i.goal_run_id = gr.id
3703                     AND i.status = 'committed' AND i.completed_at IS NULL
3704                     AND dc.action_attempts < CAST(
3705                         COALESCE(json_extract(m.authority_json,
3706                             '$.max_mutating_actions_per_cycle'), 0) AS INTEGER
3707                     )
3708                     AND CAST(COALESCE(json_extract(m.authority_json,
3709                             '$.max_mutating_actions_per_rolling_24h'), 0) AS INTEGER) > 0
3710                     AND (
3711                         SELECT COUNT(*) FROM mandate_mutation_attempts prior
3712                         WHERE prior.mandate_id = m.id
3713                           AND prior.status != 'never_dispatched'
3714                           AND julianday(prior.reserved_at) > julianday(?) - 1.0
3715                     ) < CAST(COALESCE(json_extract(m.authority_json,
3716                             '$.max_mutating_actions_per_rolling_24h'), 0) AS INTEGER)
3717                     AND NOT EXISTS (
3718                         SELECT 1 FROM mandate_mutation_attempts recent
3719                         WHERE recent.mandate_id = m.id
3720                           AND recent.status != 'never_dispatched'
3721                           AND julianday(recent.reserved_at) > julianday(?) -
3722                               (CAST(COALESCE(json_extract(m.authority_json,
3723                                   '$.min_seconds_between_mutations'), 0) AS REAL) / 86400.0)
3724                     )
3725                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
3726               )",
3727        )
3728        .bind(&reserved_at_string)
3729        .bind(&reservation.grant.decision_cycle_id)
3730        .bind(&reservation.grant.mandate_id)
3731        .bind(reservation.grant.mandate_version)
3732        .bind(&reservation.goal_run_id)
3733        .bind(expected_attempts)
3734        .bind(reservation.grant.reserved_action_attempt)
3735        .bind(&reservation.task_id)
3736        .bind(&reservation.grant.owner_principal_id)
3737        .bind(&reservation.root_task_id)
3738        .bind(&reservation.root_task_attempt_id)
3739        .bind(&reservation.root_task_attempt_id)
3740        .bind(&reserved_at_string)
3741        .bind(&reservation.task_attempt_id)
3742        .bind(&reservation.task_attempt_id)
3743        .bind(&reserved_at_string)
3744        .bind(&reserved_at_string)
3745        .bind(&reserved_at_string)
3746        .bind(&reserved_at_string)
3747        .execute(&mut *tx)
3748        .await?;
3749        if result.rows_affected() != 1 {
3750            tx.rollback().await?;
3751            return Ok(None);
3752        }
3753
3754        let intention_id = sqlx::query_scalar::<_, String>(
3755            "SELECT id FROM intentions
3756             WHERE decision_cycle_id = ? AND mandate_id = ? AND goal_run_id = ?
3757               AND status = 'committed' AND completed_at IS NULL",
3758        )
3759        .bind(&reservation.grant.decision_cycle_id)
3760        .bind(&reservation.grant.mandate_id)
3761        .bind(&reservation.goal_run_id)
3762        .fetch_one(&mut *tx)
3763        .await?;
3764
3765        sqlx::query(
3766            "INSERT INTO mandate_mutation_attempts (
3767                id, mandate_id, mandate_version, decision_cycle_id, goal_run_id, intention_id,
3768                root_task_id, root_task_attempt_id, task_id, task_attempt_id,
3769                reserved_action_attempt, action_digest, tool_call_id, tool_name,
3770                mutation_effects_json, targets_json, account_identifiers_json,
3771                status, reserved_at
3772             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'reserved', ?)",
3773        )
3774        .bind(&ledger_id)
3775        .bind(&reservation.grant.mandate_id)
3776        .bind(reservation.grant.mandate_version)
3777        .bind(&reservation.grant.decision_cycle_id)
3778        .bind(&reservation.goal_run_id)
3779        .bind(&intention_id)
3780        .bind(&reservation.root_task_id)
3781        .bind(&reservation.root_task_attempt_id)
3782        .bind(&reservation.task_id)
3783        .bind(&reservation.task_attempt_id)
3784        .bind(reservation.grant.reserved_action_attempt)
3785        .bind(&reservation.grant.action_digest)
3786        .bind(&reservation.tool_call_id)
3787        .bind(&reservation.tool_name)
3788        .bind(&mutation_effects_json)
3789        .bind(&targets_json)
3790        .bind(&account_identifiers_json)
3791        .bind(&reserved_at_string)
3792        .execute(&mut *tx)
3793        .await?;
3794
3795        let query = format!(
3796            "SELECT {MUTATION_ATTEMPT_COLUMNS} FROM mandate_mutation_attempts WHERE id = ?"
3797        );
3798        let row = sqlx::query(sqlx::AssertSqlSafe(&*query))
3799            .bind(&ledger_id)
3800            .fetch_one(&mut *tx)
3801            .await?;
3802        let attempt = mutation_attempt_from_row(&row)?;
3803        tx.commit().await?;
3804        Ok(Some(attempt))
3805    }
3806
3807    async fn claim_mandate_mutation_dispatch(
3808        &self,
3809        claim: &MandateMutationDispatchClaim,
3810    ) -> anyhow::Result<bool> {
3811        anyhow::ensure!(
3812            claim.grant.counts_toward_cycle_budget
3813                && claim.grant.mandate_version > 0
3814                && claim.grant.reserved_action_attempt > 0,
3815            "mutation dispatch requires a positive metered grant"
3816        );
3817        validate_canonical_identifier("owner principal id", &claim.grant.owner_principal_id, 256)?;
3818        anyhow::ensure!(
3819            claim.grant.action_digest.len() == 64
3820                && claim
3821                    .grant
3822                    .action_digest
3823                    .bytes()
3824                    .all(|byte| byte.is_ascii_hexdigit()),
3825            "invalid mutation dispatch action digest"
3826        );
3827        anyhow::ensure!(
3828            claim.grant.tool_call_id.as_deref() == Some(claim.tool_call_id.as_str()),
3829            "mutation dispatch tool call does not match its bound grant"
3830        );
3831        for (label, value) in [
3832            ("mandate id", claim.grant.mandate_id.as_str()),
3833            ("decision cycle id", claim.grant.decision_cycle_id.as_str()),
3834            ("goal run id", claim.goal_run_id.as_str()),
3835            ("root task id", claim.root_task_id.as_str()),
3836            ("root task attempt id", claim.root_task_attempt_id.as_str()),
3837            ("task id", claim.task_id.as_str()),
3838            ("task attempt id", claim.task_attempt_id.as_str()),
3839            ("tool call id", claim.tool_call_id.as_str()),
3840            ("tool name", claim.tool_name.as_str()),
3841        ] {
3842            validate_canonical_identifier(label, value, 256)?;
3843        }
3844        anyhow::ensure!(
3845            claim.root_task_id != claim.task_id,
3846            "the mandate deliberator cannot dispatch mutations"
3847        );
3848        validate_timestamp("mutation dispatch claimed_at", &claim.claimed_at)?;
3849
3850        // This single conditional write is the one-use point. Concurrent or
3851        // replayed dispatches cannot both move dispatch_claimed_at from NULL,
3852        // and every mutable lifecycle/lease fact is checked in the same
3853        // writer transaction before adapter I/O begins.
3854        let result = sqlx::query(
3855            "UPDATE mandate_mutation_attempts AS ma
3856             SET dispatch_claimed_at = ?
3857             WHERE ma.mandate_id = ? AND ma.mandate_version = ?
3858               AND ma.decision_cycle_id = ? AND ma.goal_run_id = ?
3859               AND ma.root_task_id = ? AND ma.root_task_attempt_id = ?
3860               AND ma.task_id = ? AND ma.task_attempt_id = ?
3861               AND ma.tool_call_id = ? AND ma.tool_name = ?
3862               AND ma.reserved_action_attempt = ? AND ma.action_digest = ?
3863               AND ma.status = 'reserved' AND ma.dispatch_claimed_at IS NULL
3864               AND EXISTS (
3865                   SELECT 1
3866                   FROM mandates m
3867                   JOIN goals g ON g.id = m.goal_id
3868                   JOIN goal_runs gr ON gr.id = ma.goal_run_id AND gr.goal_id = m.goal_id
3869                   JOIN mandate_decision_cycles dc
3870                     ON dc.id = ma.decision_cycle_id
3871                    AND dc.goal_run_id = gr.id
3872                    AND dc.mandate_id = m.id
3873                   JOIN intentions i
3874                     ON i.id = ma.intention_id
3875                    AND i.decision_cycle_id = dc.id
3876                    AND i.goal_run_id = gr.id
3877                    AND i.mandate_id = m.id
3878                   JOIN tasks root
3879                     ON root.id = ma.root_task_id AND root.goal_run_id = gr.id
3880                   JOIN task_attempts root_attempt
3881                     ON root_attempt.id = ma.root_task_attempt_id
3882                    AND root_attempt.task_id = root.id
3883                    AND root_attempt.goal_run_id = gr.id
3884                   JOIN tasks worker
3885                     ON worker.id = ma.task_id AND worker.goal_run_id = gr.id
3886                   JOIN task_attempts worker_attempt
3887                     ON worker_attempt.id = ma.task_attempt_id
3888                    AND worker_attempt.task_id = worker.id
3889                    AND worker_attempt.goal_run_id = gr.id
3890                   WHERE m.id = ma.mandate_id
3891                     AND m.owner_principal_id = ?
3892                     AND m.version = ma.mandate_version
3893                     AND m.status = 'active' AND m.confirmed_at IS NOT NULL
3894                     AND (m.expires_at IS NULL OR julianday(m.expires_at) > julianday(?))
3895                     AND g.status = 'active'
3896                     AND gr.trigger_type = 'mandate' AND gr.status = 'running'
3897                     AND gr.root_task_id = root.id AND root.id != worker.id
3898                     AND dc.mandate_version = m.version AND dc.outcome = 'act'
3899                     AND dc.action_attempts = ma.reserved_action_attempt
3900                     AND i.status = 'committed' AND i.completed_at IS NULL
3901                     AND root.status IN ('claimed', 'running')
3902                     AND root.current_attempt_id = root_attempt.id
3903                     AND root.error IS NULL AND root.blocker IS NULL
3904                     AND root_attempt.status IN ('claimed', 'running')
3905                     AND julianday(root_attempt.lease_expires_at) > julianday(?)
3906                     AND worker.status IN ('claimed', 'running')
3907                     AND worker.current_attempt_id = worker_attempt.id
3908                     AND worker.error IS NULL AND worker.blocker IS NULL
3909                     AND worker_attempt.status IN ('claimed', 'running')
3910                     AND julianday(worker_attempt.lease_expires_at) > julianday(?)
3911               )",
3912        )
3913        .bind(&claim.claimed_at)
3914        .bind(&claim.grant.mandate_id)
3915        .bind(claim.grant.mandate_version)
3916        .bind(&claim.grant.decision_cycle_id)
3917        .bind(&claim.goal_run_id)
3918        .bind(&claim.root_task_id)
3919        .bind(&claim.root_task_attempt_id)
3920        .bind(&claim.task_id)
3921        .bind(&claim.task_attempt_id)
3922        .bind(&claim.tool_call_id)
3923        .bind(&claim.tool_name)
3924        .bind(claim.grant.reserved_action_attempt)
3925        .bind(&claim.grant.action_digest)
3926        .bind(&claim.grant.owner_principal_id)
3927        .bind(&claim.claimed_at)
3928        .bind(&claim.claimed_at)
3929        .bind(&claim.claimed_at)
3930        .execute(self.work_pool())
3931        .await?;
3932        Ok(result.rows_affected() == 1)
3933    }
3934
3935    async fn get_mandate_mutation_quota_state(
3936        &self,
3937        mandate_id: &str,
3938        as_of: &str,
3939    ) -> anyhow::Result<Option<MandateMutationQuotaState>> {
3940        validate_canonical_identifier("mandate id", mandate_id, 256)?;
3941        let mut connection = self.work_pool().acquire().await?;
3942        mutation_quota_state_on_connection(&mut connection, mandate_id, as_of).await
3943    }
3944
3945    async fn list_mandate_mutation_attempts_for_run(
3946        &self,
3947        goal_run_id: &str,
3948    ) -> anyhow::Result<Vec<MandateMutationAttempt>> {
3949        validate_canonical_identifier("goal run id", goal_run_id, 256)?;
3950        let query = format!(
3951            "SELECT {MUTATION_ATTEMPT_COLUMNS} FROM mandate_mutation_attempts
3952             WHERE goal_run_id = ? ORDER BY julianday(reserved_at), id"
3953        );
3954        let rows = sqlx::query(sqlx::AssertSqlSafe(&*query))
3955            .bind(goal_run_id)
3956            .fetch_all(self.work_pool())
3957            .await?;
3958        rows.iter().map(mutation_attempt_from_row).collect()
3959    }
3960
3961    async fn finalize_mandate_run_from_proof(
3962        &self,
3963        request: &MandateRunFinalizationRequest,
3964    ) -> anyhow::Result<MandateRunFinalizationResult> {
3965        if validate_canonical_identifier("mandate id", &request.mandate_id, 256).is_err()
3966            || validate_canonical_identifier("goal run id", &request.goal_run_id, 256).is_err()
3967            || request.expected_mandate_version <= 0
3968            || validate_timestamp("mandate finalization timestamp", &request.finalized_at).is_err()
3969        {
3970            return Ok(MandateRunFinalizationResult::Rejected {
3971                reason: MandateFinalizationRejectReason::InvalidRequest,
3972            });
3973        }
3974
3975        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
3976        // Acquire SQLite's writer lock before reading the proof snapshot. All
3977        // subsequent task, ledger, policy, and lifecycle checks therefore
3978        // linearize with owner updates and worker finalization writes.
3979        let fenced = sqlx::query(
3980            "UPDATE goal_runs SET updated_at = updated_at
3981             WHERE id = ? AND trigger_type = 'mandate' AND status = 'running'",
3982        )
3983        .bind(&request.goal_run_id)
3984        .execute(&mut *tx)
3985        .await?;
3986        if fenced.rows_affected() != 1 {
3987            tx.rollback().await?;
3988            return Ok(MandateRunFinalizationResult::Stale {
3989                reason: MandateFinalizationStaleReason::RunNotCurrent,
3990            });
3991        }
3992
3993        let row = sqlx::query(
3994            "SELECT m.version AS mandate_version, m.status AS mandate_status,
3995                    m.min_review_secs AS min_review_secs,
3996                    m.max_review_secs AS max_review_secs,
3997                    g.session_id AS owner_session_id,
3998                    g.dispatch_failures AS review_failures,
3999                    gr.goal_id AS goal_id, gr.root_task_id AS root_task_id,
4000                    dc.id AS decision_cycle_id, dc.mandate_version AS decision_version,
4001                    dc.outcome AS decision_outcome, dc.origin AS decision_origin,
4002                    dc.action_attempts AS decision_action_attempts
4003             FROM goal_runs gr
4004             JOIN mandates m ON m.goal_id = gr.goal_id
4005             JOIN goals g ON g.id = gr.goal_id
4006             LEFT JOIN mandate_decision_cycles dc ON dc.goal_run_id = gr.id
4007             WHERE gr.id = ? AND m.id = ?",
4008        )
4009        .bind(&request.goal_run_id)
4010        .bind(&request.mandate_id)
4011        .fetch_optional(&mut *tx)
4012        .await?;
4013        let Some(row) = row else {
4014            tx.rollback().await?;
4015            return Ok(MandateRunFinalizationResult::Stale {
4016                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4017            });
4018        };
4019        let mandate_version: i64 = row.get("mandate_version");
4020        let min_review_secs: i64 = row.get("min_review_secs");
4021        let max_review_secs: i64 = row.get("max_review_secs");
4022        let review_failures: i32 = row.get("review_failures");
4023        let goal_id: String = row.get("goal_id");
4024        let owner_session_id: String = row.get("owner_session_id");
4025        if mandate_version != request.expected_mandate_version {
4026            tx.rollback().await?;
4027            return Ok(MandateRunFinalizationResult::Stale {
4028                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4029            });
4030        }
4031        let open_run_count: i64 = sqlx::query_scalar(
4032            "SELECT COUNT(*) FROM goal_runs
4033             WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')",
4034        )
4035        .bind(&goal_id)
4036        .fetch_one(&mut *tx)
4037        .await?;
4038        if open_run_count != 1 {
4039            tx.rollback().await?;
4040            return Ok(MandateRunFinalizationResult::Stale {
4041                reason: MandateFinalizationStaleReason::RunNotCurrent,
4042            });
4043        }
4044
4045        macro_rules! close_review_failed_retry {
4046            ($reason:expr) => {{
4047                let reason = $reason;
4048                let (intention_from, intention_to) =
4049                    intention_transition(IntentionStatus::Committed, IntentionStatus::Failed)?;
4050                sqlx::query(
4051                    "UPDATE intentions
4052                     SET status = ?, updated_at = ?, completed_at = ?
4053                     WHERE goal_run_id = ? AND status = ?",
4054                )
4055                .bind(intention_to)
4056                .bind(&request.finalized_at)
4057                .bind(&request.finalized_at)
4058                .bind(&request.goal_run_id)
4059                .bind(intention_from)
4060                .execute(&mut *tx)
4061                .await?;
4062                sqlx::query(
4063                    "UPDATE task_attempts
4064                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4065                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4066                )
4067                .bind(&request.finalized_at)
4068                .bind(&request.goal_run_id)
4069                .execute(&mut *tx)
4070                .await?;
4071                sqlx::query(
4072                    "UPDATE tasks
4073                     SET status = 'cancelled', current_attempt_id = NULL,
4074                         completed_at = COALESCE(completed_at, ?), updated_at = ?,
4075                         version = version + 1
4076                     WHERE goal_run_id = ?
4077                       AND status IN ('pending', 'claimed', 'running', 'blocked')",
4078                )
4079                .bind(&request.finalized_at)
4080                .bind(&request.finalized_at)
4081                .bind(&request.goal_run_id)
4082                .execute(&mut *tx)
4083                .await?;
4084                let run_updated = sqlx::query(
4085                    "UPDATE goal_runs
4086                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4087                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4088                )
4089                .bind(format!("mandate_review_failed:{}", reason.as_str()))
4090                .bind(&request.finalized_at)
4091                .bind(&request.finalized_at)
4092                .bind(&request.goal_run_id)
4093                .execute(&mut *tx)
4094                .await?;
4095                let finalized_at = chrono::DateTime::parse_from_rfc3339(&request.finalized_at)
4096                    .expect("validated mandate finalization timestamp")
4097                    .with_timezone(&chrono::Utc);
4098                let next_review_failures = review_failures.saturating_add(1);
4099                let backoff_shift = u32::try_from(next_review_failures.saturating_sub(1))
4100                    .unwrap_or(0)
4101                    .min(6);
4102                let retry_delay_secs = min_review_secs
4103                    .saturating_mul(1_i64 << backoff_shift)
4104                    .min(max_review_secs);
4105                let retry_at =
4106                    (finalized_at + chrono::Duration::seconds(retry_delay_secs)).to_rfc3339();
4107                let mandate_updated = sqlx::query(
4108                    "UPDATE mandates
4109                     SET next_review_at = ?, review_lease_token = NULL,
4110                         review_lease_expires_at = NULL, updated_at = ?
4111                     WHERE id = ? AND version = ? AND status = 'active'",
4112                )
4113                .bind(&retry_at)
4114                .bind(&request.finalized_at)
4115                .bind(&request.mandate_id)
4116                .bind(request.expected_mandate_version)
4117                .execute(&mut *tx)
4118                .await?;
4119                anyhow::ensure!(
4120                    run_updated.rows_affected() == 1 && mandate_updated.rows_affected() == 1,
4121                    "mandate review-failure retry state changed during finalization"
4122                );
4123                update_controller_status(
4124                    &mut tx,
4125                    &goal_id,
4126                    MandateStatus::Active,
4127                    &request.finalized_at,
4128                )
4129                .await?;
4130                sqlx::query(
4131                    "UPDATE goals SET dispatch_failures = ?, updated_at = ? WHERE id = ?",
4132                )
4133                .bind(next_review_failures)
4134                .bind(&request.finalized_at)
4135                .bind(&goal_id)
4136                .execute(&mut *tx)
4137                .await?;
4138                if crate::mandates::review_failure_is_notified(i64::from(next_review_failures)) {
4139                    let notice = crate::traits::MandateRunNotification::new(
4140                        &request.mandate_id,
4141                        request.expected_mandate_version,
4142                        &goal_id,
4143                        &request.goal_run_id,
4144                        &owner_session_id,
4145                        crate::traits::MandateRunNotificationKind::ReviewFailed { reason },
4146                        crate::traits::MandateRunProofCounts::default(),
4147                        &request.finalized_at,
4148                    );
4149                    super::notifications::enqueue_mandate_run_notification_on_connection(
4150                        &mut *tx,
4151                        &notice,
4152                    )
4153                    .await?;
4154                }
4155                tx.commit().await?;
4156                return Ok(MandateRunFinalizationResult::Rejected { reason });
4157            }};
4158        }
4159
4160        macro_rules! close_invalid_decision_state {
4161            () => {{
4162                let reason = MandateFinalizationRejectReason::InvalidDecisionState;
4163                sqlx::query(
4164                    "UPDATE mandate_mutation_attempts
4165                     SET status = CASE
4166                             WHEN dispatch_claimed_at IS NULL THEN 'never_dispatched'
4167                             ELSE 'ambiguous'
4168                         END,
4169                         completed_at = COALESCE(completed_at, ?)
4170                     WHERE goal_run_id = ? AND mandate_id = ? AND status = 'reserved'",
4171                )
4172                .bind(&request.finalized_at)
4173                .bind(&request.goal_run_id)
4174                .bind(&request.mandate_id)
4175                .execute(&mut *tx)
4176                .await?;
4177                sqlx::query(
4178                    "UPDATE task_attempts
4179                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4180                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4181                )
4182                .bind(&request.finalized_at)
4183                .bind(&request.goal_run_id)
4184                .execute(&mut *tx)
4185                .await?;
4186                sqlx::query(
4187                    "UPDATE tasks
4188                     SET status = 'cancelled', current_attempt_id = NULL,
4189                         completed_at = COALESCE(completed_at, ?), updated_at = ?,
4190                         version = version + 1
4191                     WHERE goal_run_id = ?
4192                       AND status IN ('pending', 'claimed', 'running', 'blocked')",
4193                )
4194                .bind(&request.finalized_at)
4195                .bind(&request.finalized_at)
4196                .bind(&request.goal_run_id)
4197                .execute(&mut *tx)
4198                .await?;
4199                let (intention_from, intention_to) = intention_transition(
4200                    IntentionStatus::Committed,
4201                    IntentionStatus::Suspended,
4202                )?;
4203                sqlx::query(
4204                    "UPDATE intentions
4205                     SET status = ?, updated_at = ?, completed_at = ?
4206                     WHERE goal_run_id = ? AND status = ?",
4207                )
4208                .bind(intention_to)
4209                .bind(&request.finalized_at)
4210                .bind(&request.finalized_at)
4211                .bind(&request.goal_run_id)
4212                .bind(intention_from)
4213                .execute(&mut *tx)
4214                .await?;
4215                let run_updated = sqlx::query(
4216                    "UPDATE goal_runs
4217                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4218                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4219                )
4220                .bind(format!("mandate_review_failed:{}", reason.as_str()))
4221                .bind(&request.finalized_at)
4222                .bind(&request.finalized_at)
4223                .bind(&request.goal_run_id)
4224                .execute(&mut *tx)
4225                .await?;
4226                let mut suspension = MandateSuspension::new(
4227                    MandateSuspensionKind::ReviewFailed,
4228                    Some(reason.as_str().to_string()),
4229                );
4230                suspension.goal_run_id = Some(request.goal_run_id.clone());
4231                let mandate_updated = sqlx::query(
4232                    "UPDATE mandates
4233                     SET status = 'awaiting_input', review_lease_token = NULL,
4234                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4235                     WHERE id = ? AND version = ? AND status = 'active'",
4236                )
4237                .bind(serde_json::to_string(&suspension)?)
4238                .bind(&request.finalized_at)
4239                .bind(&request.mandate_id)
4240                .bind(request.expected_mandate_version)
4241                .execute(&mut *tx)
4242                .await?;
4243                anyhow::ensure!(
4244                    run_updated.rows_affected() == 1 && mandate_updated.rows_affected() == 1,
4245                    "invalid mandate decision state changed during finalization"
4246                );
4247                update_controller_status(
4248                    &mut tx,
4249                    &goal_id,
4250                    MandateStatus::AwaitingInput,
4251                    &request.finalized_at,
4252                )
4253                .await?;
4254                let notice = crate::traits::MandateRunNotification::new(
4255                    &request.mandate_id,
4256                    request.expected_mandate_version,
4257                    &goal_id,
4258                    &request.goal_run_id,
4259                    &owner_session_id,
4260                    crate::traits::MandateRunNotificationKind::ReviewFailed { reason },
4261                    crate::traits::MandateRunProofCounts::default(),
4262                    &request.finalized_at,
4263                );
4264                super::notifications::enqueue_mandate_run_notification_on_connection(
4265                    &mut *tx,
4266                    &notice,
4267                )
4268                .await?;
4269                tx.commit().await?;
4270                return Ok(MandateRunFinalizationResult::Rejected { reason });
4271            }};
4272        }
4273        let decision_cycle_id: Option<String> = row.get("decision_cycle_id");
4274        let decision_version: Option<i64> = row.get("decision_version");
4275        let decision_outcome_raw: Option<String> = row.get("decision_outcome");
4276        let decision_origin = row
4277            .get::<Option<String>, _>("decision_origin")
4278            .as_deref()
4279            .and_then(MandateDecisionOrigin::parse);
4280        let decision_action_attempts: Option<i64> = row.get("decision_action_attempts");
4281        let (Some(decision_cycle_id), Some(decision_version), Some(decision_outcome_raw)) =
4282            (decision_cycle_id, decision_version, decision_outcome_raw)
4283        else {
4284            close_review_failed_retry!(MandateFinalizationRejectReason::DecisionMissing);
4285        };
4286        if decision_version != mandate_version {
4287            tx.rollback().await?;
4288            return Ok(MandateRunFinalizationResult::Stale {
4289                reason: MandateFinalizationStaleReason::DecisionVersionChanged,
4290            });
4291        }
4292        let Some(decision_outcome) = MandateDecisionOutcome::parse(&decision_outcome_raw) else {
4293            close_invalid_decision_state!();
4294        };
4295        if decision_origin == Some(MandateDecisionOrigin::RuntimeFallback) {
4296            close_review_failed_retry!(MandateFinalizationRejectReason::DeliberatorFailed);
4297        }
4298        let Some(decision_action_attempts) = decision_action_attempts else {
4299            close_invalid_decision_state!();
4300        };
4301        let mandate_status_raw: String = row.get("mandate_status");
4302        let Some(mandate_status) = MandateStatus::parse(&mandate_status_raw) else {
4303            close_invalid_decision_state!();
4304        };
4305        let expected_status = MandateStatus::Active;
4306        if mandate_status != expected_status {
4307            tx.rollback().await?;
4308            return Ok(MandateRunFinalizationResult::Stale {
4309                reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4310            });
4311        }
4312
4313        let root_task_id: Option<String> = row.get("root_task_id");
4314        let root_success = if let Some(root_task_id) = root_task_id.as_deref() {
4315            sqlx::query_scalar::<_, i64>(
4316                "SELECT COUNT(*) FROM tasks
4317                 WHERE id = ? AND goal_run_id = ? AND status = 'completed'
4318                   AND COALESCE(NULLIF(trim(error), ''), '') = ''
4319                   AND COALESCE(NULLIF(trim(blocker), ''), '') = ''",
4320            )
4321            .bind(root_task_id)
4322            .bind(&request.goal_run_id)
4323            .fetch_one(&mut *tx)
4324            .await?
4325                == 1
4326        } else {
4327            false
4328        };
4329
4330        // Before the task counts: a worker refused before dispatch did not do
4331        // its work, whatever status it closed with.
4332        let reserved_mutations: i64 = sqlx::query_scalar(
4333            "SELECT COUNT(*) FROM mandate_mutation_attempts
4334             WHERE goal_run_id = ? AND mandate_id = ?",
4335        )
4336        .bind(&request.goal_run_id)
4337        .bind(&request.mandate_id)
4338        .fetch_one(&mut *tx)
4339        .await?;
4340        let refused_by =
4341            if decision_outcome == MandateDecisionOutcome::Act && reserved_mutations == 0 {
4342                block_worker_refused_before_dispatch(
4343                    &mut tx,
4344                    &request.goal_run_id,
4345                    root_task_id.as_deref().unwrap_or(""),
4346                    &request.finalized_at,
4347                )
4348                .await?
4349            } else {
4350                None
4351            };
4352
4353        let task_counts = sqlx::query(
4354            "SELECT COUNT(*) AS total,
4355                    COALESCE(SUM(CASE WHEN status = 'completed'
4356                        AND COALESCE(NULLIF(trim(error), ''), '') = ''
4357                        AND COALESCE(NULLIF(trim(blocker), ''), '') = ''
4358                        THEN 1 ELSE 0 END), 0) AS completed,
4359                    COALESCE(SUM(CASE WHEN status IN ('failed', 'blocked', 'interrupted')
4360                        OR COALESCE(NULLIF(trim(error), ''), '') != ''
4361                        OR COALESCE(NULLIF(trim(blocker), ''), '') != ''
4362                        THEN 1 ELSE 0 END), 0) AS failed_or_blocked
4363             FROM tasks WHERE goal_run_id = ? AND id != ?",
4364        )
4365        .bind(&request.goal_run_id)
4366        .bind(root_task_id.as_deref().unwrap_or(""))
4367        .fetch_one(&mut *tx)
4368        .await?;
4369        let non_root_tasks: i64 = task_counts.get("total");
4370        let completed_tasks: i64 = task_counts.get("completed");
4371        let failed_or_blocked_tasks: i64 = task_counts.get("failed_or_blocked");
4372
4373        // Close any crash window between durable reservation, the one-use
4374        // final-dispatch claim, and strict receipt projection before proving
4375        // the run. Unclaimed rows prove no adapter I/O was authorized; claimed
4376        // rows without a receipt are necessarily ambiguous.
4377        sqlx::query(
4378            "UPDATE mandate_mutation_attempts
4379             SET status = CASE
4380                     WHEN dispatch_claimed_at IS NULL THEN 'never_dispatched'
4381                     ELSE 'ambiguous'
4382                 END,
4383                 completed_at = COALESCE(completed_at, ?)
4384             WHERE goal_run_id = ? AND mandate_id = ? AND status = 'reserved'",
4385        )
4386        .bind(&request.finalized_at)
4387        .bind(&request.goal_run_id)
4388        .bind(&request.mandate_id)
4389        .execute(&mut *tx)
4390        .await?;
4391
4392        let mutation_counts = sqlx::query(
4393            "SELECT COUNT(*) AS total,
4394                    COALESCE(SUM(CASE WHEN status = 'succeeded' THEN 1 ELSE 0 END), 0) AS succeeded,
4395                    COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) AS failed,
4396                    COALESCE(SUM(CASE WHEN status = 'never_dispatched' THEN 1 ELSE 0 END), 0)
4397                        AS never_dispatched,
4398                    COALESCE(SUM(CASE WHEN status = 'ambiguous' THEN 1 ELSE 0 END), 0)
4399                        AS ambiguous,
4400                    COALESCE(SUM(CASE WHEN mandate_version != ? OR decision_cycle_id != ?
4401                        THEN 1 ELSE 0 END), 0) AS mismatched
4402             FROM mandate_mutation_attempts
4403             WHERE goal_run_id = ? AND mandate_id = ?",
4404        )
4405        .bind(mandate_version)
4406        .bind(&decision_cycle_id)
4407        .bind(&request.goal_run_id)
4408        .bind(&request.mandate_id)
4409        .fetch_one(&mut *tx)
4410        .await?;
4411        let mutation_total: i64 = mutation_counts.get("total");
4412        let mutation_succeeded: i64 = mutation_counts.get("succeeded");
4413        let mutation_failed: i64 = mutation_counts.get("failed");
4414        let mutation_never_dispatched: i64 = mutation_counts.get("never_dispatched");
4415        let mutation_ambiguous: i64 = mutation_counts.get("ambiguous");
4416        let mutation_mismatched: i64 = mutation_counts.get("mismatched");
4417        let count = |value: i64| u32::try_from(value.max(0)).unwrap_or(u32::MAX);
4418        let counts = MandateRunProofCounts {
4419            non_root_tasks: count(non_root_tasks),
4420            completed_tasks: count(completed_tasks),
4421            incomplete_tasks: count(non_root_tasks.saturating_sub(completed_tasks)),
4422            failed_or_blocked_tasks: count(failed_or_blocked_tasks),
4423            mutation_reservations: count(mutation_total),
4424            succeeded_mutations: count(mutation_succeeded),
4425            failed_mutations: count(mutation_failed),
4426            never_dispatched_mutations: count(mutation_never_dispatched),
4427            ambiguous_or_reserved_mutations: count(mutation_ambiguous),
4428        };
4429        macro_rules! reconcile_fail_closed {
4430            ($reason:expr) => {{
4431                let reason = $reason;
4432                sqlx::query(
4433                    "UPDATE task_attempts
4434                     SET status = 'cancelled', completed_at = COALESCE(completed_at, ?)
4435                     WHERE goal_run_id = ? AND status IN ('claimed', 'running')",
4436                )
4437                .bind(&request.finalized_at)
4438                .bind(&request.goal_run_id)
4439                .execute(&mut *tx)
4440                .await?;
4441                sqlx::query(
4442                    "UPDATE tasks
4443                     SET status = 'cancelled', current_attempt_id = NULL,
4444                         completed_at = COALESCE(completed_at, ?), updated_at = ?, version = version + 1
4445                     WHERE goal_run_id = ? AND status IN ('pending', 'claimed', 'running')",
4446                )
4447                .bind(&request.finalized_at)
4448                .bind(&request.finalized_at)
4449                .bind(&request.goal_run_id)
4450                .execute(&mut *tx)
4451                .await?;
4452                let (intention_from, intention_to) = intention_transition(
4453                    IntentionStatus::Committed,
4454                    IntentionStatus::Suspended,
4455                )?;
4456                sqlx::query(
4457                    "UPDATE intentions
4458                     SET status = ?, updated_at = ?, completed_at = ?
4459                     WHERE goal_run_id = ? AND status = ?",
4460                )
4461                .bind(intention_to)
4462                .bind(&request.finalized_at)
4463                .bind(&request.finalized_at)
4464                .bind(&request.goal_run_id)
4465                .bind(intention_from)
4466                .execute(&mut *tx)
4467                .await?;
4468                let run_updated = sqlx::query(
4469                    "UPDATE goal_runs
4470                     SET status = 'failed', outcome_summary = ?, completed_at = ?, updated_at = ?
4471                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4472                )
4473                .bind(format!("mandate_reconciliation_required:{}", reason.as_str()))
4474                .bind(&request.finalized_at)
4475                .bind(&request.finalized_at)
4476                .bind(&request.goal_run_id)
4477                .execute(&mut *tx)
4478                .await?;
4479                let mut suspension = MandateSuspension::new(
4480                    MandateSuspensionKind::ReconciliationRequired,
4481                    Some(reason.as_str().to_string()),
4482                );
4483                suspension.decision_cycle_id = Some(decision_cycle_id.clone());
4484                suspension.goal_run_id = Some(request.goal_run_id.clone());
4485                let mandate_updated = sqlx::query(
4486                    "UPDATE mandates
4487                     SET status = 'awaiting_input', review_lease_token = NULL,
4488                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4489                     WHERE id = ? AND version = ? AND status = ?",
4490                )
4491                .bind(serde_json::to_string(&suspension)?)
4492                .bind(&request.finalized_at)
4493                .bind(&request.mandate_id)
4494                .bind(request.expected_mandate_version)
4495                .bind(expected_status.as_str())
4496                .execute(&mut *tx)
4497                .await?;
4498                if run_updated.rows_affected() != 1 || mandate_updated.rows_affected() != 1 {
4499                    tx.rollback().await?;
4500                    return Ok(MandateRunFinalizationResult::Stale {
4501                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4502                    });
4503                }
4504                update_controller_status(
4505                    &mut tx,
4506                    &goal_id,
4507                    MandateStatus::AwaitingInput,
4508                    &request.finalized_at,
4509                )
4510                .await?;
4511                let notice = crate::traits::MandateRunNotification::new(
4512                    &request.mandate_id,
4513                    request.expected_mandate_version,
4514                    &goal_id,
4515                    &request.goal_run_id,
4516                    &owner_session_id,
4517                    crate::traits::MandateRunNotificationKind::ReconciliationRequired { reason },
4518                    counts.clone(),
4519                    &request.finalized_at,
4520                );
4521                super::notifications::enqueue_mandate_run_notification_on_connection(
4522                    &mut *tx,
4523                    &notice,
4524                )
4525                .await?;
4526                tx.commit().await?;
4527                return Ok(MandateRunFinalizationResult::ReconciliationRequired {
4528                    reason,
4529                    counts: counts.clone(),
4530                });
4531            }};
4532        }
4533        if let Some(gate) = refused_by {
4534            reconcile_fail_closed!(MandateReconciliationReason::ActBlockedBeforeDispatch { gate });
4535        }
4536        // Every external effect of an ACT goes through a mutation
4537        // reservation. When none succeeded, none has an unknown outcome and
4538        // none belongs to another decision, the ledger proves the review
4539        // changed nothing: retry it rather than ask the owner to confirm
4540        // what is already known.
4541        if decision_outcome == MandateDecisionOutcome::Act
4542            && mutation_succeeded == 0
4543            && mutation_ambiguous == 0
4544            && mutation_mismatched == 0
4545        {
4546            close_review_failed_retry!(MandateFinalizationRejectReason::ActChangedNothing);
4547        }
4548        if !root_success {
4549            reconcile_fail_closed!(MandateReconciliationReason::RootTaskNotSuccessful);
4550        }
4551
4552        match decision_outcome {
4553            MandateDecisionOutcome::Act => {
4554                let intention_id = sqlx::query_scalar::<_, String>(
4555                    "SELECT id FROM intentions
4556                     WHERE mandate_id = ? AND decision_cycle_id = ? AND goal_run_id = ?
4557                       AND status = 'committed' AND completed_at IS NULL",
4558                )
4559                .bind(&request.mandate_id)
4560                .bind(&decision_cycle_id)
4561                .bind(&request.goal_run_id)
4562                .fetch_optional(&mut *tx)
4563                .await?;
4564                let Some(intention_id) = intention_id else {
4565                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingIntention);
4566                };
4567                if non_root_tasks == 0 {
4568                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingWorkTask);
4569                }
4570                if completed_tasks != non_root_tasks || failed_or_blocked_tasks > 0 {
4571                    reconcile_fail_closed!(MandateReconciliationReason::WorkTasksIncomplete);
4572                }
4573                if mutation_mismatched > 0 || decision_action_attempts != mutation_total {
4574                    reconcile_fail_closed!(MandateReconciliationReason::ActionLedgerMismatch);
4575                }
4576                if mutation_failed > 0 {
4577                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeFailed);
4578                }
4579                if mutation_never_dispatched > 0 {
4580                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeFailed);
4581                }
4582                if mutation_ambiguous > 0 {
4583                    reconcile_fail_closed!(MandateReconciliationReason::MutationOutcomeAmbiguous);
4584                }
4585                if mutation_succeeded == 0 {
4586                    reconcile_fail_closed!(MandateReconciliationReason::ActMissingVerifiedMutation);
4587                }
4588                let (intention_from, intention_to) =
4589                    intention_transition(IntentionStatus::Committed, IntentionStatus::Satisfied)?;
4590                let intention_updated = sqlx::query(
4591                    "UPDATE intentions SET status = ?, updated_at = ?, completed_at = ?
4592                     WHERE id = ? AND status = ? AND completed_at IS NULL",
4593                )
4594                .bind(intention_to)
4595                .bind(&request.finalized_at)
4596                .bind(&request.finalized_at)
4597                .bind(&intention_id)
4598                .bind(intention_from)
4599                .execute(&mut *tx)
4600                .await?;
4601                if intention_updated.rows_affected() != 1 {
4602                    tx.rollback().await?;
4603                    return Ok(MandateRunFinalizationResult::Stale {
4604                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4605                    });
4606                }
4607                let run_updated = sqlx::query(
4608                    "UPDATE goal_runs
4609                     SET status = 'completed', outcome_summary = 'mandate_act_satisfied',
4610                         completed_at = ?, updated_at = ?
4611                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4612                )
4613                .bind(&request.finalized_at)
4614                .bind(&request.finalized_at)
4615                .bind(&request.goal_run_id)
4616                .execute(&mut *tx)
4617                .await?;
4618                if run_updated.rows_affected() != 1 {
4619                    tx.rollback().await?;
4620                    return Ok(MandateRunFinalizationResult::Stale {
4621                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4622                    });
4623                }
4624                let notice = crate::traits::MandateRunNotification::new(
4625                    &request.mandate_id,
4626                    request.expected_mandate_version,
4627                    &goal_id,
4628                    &request.goal_run_id,
4629                    &owner_session_id,
4630                    crate::traits::MandateRunNotificationKind::ActSatisfied,
4631                    counts.clone(),
4632                    &request.finalized_at,
4633                );
4634                super::notifications::enqueue_mandate_run_notification_on_connection(
4635                    &mut tx, &notice,
4636                )
4637                .await?;
4638                sqlx::query("UPDATE goals SET dispatch_failures = 0, updated_at = ? WHERE id = ?")
4639                    .bind(&request.finalized_at)
4640                    .bind(&goal_id)
4641                    .execute(&mut *tx)
4642                    .await?;
4643                tx.commit().await?;
4644                Ok(MandateRunFinalizationResult::ActSatisfied { counts })
4645            }
4646            MandateDecisionOutcome::Wait
4647            | MandateDecisionOutcome::Ask
4648            | MandateDecisionOutcome::Stop => {
4649                if non_root_tasks != 0 {
4650                    reconcile_fail_closed!(MandateReconciliationReason::NonActionCreatedWork);
4651                }
4652                if mutation_total != 0 || decision_action_attempts != 0 {
4653                    reconcile_fail_closed!(MandateReconciliationReason::NonActionReservedMutation);
4654                }
4655                let intention_count: i64 = sqlx::query_scalar(
4656                    "SELECT COUNT(*) FROM intentions
4657                     WHERE mandate_id = ? AND decision_cycle_id = ? AND goal_run_id = ?",
4658                )
4659                .bind(&request.mandate_id)
4660                .bind(&decision_cycle_id)
4661                .bind(&request.goal_run_id)
4662                .fetch_one(&mut *tx)
4663                .await?;
4664                if intention_count != 0 {
4665                    close_invalid_decision_state!();
4666                }
4667                let final_mandate_status = match decision_outcome {
4668                    MandateDecisionOutcome::Wait => MandateStatus::Active,
4669                    MandateDecisionOutcome::Ask => MandateStatus::AwaitingInput,
4670                    MandateDecisionOutcome::Stop => MandateStatus::Completed,
4671                    MandateDecisionOutcome::Act => unreachable!(),
4672                };
4673                let suspension = (decision_outcome == MandateDecisionOutcome::Ask).then(|| {
4674                    let mut value = MandateSuspension::new(
4675                        MandateSuspensionKind::AwaitingAnswer,
4676                        Some("agent_question".to_string()),
4677                    );
4678                    value.decision_cycle_id = Some(decision_cycle_id.clone());
4679                    value.goal_run_id = Some(request.goal_run_id.clone());
4680                    value
4681                });
4682                let mandate_updated = sqlx::query(
4683                    "UPDATE mandates
4684                     SET status = ?, review_lease_token = NULL,
4685                         review_lease_expires_at = NULL, suspension_json = ?, updated_at = ?
4686                     WHERE id = ? AND version = ? AND status = 'active'",
4687                )
4688                .bind(final_mandate_status.as_str())
4689                .bind(suspension.as_ref().map(serde_json::to_string).transpose()?)
4690                .bind(&request.finalized_at)
4691                .bind(&request.mandate_id)
4692                .bind(request.expected_mandate_version)
4693                .execute(&mut *tx)
4694                .await?;
4695                if mandate_updated.rows_affected() != 1 {
4696                    tx.rollback().await?;
4697                    return Ok(MandateRunFinalizationResult::Stale {
4698                        reason: MandateFinalizationStaleReason::MandateMissingOrVersionChanged,
4699                    });
4700                }
4701                update_controller_status(
4702                    &mut tx,
4703                    &goal_id,
4704                    final_mandate_status,
4705                    &request.finalized_at,
4706                )
4707                .await?;
4708                sqlx::query("UPDATE goals SET dispatch_failures = 0, updated_at = ? WHERE id = ?")
4709                    .bind(&request.finalized_at)
4710                    .bind(&goal_id)
4711                    .execute(&mut *tx)
4712                    .await?;
4713                let run_updated = sqlx::query(
4714                    "UPDATE goal_runs
4715                     SET status = 'completed', outcome_summary = 'mandate_non_action_satisfied',
4716                         completed_at = ?, updated_at = ?
4717                     WHERE id = ? AND status = 'running' AND trigger_type = 'mandate'",
4718                )
4719                .bind(&request.finalized_at)
4720                .bind(&request.finalized_at)
4721                .bind(&request.goal_run_id)
4722                .execute(&mut *tx)
4723                .await?;
4724                if run_updated.rows_affected() != 1 {
4725                    tx.rollback().await?;
4726                    return Ok(MandateRunFinalizationResult::Stale {
4727                        reason: MandateFinalizationStaleReason::RunNotCurrent,
4728                    });
4729                }
4730                let owner_alert = if decision_outcome == MandateDecisionOutcome::Wait {
4731                    sqlx::query_scalar::<_, Option<String>>(
4732                        "SELECT owner_alert FROM mandate_decision_cycles WHERE id = ?",
4733                    )
4734                    .bind(&decision_cycle_id)
4735                    .fetch_optional(&mut *tx)
4736                    .await?
4737                    .flatten()
4738                } else {
4739                    None
4740                };
4741                if let Some(kind) = match decision_outcome {
4742                    MandateDecisionOutcome::Wait => owner_alert
4743                        .is_some()
4744                        .then_some(crate::traits::MandateRunNotificationKind::Alert),
4745                    MandateDecisionOutcome::Ask => {
4746                        Some(crate::traits::MandateRunNotificationKind::Ask)
4747                    }
4748                    MandateDecisionOutcome::Stop => {
4749                        Some(crate::traits::MandateRunNotificationKind::Stopped)
4750                    }
4751                    MandateDecisionOutcome::Act => unreachable!(),
4752                } {
4753                    let question = if decision_outcome == MandateDecisionOutcome::Ask {
4754                        sqlx::query_scalar::<_, Option<String>>(
4755                            "SELECT question FROM mandate_decision_cycles WHERE id = ?",
4756                        )
4757                        .bind(&decision_cycle_id)
4758                        .fetch_optional(&mut *tx)
4759                        .await?
4760                        .flatten()
4761                    } else {
4762                        None
4763                    };
4764                    let notice = crate::traits::MandateRunNotification::new(
4765                        &request.mandate_id,
4766                        request.expected_mandate_version,
4767                        &goal_id,
4768                        &request.goal_run_id,
4769                        &owner_session_id,
4770                        kind,
4771                        counts.clone(),
4772                        &request.finalized_at,
4773                    )
4774                    .with_owner_question(question.as_deref())
4775                    .with_owner_alert(owner_alert.as_deref());
4776                    super::notifications::enqueue_mandate_run_notification_on_connection(
4777                        &mut tx, &notice,
4778                    )
4779                    .await?;
4780                }
4781                tx.commit().await?;
4782                Ok(MandateRunFinalizationResult::NonActionSatisfied {
4783                    outcome: decision_outcome,
4784                    counts,
4785                })
4786            }
4787        }
4788    }
4789}
4790
4791#[cfg(test)]
4792mod tests {
4793    use super::*;
4794    use crate::traits::*;
4795    use crate::traits::{
4796        Goal, Intention, Mandate, MandateAuthority, MandateDecisionCycle, MandateMutationTarget,
4797        MandateObjectiveControl, MandateOperationKind, MandateOperationScope,
4798        MandateWakeSignalKind, ObjectiveMetricDirection, Task, ToolCallOperation,
4799    };
4800    use std::sync::Arc;
4801
4802    async fn test_store() -> (SqliteWorkStore, tempfile::NamedTempFile) {
4803        let database = tempfile::NamedTempFile::new().unwrap();
4804        let store = open_for_tests(database.path().to_str().unwrap()).await;
4805        (store, database)
4806    }
4807
4808    fn authority(max_actions: u32) -> MandateAuthority {
4809        MandateAuthority {
4810            allowed_tools: vec!["http_request".to_string()],
4811            allowed_mutation_effects: vec!["external_delivery".to_string()],
4812            allowed_target_prefixes: vec!["https://api.x.com/2/".to_string()],
4813            max_mutating_actions_per_cycle: max_actions,
4814            max_mutating_actions_per_rolling_24h: if max_actions == 0 { 0 } else { 24 },
4815            min_seconds_between_mutations: if max_actions == 0 { 0 } else { 900 },
4816            ..MandateAuthority::default()
4817        }
4818    }
4819
4820    fn controller(session_id: &str, max_actions: u32) -> (Goal, Mandate) {
4821        let goal = Goal::new_continuous(
4822            "Steward the account",
4823            session_id,
4824            Some(10_000),
4825            Some(50_000),
4826        );
4827        let mut mandate = Mandate::new(
4828            &goal.id,
4829            None,
4830            "Maintain a useful, authentic account presence",
4831            session_id,
4832            authority(max_actions),
4833            60,
4834            3_600,
4835            300,
4836        );
4837        mandate.next_review_at = (chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339();
4838        (goal, mandate)
4839    }
4840
4841    /// A database whose `mandates` table predates the owner-given name
4842    /// gains the nullable column on the next migration; old rows read back
4843    /// unnamed and new ones keep their name.
4844    #[tokio::test]
4845    async fn an_existing_mandates_table_gains_the_name_column() {
4846        let (store, _database) = test_store().await;
4847        let pool = store.pool();
4848        let (old_goal, old_mandate) = controller("owner-session", 0);
4849        store
4850            .create_mandate_controller(&old_goal, &old_mandate)
4851            .await
4852            .unwrap();
4853        sqlx::query("ALTER TABLE mandates DROP COLUMN name")
4854            .execute(&pool)
4855            .await
4856            .unwrap();
4857
4858        crate::schema::migrate_work_tables(&pool, |_| false)
4859            .await
4860            .unwrap();
4861
4862        let unnamed = store.get_mandate(&old_mandate.id).await.unwrap().unwrap();
4863        assert_eq!(unnamed.name, None);
4864        let (goal, mut mandate) = controller("owner-session", 0);
4865        mandate.name = Some("synthetic-watch".to_string());
4866        store
4867            .create_mandate_controller(&goal, &mandate)
4868            .await
4869            .unwrap();
4870        let named = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4871        assert_eq!(named.name.as_deref(), Some("synthetic-watch"));
4872        assert!(named.has_name("Synthetic-Watch"));
4873    }
4874
4875    fn objective_control() -> MandateObjectiveControl {
4876        MandateObjectiveControl {
4877            schema_version: MandateObjectiveControl::SCHEMA_VERSION,
4878            metric_name: "synthetic useful interactions".to_string(),
4879            unit: "count".to_string(),
4880            baseline_micros: 10_000_000,
4881            target_micros: 20_000_000,
4882            direction: ObjectiveMetricDirection::AtLeast,
4883            measurement_source: "metric_source:synthetic-analytics".to_string(),
4884            measurement_cadence_secs: 3_600,
4885            baseline_observed_at: chrono::Utc::now().to_rfc3339(),
4886        }
4887    }
4888
4889    #[tokio::test]
4890    async fn autopilot_without_a_measured_objective_stays_active_and_due() {
4891        let (store, _database) = test_store().await;
4892        let (goal, mut mandate) = controller("owner-session", 0);
4893        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
4894        store
4895            .create_mandate_controller(&goal, &mandate)
4896            .await
4897            .unwrap();
4898
4899        let claimed = store
4900            .claim_due_mandates(10, "synthetic-heartbeat", 300)
4901            .await
4902            .unwrap();
4903        assert_eq!(claimed.len(), 1);
4904        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4905        assert_eq!(current.status, MandateStatus::Active);
4906        assert!(current.objective_control.is_none());
4907        assert!(current.suspension.is_none());
4908    }
4909
4910    #[tokio::test]
4911    async fn structured_signal_wakes_only_matching_autopilot_once() {
4912        let (store, _database) = test_store().await;
4913        let (goal, mut mandate) = controller("owner-session", 0);
4914        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
4915        mandate.objective_control = Some(objective_control());
4916        mandate.authority = MandateAuthority::from_operation_scopes(
4917            true,
4918            vec![MandateOperationScope {
4919                tool: "http_request".to_string(),
4920                operation: ToolCallOperation::Get,
4921                kind: MandateOperationKind::Observation,
4922                target_prefixes: vec![
4923                    "https://api.example.test/v1/mentions".to_string(),
4924                    "auth_profile:synthetic-social".to_string(),
4925                    "account:synthetic-1".to_string(),
4926                ],
4927                allowed_query_params: vec!["since_id".to_string()],
4928                mutation_effects: Vec::new(),
4929            }],
4930            0,
4931            0,
4932            0,
4933        );
4934        mandate.next_review_at = (chrono::Utc::now() + chrono::Duration::hours(3)).to_rfc3339();
4935        store
4936            .create_mandate_controller(&goal, &mandate)
4937            .await
4938            .unwrap();
4939        let signal = MandateWakeSignal {
4940            kind: MandateWakeSignalKind::Mention,
4941            source: "synthetic_social".to_string(),
4942            target_url: "https://api.example.test/v1/mentions?since_id=42".to_string(),
4943            account_id: Some("account:synthetic-1".to_string()),
4944            dedupe_key: "mention:42".to_string(),
4945            occurred_at: chrono::Utc::now().to_rfc3339(),
4946        };
4947
4948        assert_eq!(
4949            store.wake_mandates_for_signal(&signal).await.unwrap(),
4950            vec![mandate.id.clone()]
4951        );
4952        let awakened = store.get_mandate(&mandate.id).await.unwrap().unwrap();
4953        assert!(
4954            chrono::DateTime::parse_from_rfc3339(&awakened.next_review_at).unwrap()
4955                <= chrono::Utc::now() + chrono::Duration::seconds(1)
4956        );
4957        assert!(
4958            store
4959                .wake_mandates_for_signal(&signal)
4960                .await
4961                .unwrap()
4962                .is_empty()
4963        );
4964
4965        let mut wrong_account = signal;
4966        wrong_account.dedupe_key = "mention:43".to_string();
4967        wrong_account.account_id = Some("account:synthetic-2".to_string());
4968        assert!(
4969            store
4970                .wake_mandates_for_signal(&wrong_account)
4971                .await
4972                .unwrap()
4973                .is_empty()
4974        );
4975    }
4976
4977    fn review_root(goal: &Goal, run_id: &str, task_id: &str) -> Task {
4978        Task {
4979            id: task_id.to_string(),
4980            goal_id: goal.id.clone(),
4981            description: format!("Mandate review: test controller for goal run {run_id}"),
4982            status: "pending".to_string(),
4983            priority: goal.priority.clone(),
4984            task_order: 0,
4985            parallel_group: None,
4986            depends_on: None,
4987            agent_id: None,
4988            context: None,
4989            result: None,
4990            error: None,
4991            blocker: None,
4992            idempotent: false,
4993            retry_count: 0,
4994            max_retries: 0,
4995            created_at: chrono::Utc::now().to_rfc3339(),
4996            started_at: None,
4997            completed_at: None,
4998        }
4999    }
5000
5001    async fn claim_and_start_run(
5002        store: &SqliteWorkStore,
5003        goal: &Goal,
5004        mandate: &Mandate,
5005    ) -> crate::traits::GoalRun {
5006        store
5007            .create_mandate_controller(goal, mandate)
5008            .await
5009            .unwrap();
5010        let claimed = store
5011            .claim_due_mandates(1, "test-heartbeat", 300)
5012            .await
5013            .unwrap();
5014        assert_eq!(claimed.len(), 1);
5015        let root_task_id = uuid::Uuid::new_v4().to_string();
5016        let run = store
5017            .start_goal_run(&goal.id, "mandate", None, Some(&root_task_id))
5018            .await
5019            .unwrap();
5020        store
5021            .create_task(&review_root(goal, &run.id, &root_task_id))
5022            .await
5023            .unwrap();
5024        // Goal runs now remain pending until a worker claim transitions them.
5025        // These storage tests exercise post-claim mandate invariants without a
5026        // task worker, so model that already-claimed state explicitly.
5027        sqlx::query("UPDATE goal_runs SET status = 'running' WHERE id = ?")
5028            .bind(&run.id)
5029            .execute(&store.pool)
5030            .await
5031            .unwrap();
5032        run
5033    }
5034
5035    struct MutationFence {
5036        root_attempt: crate::traits::TaskAttempt,
5037        worker_task: Task,
5038        worker_attempt: crate::traits::TaskAttempt,
5039    }
5040
5041    async fn claim_mutation_fence(
5042        store: &SqliteWorkStore,
5043        goal: &Goal,
5044        mandate: &Mandate,
5045        run: &GoalRun,
5046    ) -> MutationFence {
5047        let root_task_id = run.root_task_id.as_deref().unwrap();
5048        let root_attempt = store
5049            .claim_task_with_lease(
5050                root_task_id,
5051                "root-worker",
5052                Some("profile-task-lead"),
5053                7_200,
5054            )
5055            .await
5056            .unwrap()
5057            .unwrap();
5058        let worker_task_id = uuid::Uuid::new_v4().to_string();
5059        let mut worker_task = review_root(goal, &run.id, &worker_task_id);
5060        worker_task.description = "Perform one governed HTTP mutation".to_string();
5061        worker_task.task_order = 1;
5062        assert!(
5063            store
5064                .create_mandate_task_from_attempt(
5065                    &worker_task,
5066                    &mandate.id,
5067                    mandate.version,
5068                    &run.id,
5069                    &root_attempt.id,
5070                    16,
5071                )
5072                .await
5073                .unwrap()
5074        );
5075        let worker_attempt = store
5076            .claim_mandate_task_from_attempt(
5077                &worker_task_id,
5078                "executor-worker",
5079                &mandate.id,
5080                mandate.version,
5081                &run.id,
5082                &root_attempt.id,
5083                7_200,
5084            )
5085            .await
5086            .unwrap()
5087            .unwrap();
5088        MutationFence {
5089            root_attempt,
5090            worker_task,
5091            worker_attempt,
5092        }
5093    }
5094
5095    fn reservation(
5096        mandate: &Mandate,
5097        decision: &MandateDecisionCycle,
5098        run: &GoalRun,
5099        fence: &MutationFence,
5100        reserved_action_attempt: i64,
5101        sequence: u64,
5102        reserved_at: chrono::DateTime<chrono::Utc>,
5103    ) -> MandateMutationReservation {
5104        MandateMutationReservation {
5105            grant: crate::traits::MandateAuthorityGrant {
5106                mandate_id: mandate.id.clone(),
5107                mandate_version: mandate.version,
5108                owner_principal_id: mandate.owner_principal_id.clone(),
5109                decision_cycle_id: decision.id.clone(),
5110                action_digest: format!("{sequence:064x}"),
5111                counts_toward_cycle_budget: true,
5112                reserved_action_attempt,
5113                tool_call_id: Some(format!("tool-call-{sequence}")),
5114            },
5115            goal_run_id: run.id.clone(),
5116            root_task_id: run.root_task_id.clone().unwrap(),
5117            root_task_attempt_id: fence.root_attempt.id.clone(),
5118            task_id: fence.worker_task.id.clone(),
5119            task_attempt_id: fence.worker_attempt.id.clone(),
5120            tool_call_id: format!("tool-call-{sequence}"),
5121            tool_name: "http_request".to_string(),
5122            mutation_effects: vec!["external_delivery".to_string()],
5123            targets: vec![MandateMutationTarget {
5124                kind: "url".to_string(),
5125                identifier: "https://api.x.com/2/tweets".to_string(),
5126            }],
5127            account_identifiers: Vec::new(),
5128            reserved_at: reserved_at.to_rfc3339(),
5129        }
5130    }
5131
5132    fn dispatch_claim(
5133        reservation: &MandateMutationReservation,
5134        claimed_at: chrono::DateTime<chrono::Utc>,
5135    ) -> MandateMutationDispatchClaim {
5136        MandateMutationDispatchClaim {
5137            grant: reservation.grant.clone(),
5138            goal_run_id: reservation.goal_run_id.clone(),
5139            root_task_id: reservation.root_task_id.clone(),
5140            root_task_attempt_id: reservation.root_task_attempt_id.clone(),
5141            task_id: reservation.task_id.clone(),
5142            task_attempt_id: reservation.task_attempt_id.clone(),
5143            tool_call_id: reservation.tool_call_id.clone(),
5144            tool_name: reservation.tool_name.clone(),
5145            claimed_at: claimed_at.to_rfc3339(),
5146        }
5147    }
5148
5149    async fn complete_mutation_fence(store: &SqliteWorkStore, fence: &MutationFence) {
5150        let complete = crate::traits::TaskAttemptPatch {
5151            status: "completed".to_string(),
5152            result: Some("verified".to_string()),
5153            ..Default::default()
5154        };
5155        assert!(
5156            store
5157                .patch_task_from_attempt(
5158                    &fence.worker_attempt.id,
5159                    &fence.worker_attempt.lease_token,
5160                    &complete,
5161                )
5162                .await
5163                .unwrap()
5164        );
5165        assert!(
5166            store
5167                .patch_task_from_attempt(
5168                    &fence.root_attempt.id,
5169                    &fence.root_attempt.lease_token,
5170                    &complete,
5171                )
5172                .await
5173                .unwrap()
5174        );
5175    }
5176
5177    #[tokio::test]
5178    async fn controller_and_mandate_are_created_atomically() {
5179        let (store, _database) = test_store().await;
5180        let (goal, mandate) = controller("owner-session", 2);
5181        store
5182            .create_mandate_controller(&goal, &mandate)
5183            .await
5184            .unwrap();
5185
5186        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5187        assert_eq!(loaded.goal_id, goal.id);
5188        assert_eq!(loaded.version, 1);
5189        assert!(loaded.review_lease_token.is_none());
5190        assert!(store.get_goal(&goal.id).await.unwrap().is_some());
5191        let channel_links: i64 = sqlx::query_scalar(
5192            "SELECT COUNT(*) FROM work_channel_links WHERE goal_id = ? AND channel_session_id = ?",
5193        )
5194        .bind(&goal.id)
5195        .bind(&goal.session_id)
5196        .fetch_one(&store.pool)
5197        .await
5198        .unwrap();
5199        assert_eq!(channel_links, 1);
5200
5201        let pending_goal = Goal::new_continuous_pending(
5202            "Mandate awaiting confirmation",
5203            "owner-session",
5204            None,
5205            None,
5206        );
5207        let mut pending_mandate = Mandate::new(
5208            &pending_goal.id,
5209            None,
5210            "Await explicit owner confirmation",
5211            "owner-session",
5212            authority(0),
5213            60,
5214            3_600,
5215            300,
5216        );
5217        pending_mandate.status = MandateStatus::Paused;
5218        pending_mandate.confirmed_at = None;
5219        store
5220            .create_mandate_controller(&pending_goal, &pending_mandate)
5221            .await
5222            .unwrap();
5223        assert_eq!(
5224            store
5225                .get_goal(&pending_goal.id)
5226                .await
5227                .unwrap()
5228                .unwrap()
5229                .status,
5230            "pending_confirmation"
5231        );
5232        assert_eq!(
5233            store
5234                .get_mandate(&pending_mandate.id)
5235                .await
5236                .unwrap()
5237                .unwrap()
5238                .status,
5239            MandateStatus::Paused
5240        );
5241
5242        let (bad_goal, mut bad_mandate) = controller("owner-session", 2);
5243        bad_mandate.source_goal_id = Some("missing-personal-goal".to_string());
5244        assert!(
5245            store
5246                .create_mandate_controller(&bad_goal, &bad_mandate)
5247                .await
5248                .is_err()
5249        );
5250        assert!(store.get_goal(&bad_goal.id).await.unwrap().is_none());
5251
5252        let same_owner_source = Goal::new_personal("Grow an audience", "owner-session");
5253        store.create_goal(&same_owner_source).await.unwrap();
5254        let (linked_goal, mut linked_mandate) = controller("owner-session", 2);
5255        linked_mandate.source_goal_id = Some(same_owner_source.id);
5256        store
5257            .create_mandate_controller(&linked_goal, &linked_mandate)
5258            .await
5259            .unwrap();
5260        assert!(store.get_goal(&linked_goal.id).await.unwrap().is_some());
5261
5262        let foreign_source = Goal::new_personal("Grow an audience", "different-owner-session");
5263        store.create_goal(&foreign_source).await.unwrap();
5264        let (foreign_goal, mut foreign_mandate) = controller("owner-session", 2);
5265        foreign_mandate.source_goal_id = Some(foreign_source.id);
5266        assert!(
5267            store
5268                .create_mandate_controller(&foreign_goal, &foreign_mandate)
5269                .await
5270                .is_err()
5271        );
5272        assert!(store.get_goal(&foreign_goal.id).await.unwrap().is_none());
5273    }
5274
5275    #[tokio::test]
5276    async fn verified_private_owner_is_authorized_across_bot_routes() {
5277        let (store, _database) = test_store().await;
5278        let (goal, mandate) = controller("alpha_bot:12345", 1);
5279        assert_eq!(mandate.owner_principal_id, "principal:telegram:12345");
5280        store
5281            .create_mandate_controller(&goal, &mandate)
5282            .await
5283            .unwrap();
5284
5285        assert!(
5286            store
5287                .is_mandate_session_authorized(&mandate.id, "beta_bot:12345")
5288                .await
5289                .unwrap()
5290        );
5291        assert_eq!(
5292            store
5293                .list_mandates(Some("beta_bot:12345"), false)
5294                .await
5295                .unwrap()
5296                .iter()
5297                .map(|item| item.id.as_str())
5298                .collect::<Vec<_>>(),
5299            [mandate.id.as_str()]
5300        );
5301        assert!(
5302            !store
5303                .is_mandate_session_authorized(&mandate.id, "beta_bot:67890")
5304                .await
5305                .unwrap()
5306        );
5307
5308        let (group_goal, group_mandate) = controller("alpha_bot:-10012345", 1);
5309        assert_ne!(
5310            group_mandate.owner_principal_id,
5311            "principal:telegram:-10012345"
5312        );
5313        store
5314            .create_mandate_controller(&group_goal, &group_mandate)
5315            .await
5316            .unwrap();
5317        assert!(
5318            !store
5319                .is_mandate_session_authorized(&group_mandate.id, "beta_bot:-10012345")
5320                .await
5321                .unwrap()
5322        );
5323    }
5324
5325    #[tokio::test]
5326    async fn objective_measurements_require_current_run_structured_receipts() {
5327        let (store, _database) = test_store().await;
5328        let (goal, mut mandate) = controller("owner-session", 1);
5329        mandate.objective_control = Some(objective_control());
5330        let run = claim_and_start_run(&store, &goal, &mandate).await;
5331        let receipt_id = "synthetic-metric-receipt";
5332        let task_id = run.root_task_id.as_deref().unwrap();
5333        sqlx::query(
5334            "INSERT INTO events
5335                (session_id, event_type, data, created_at, task_id, tool_name)
5336             VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
5337        )
5338        .bind("owner-session")
5339        .bind(
5340            serde_json::json!({
5341                "task_id": task_id,
5342                "tool_call_id": receipt_id,
5343                "name": "http_request",
5344                "result": "synthetic metric value",
5345                "success": true,
5346                "duration_ms": 1,
5347                "receipt": {
5348                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
5349                    "outcome_status": "succeeded",
5350                    "outcome_evidence": "structured_metadata"
5351                }
5352            })
5353            .to_string(),
5354        )
5355        .bind(chrono::Utc::now().to_rfc3339())
5356        .bind(task_id)
5357        .execute(&store.pool)
5358        .await
5359        .unwrap();
5360
5361        let measurement = MandateObjectiveMeasurement::new(
5362            &mandate.id,
5363            mandate.version,
5364            &run.id,
5365            12_000_000,
5366            9_500,
5367            vec![receipt_id.to_string()],
5368            &chrono::Utc::now().to_rfc3339(),
5369        );
5370        store
5371            .record_mandate_objective_measurement(&measurement)
5372            .await
5373            .unwrap();
5374        assert_eq!(
5375            store
5376                .list_mandate_objective_measurements(&mandate.id, 10)
5377                .await
5378                .unwrap(),
5379            vec![measurement]
5380        );
5381
5382        let unproven = MandateObjectiveMeasurement::new(
5383            &mandate.id,
5384            mandate.version,
5385            &run.id,
5386            13_000_000,
5387            9_500,
5388            vec!["receipt-from-another-run".to_string()],
5389            &chrono::Utc::now().to_rfc3339(),
5390        );
5391        assert!(
5392            store
5393                .record_mandate_objective_measurement(&unproven)
5394                .await
5395                .is_err()
5396        );
5397    }
5398
5399    #[tokio::test]
5400    async fn persistence_rejects_text_bound_bypasses_before_writing() {
5401        let (store, _database) = test_store().await;
5402        let (bad_goal, mut bad_mandate) = controller("owner-session", 2);
5403        bad_mandate.objective = "é".repeat(1_025);
5404        assert!(
5405            store
5406                .create_mandate_controller(&bad_goal, &bad_mandate)
5407                .await
5408                .is_err()
5409        );
5410        assert!(store.get_goal(&bad_goal.id).await.unwrap().is_none());
5411
5412        let (goal, mandate) = controller("owner-session", 2);
5413        let run = claim_and_start_run(&store, &goal, &mandate).await;
5414        let oversized_decision = MandateDecisionCycle::new(
5415            &mandate.id,
5416            &run.id,
5417            MandateDecisionOutcome::Wait,
5418            &"é".repeat(1_025),
5419            mandate.version,
5420        );
5421        assert!(
5422            store
5423                .record_mandate_decision(&oversized_decision, None, None)
5424                .await
5425                .is_err()
5426        );
5427
5428        let act = MandateDecisionCycle::new(
5429            &mandate.id,
5430            &run.id,
5431            MandateDecisionOutcome::Act,
5432            "A bounded governed action is useful",
5433            mandate.version,
5434        );
5435        let oversized_intention = Intention::new(
5436            &mandate.id,
5437            &act.id,
5438            &run.id,
5439            &"é".repeat(513),
5440            "A bounded governed action is useful",
5441        );
5442        assert!(
5443            store
5444                .record_mandate_decision(&act, Some(&oversized_intention), None)
5445                .await
5446                .is_err()
5447        );
5448        assert!(
5449            store
5450                .get_mandate_decision_for_run(&run.id)
5451                .await
5452                .unwrap()
5453                .is_none()
5454        );
5455    }
5456
5457    #[tokio::test]
5458    async fn owner_update_is_cas_and_clears_a_live_lease() {
5459        let (store, _database) = test_store().await;
5460        let (goal, mandate) = controller("owner-session", 2);
5461        store
5462            .create_mandate_controller(&goal, &mandate)
5463            .await
5464            .unwrap();
5465        assert_eq!(
5466            store
5467                .claim_due_mandates(1, "heartbeat", 300)
5468                .await
5469                .unwrap()
5470                .len(),
5471            1
5472        );
5473
5474        let mut update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5475        update.version += 1;
5476        update.objective = "Updated owner objective".to_string();
5477        store.update_mandate(&update).await.unwrap();
5478
5479        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5480        assert_eq!(loaded.version, 2);
5481        assert_eq!(loaded.objective, "Updated owner objective");
5482        assert!(loaded.review_lease_token.is_none());
5483        assert!(store.update_mandate(&update).await.is_err());
5484
5485        let mut attempted_pause = loaded;
5486        attempted_pause.version += 1;
5487        attempted_pause.status = MandateStatus::Paused;
5488        assert!(store.update_mandate(&attempted_pause).await.is_err());
5489        assert!(
5490            store
5491                .transition_mandate_status(
5492                    &mandate.id,
5493                    MandateStatus::Active,
5494                    MandateStatus::Paused,
5495                )
5496                .await
5497                .unwrap()
5498        );
5499        assert_eq!(
5500            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5501            "paused"
5502        );
5503    }
5504
5505    #[tokio::test]
5506    async fn confirmation_is_durable_atomic_and_required_for_activation() {
5507        let (store, _database) = test_store().await;
5508        let goal = Goal::new_continuous_pending(
5509            "Mandate awaiting owner confirmation",
5510            "owner-session",
5511            None,
5512            None,
5513        );
5514        let mut mandate = Mandate::new(
5515            &goal.id,
5516            None,
5517            "Await explicit owner confirmation",
5518            "owner-session",
5519            authority(0),
5520            60,
5521            3_600,
5522            300,
5523        );
5524        mandate.status = MandateStatus::Paused;
5525        mandate.confirmed_at = None;
5526        store
5527            .create_mandate_controller(&goal, &mandate)
5528            .await
5529            .unwrap();
5530
5531        assert!(
5532            !store
5533                .transition_mandate_status(
5534                    &mandate.id,
5535                    MandateStatus::Paused,
5536                    MandateStatus::Active,
5537                )
5538                .await
5539                .unwrap()
5540        );
5541        // Confirmation is a CAS against the exact policy version displayed to
5542        // the owner; a stale or speculative callback cannot activate it.
5543        assert!(
5544            !store
5545                .confirm_mandate(&mandate.id, mandate.version + 1, None)
5546                .await
5547                .unwrap()
5548        );
5549        assert_eq!(
5550            store
5551                .get_mandate(&mandate.id)
5552                .await
5553                .unwrap()
5554                .unwrap()
5555                .status,
5556            MandateStatus::Paused
5557        );
5558        assert!(
5559            store
5560                .confirm_mandate(&mandate.id, mandate.version, None)
5561                .await
5562                .unwrap()
5563        );
5564        assert!(
5565            !store
5566                .confirm_mandate(&mandate.id, mandate.version, None)
5567                .await
5568                .unwrap()
5569        );
5570
5571        let confirmed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5572        assert_eq!(confirmed.status, MandateStatus::Active);
5573        assert_eq!(confirmed.version, 2);
5574        assert!(confirmed.confirmed_at.is_some());
5575        assert!(confirmed.is_active());
5576        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
5577        assert_eq!(controller.status, "active");
5578        assert_eq!(controller.dispatch_failures, 0);
5579    }
5580
5581    #[tokio::test]
5582    async fn stale_confirmation_cleanup_cancels_linked_mandate_and_cannot_activate_it() {
5583        let (store, _database) = test_store().await;
5584        let goal =
5585            Goal::new_continuous_pending("Stale mandate confirmation", "owner-session", None, None);
5586        let mut mandate = Mandate::new(
5587            &goal.id,
5588            None,
5589            "Never activate without confirmation",
5590            "owner-session",
5591            authority(0),
5592            60,
5593            3_600,
5594            300,
5595        );
5596        mandate.status = MandateStatus::Paused;
5597        mandate.confirmed_at = None;
5598        store
5599            .create_mandate_controller(&goal, &mandate)
5600            .await
5601            .unwrap();
5602        sqlx::query("UPDATE goals SET created_at = ? WHERE id = ?")
5603            .bind((chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339())
5604            .bind(&goal.id)
5605            .execute(&store.pool)
5606            .await
5607            .unwrap();
5608
5609        assert_eq!(
5610            store
5611                .cancel_stale_pending_confirmation_goals(3_600)
5612                .await
5613                .unwrap(),
5614            1
5615        );
5616        let cancelled = store.get_mandate(&mandate.id).await.unwrap().unwrap();
5617        assert_eq!(cancelled.status, MandateStatus::Cancelled);
5618        assert!(cancelled.confirmed_at.is_none());
5619        assert_eq!(
5620            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5621            "cancelled"
5622        );
5623        assert!(
5624            !store
5625                .confirm_mandate(&mandate.id, mandate.version, None)
5626                .await
5627                .unwrap()
5628        );
5629        assert!(
5630            !store
5631                .transition_mandate_status(
5632                    &mandate.id,
5633                    MandateStatus::Cancelled,
5634                    MandateStatus::Active,
5635                )
5636                .await
5637                .unwrap()
5638        );
5639    }
5640
5641    #[tokio::test]
5642    async fn atomic_review_creation_rolls_back_run_when_root_insert_fails() {
5643        let (store, _database) = test_store().await;
5644        let (goal, mandate) = controller("owner-session", 1);
5645        store
5646            .create_mandate_controller(&goal, &mandate)
5647            .await
5648            .unwrap();
5649        let claimed = store
5650            .claim_due_mandates(1, "test-heartbeat", 300)
5651            .await
5652            .unwrap();
5653        let lease = claimed[0].review_lease_token.as_deref().unwrap();
5654
5655        let other_goal = Goal::new_finite("Existing task owner", "owner-session");
5656        store.create_goal(&other_goal).await.unwrap();
5657        let existing_task = review_root(&other_goal, "other-run", "duplicate-root-id");
5658        store.create_task(&existing_task).await.unwrap();
5659
5660        let attempted_run_id = uuid::Uuid::new_v4().to_string();
5661        let duplicate_root = review_root(&goal, &attempted_run_id, "duplicate-root-id");
5662        assert!(
5663            store
5664                .create_mandate_review_run(&mandate.id, lease, &attempted_run_id, &duplicate_root,)
5665                .await
5666                .is_err()
5667        );
5668        let orphan_count =
5669            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM goal_runs WHERE id = ?")
5670                .bind(&attempted_run_id)
5671                .fetch_one(&store.pool)
5672                .await
5673                .unwrap();
5674        assert_eq!(orphan_count, 0);
5675
5676        let successful_run_id = uuid::Uuid::new_v4().to_string();
5677        let fresh_root = review_root(&goal, &successful_run_id, &uuid::Uuid::new_v4().to_string());
5678        let run = store
5679            .create_mandate_review_run(&mandate.id, lease, &successful_run_id, &fresh_root)
5680            .await
5681            .unwrap();
5682        assert_eq!(run.root_task_id.as_deref(), Some(fresh_root.id.as_str()));
5683        assert_eq!(
5684            store.get_tasks_for_goal_run(&run.id).await.unwrap().len(),
5685            1
5686        );
5687    }
5688
5689    #[tokio::test]
5690    async fn claiming_recovers_pre_atomic_run_created_without_a_root_task() {
5691        let (store, _database) = test_store().await;
5692        let (goal, mandate) = controller("owner-session", 1);
5693        store
5694            .create_mandate_controller(&goal, &mandate)
5695            .await
5696            .unwrap();
5697        let first_claim = store
5698            .claim_due_mandates(1, "old-heartbeat", 300)
5699            .await
5700            .unwrap();
5701        assert_eq!(first_claim.len(), 1);
5702        let interrupted = store
5703            .start_goal_run(&goal.id, "mandate", None, Some("missing-root"))
5704            .await
5705            .unwrap();
5706
5707        let recovered = store
5708            .claim_due_mandates(1, "new-heartbeat", 300)
5709            .await
5710            .unwrap();
5711        assert_eq!(recovered.len(), 1);
5712        let old_run = store
5713            .get_goal_runs(&goal.id)
5714            .await
5715            .unwrap()
5716            .into_iter()
5717            .find(|run| run.id == interrupted.id)
5718            .unwrap();
5719        assert_eq!(old_run.status, "failed");
5720        assert!(
5721            old_run
5722                .outcome_summary
5723                .as_deref()
5724                .unwrap()
5725                .contains("interrupted mandate dispatch")
5726        );
5727
5728        let run_id = uuid::Uuid::new_v4().to_string();
5729        let root = review_root(&goal, &run_id, &uuid::Uuid::new_v4().to_string());
5730        let new_run = store
5731            .create_mandate_review_run(
5732                &mandate.id,
5733                recovered[0].review_lease_token.as_deref().unwrap(),
5734                &run_id,
5735                &root,
5736            )
5737            .await
5738            .unwrap();
5739        assert_eq!(
5740            store
5741                .get_tasks_for_goal_run(&new_run.id)
5742                .await
5743                .unwrap()
5744                .len(),
5745            1
5746        );
5747    }
5748
5749    #[tokio::test]
5750    async fn completed_root_crash_without_dispatch_retries_after_grace_and_cancels_pending_child() {
5751        let (store, _database) = test_store().await;
5752        let (goal, mandate) = controller("owner-session", 1);
5753        let run = claim_and_start_run(&store, &goal, &mandate).await;
5754        let root_task_id = run.root_task_id.as_deref().unwrap();
5755        let root_attempt = store
5756            .claim_task_with_lease(
5757                root_task_id,
5758                "crashing-root",
5759                Some("profile-task-lead"),
5760                7_200,
5761            )
5762            .await
5763            .unwrap()
5764            .unwrap();
5765        let act = MandateDecisionCycle::new(
5766            &mandate.id,
5767            &run.id,
5768            MandateDecisionOutcome::Act,
5769            "One bounded child should perform the action",
5770            mandate.version,
5771        );
5772        let intention = Intention::new(
5773            &mandate.id,
5774            &act.id,
5775            &run.id,
5776            "Perform the bounded child action",
5777            "It advances the mandate",
5778        );
5779        store
5780            .record_mandate_decision(&act, Some(&intention), Some(&root_attempt.id))
5781            .await
5782            .unwrap();
5783        let child_id = uuid::Uuid::new_v4().to_string();
5784        let mut child = review_root(&goal, &run.id, &child_id);
5785        child.task_order = 1;
5786        child.description = "Pending governed child".to_string();
5787        assert!(
5788            store
5789                .create_mandate_task_from_attempt(
5790                    &child,
5791                    &mandate.id,
5792                    mandate.version,
5793                    &run.id,
5794                    &root_attempt.id,
5795                    16,
5796                )
5797                .await
5798                .unwrap()
5799        );
5800        assert!(
5801            store
5802                .patch_task_from_attempt(
5803                    &root_attempt.id,
5804                    &root_attempt.lease_token,
5805                    &crate::traits::TaskAttemptPatch {
5806                        status: "completed".to_string(),
5807                        result: Some("decision recorded; child queued".to_string()),
5808                        ..Default::default()
5809                    },
5810                )
5811                .await
5812                .unwrap()
5813        );
5814
5815        // The immediate finalizer gets a short uncontended window.
5816        assert!(
5817            store
5818                .claim_due_mandates(1, "grace-probe", 300)
5819                .await
5820                .unwrap()
5821                .is_empty()
5822        );
5823        assert_eq!(
5824            store
5825                .get_mandate(&mandate.id)
5826                .await
5827                .unwrap()
5828                .unwrap()
5829                .status,
5830            MandateStatus::Active
5831        );
5832        assert_eq!(
5833            store.get_task(&child_id).await.unwrap().unwrap().status,
5834            "pending"
5835        );
5836
5837        let stale_completion = (chrono::Utc::now() - chrono::Duration::seconds(61)).to_rfc3339();
5838        sqlx::query("UPDATE tasks SET completed_at = ? WHERE id = ?")
5839            .bind(&stale_completion)
5840            .bind(root_task_id)
5841            .execute(&store.pool)
5842            .await
5843            .unwrap();
5844        assert!(
5845            store
5846                .claim_due_mandates(1, "reconciliation-probe", 300)
5847                .await
5848                .unwrap()
5849                .is_empty()
5850        );
5851
5852        // The child never reserved a mutation, so nothing external can have
5853        // happened: the run fails and the mandate retries, unsuspended.
5854        assert_eq!(
5855            store
5856                .get_mandate(&mandate.id)
5857                .await
5858                .unwrap()
5859                .unwrap()
5860                .status,
5861            MandateStatus::Active
5862        );
5863        assert_eq!(
5864            store.get_goal(&goal.id).await.unwrap().unwrap().status,
5865            "active"
5866        );
5867        assert_eq!(
5868            store.get_task(&child_id).await.unwrap().unwrap().status,
5869            "cancelled"
5870        );
5871        assert_eq!(
5872            store.get_goal_runs(&goal.id).await.unwrap()[0]
5873                .outcome_summary
5874                .as_deref(),
5875            Some("mandate_review_failed:act_interrupted_before_dispatch")
5876        );
5877        let notification_message: String = sqlx::query_scalar(
5878            "SELECT message FROM notification_queue
5879             WHERE goal_id = ? AND notification_type = 'mandate_review_failed'
5880               AND priority = 'critical' AND expires_at IS NULL
5881             LIMIT 1",
5882        )
5883        .bind(&goal.id)
5884        .fetch_one(&store.pool)
5885        .await
5886        .unwrap();
5887        assert!(
5888            notification_message.contains("decided to act"),
5889            "{notification_message}"
5890        );
5891        assert!(
5892            notification_message.contains("interrupted before any action was dispatched"),
5893            "{notification_message}"
5894        );
5895        assert!(!notification_message.contains("stopped before it finished"));
5896        assert!(notification_message.contains("will retry automatically"));
5897        let intention_status =
5898            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
5899                .bind(&intention.id)
5900                .fetch_one(&store.pool)
5901                .await
5902                .unwrap();
5903        assert_eq!(intention_status, "suspended");
5904    }
5905
5906    /// An ACT committed by a root whose daemon then stopped: no action task,
5907    /// no reservation, root attempt gone.
5908    async fn orphan_act_without_task(
5909        store: &SqliteWorkStore,
5910    ) -> (Goal, Mandate, crate::traits::GoalRun, Intention) {
5911        let (goal, mandate) = controller("owner-session", 1);
5912        let run = claim_and_start_run(store, &goal, &mandate).await;
5913        let root_task_id = run.root_task_id.clone().unwrap();
5914        let root_attempt = store
5915            .claim_task_with_lease(
5916                &root_task_id,
5917                "crashing-root",
5918                Some("profile-task-lead"),
5919                600,
5920            )
5921            .await
5922            .unwrap()
5923            .unwrap();
5924        let act = MandateDecisionCycle::new(
5925            &mandate.id,
5926            &run.id,
5927            MandateDecisionOutcome::Act,
5928            "Post the drafted update",
5929            mandate.version,
5930        );
5931        let intention = Intention::new(
5932            &mandate.id,
5933            &act.id,
5934            &run.id,
5935            "Publish: Synthetic launch note for Acme Corp",
5936            "It advances the mandate",
5937        );
5938        store
5939            .record_mandate_decision(&act, Some(&intention), Some(&root_attempt.id))
5940            .await
5941            .unwrap();
5942        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
5943            .bind((chrono::Utc::now() - chrono::Duration::seconds(5)).to_rfc3339())
5944            .bind(&root_attempt.id)
5945            .execute(&store.pool)
5946            .await
5947            .unwrap();
5948        sqlx::query("UPDATE tasks SET status = 'interrupted' WHERE id = ?")
5949            .bind(&root_task_id)
5950            .execute(&store.pool)
5951            .await
5952            .unwrap();
5953        (goal, mandate, run, intention)
5954    }
5955
5956    async fn recover(store: &SqliteWorkStore) {
5957        let _ = store
5958            .claim_due_mandates(1, "recovery-probe", 300)
5959            .await
5960            .unwrap();
5961    }
5962
5963    #[tokio::test]
5964    async fn orphaned_act_without_task_resumes_once_with_saved_intention() {
5965        let (store, _database) = test_store().await;
5966        let (goal, mandate, run, intention) = orphan_act_without_task(&store).await;
5967        recover(&store).await;
5968        let root = store
5969            .get_task(run.root_task_id.as_deref().unwrap())
5970            .await
5971            .unwrap()
5972            .unwrap();
5973        assert_eq!(root.status, "pending");
5974        assert_eq!(root.retry_count, 1);
5975        assert!(
5976            root.description.contains(&intention.description),
5977            "{}",
5978            root.description
5979        );
5980        let runs = store.get_goal_runs(&goal.id).await.unwrap();
5981        assert_eq!(runs.len(), 1);
5982        assert_eq!(runs[0].status, "pending");
5983        assert_eq!(
5984            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
5985                .bind(&intention.id)
5986                .fetch_one(&store.pool)
5987                .await
5988                .unwrap(),
5989            "committed"
5990        );
5991        assert_eq!(
5992            store
5993                .get_mandate(&mandate.id)
5994                .await
5995                .unwrap()
5996                .unwrap()
5997                .status,
5998            MandateStatus::Active
5999        );
6000        // A second recovery while it waits for dispatch changes nothing.
6001        recover(&store).await;
6002        let tasks = store.get_tasks_for_goal_run(&run.id).await.unwrap();
6003        assert_eq!(tasks.len(), 1);
6004        assert_eq!(tasks[0].status, "pending");
6005        assert_eq!(store.get_goal_runs(&goal.id).await.unwrap().len(), 1);
6006    }
6007
6008    #[tokio::test]
6009    async fn resumed_act_interrupted_again_falls_back_instead_of_resuming_twice() {
6010        let (store, _database) = test_store().await;
6011        let (goal, _mandate, run, intention) = orphan_act_without_task(&store).await;
6012        let root_task_id = run.root_task_id.clone().unwrap();
6013        recover(&store).await;
6014        // The resumed lead is interrupted too, again before any task.
6015        let attempt = store
6016            .claim_task_with_lease(
6017                &root_task_id,
6018                "resumed-root",
6019                Some("profile-task-lead"),
6020                600,
6021            )
6022            .await
6023            .unwrap()
6024            .unwrap();
6025        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
6026            .bind((chrono::Utc::now() - chrono::Duration::seconds(5)).to_rfc3339())
6027            .bind(&attempt.id)
6028            .execute(&store.pool)
6029            .await
6030            .unwrap();
6031        sqlx::query("UPDATE tasks SET status = 'interrupted' WHERE id = ?")
6032            .bind(&root_task_id)
6033            .execute(&store.pool)
6034            .await
6035            .unwrap();
6036        recover(&store).await;
6037        assert_eq!(
6038            store.get_goal_runs(&goal.id).await.unwrap()[0]
6039                .outcome_summary
6040                .as_deref(),
6041            Some("mandate_review_failed:act_interrupted_before_dispatch")
6042        );
6043        assert_eq!(
6044            sqlx::query_scalar::<_, String>("SELECT status FROM intentions WHERE id = ?")
6045                .bind(&intention.id)
6046                .fetch_one(&store.pool)
6047                .await
6048                .unwrap(),
6049            "suspended"
6050        );
6051    }
6052
6053    #[tokio::test]
6054    async fn orphaned_act_with_existing_action_task_is_not_resumed() {
6055        let (store, _database) = test_store().await;
6056        let (goal, _mandate, run, _intention) = orphan_act_without_task(&store).await;
6057        // An action task already exists for the cycle: never resume.
6058        sqlx::query("UPDATE tasks SET retry_count = 0 WHERE id = ?")
6059            .bind(run.root_task_id.as_deref().unwrap())
6060            .execute(&store.pool)
6061            .await
6062            .unwrap();
6063        let child_id = uuid::Uuid::new_v4().to_string();
6064        let mut child = review_root(&goal, &run.id, &child_id);
6065        child.task_order = 1;
6066        store.create_task(&child).await.unwrap();
6067        recover(&store).await;
6068        let runs = store.get_goal_runs(&goal.id).await.unwrap();
6069        assert_ne!(runs[0].status, "pending");
6070        assert_eq!(
6071            runs[0].outcome_summary.as_deref(),
6072            Some("mandate_review_failed:act_interrupted_before_dispatch")
6073        );
6074    }
6075
6076    #[tokio::test]
6077    async fn stale_or_version_changed_act_is_not_resumed() {
6078        for case in ["stale", "version"] {
6079            let (store, _database) = test_store().await;
6080            let (goal, mandate, run, _intention) = orphan_act_without_task(&store).await;
6081            match case {
6082                "stale" => {
6083                    sqlx::query(
6084                        "UPDATE mandate_decision_cycles SET created_at = ? WHERE goal_run_id = ?",
6085                    )
6086                    .bind((chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339())
6087                    .bind(&run.id)
6088                    .execute(&store.pool)
6089                    .await
6090                    .unwrap();
6091                }
6092                _ => {
6093                    sqlx::query("UPDATE mandates SET version = version + 1 WHERE id = ?")
6094                        .bind(&mandate.id)
6095                        .execute(&store.pool)
6096                        .await
6097                        .unwrap();
6098                }
6099            }
6100            recover(&store).await;
6101            let root = store
6102                .get_task(run.root_task_id.as_deref().unwrap())
6103                .await
6104                .unwrap()
6105                .unwrap();
6106            assert_eq!(root.retry_count, 0, "{case}");
6107            assert_ne!(root.status, "pending", "{case}");
6108            if case == "stale" {
6109                assert_eq!(
6110                    store.get_goal_runs(&goal.id).await.unwrap()[0]
6111                        .outcome_summary
6112                        .as_deref(),
6113                    Some("mandate_review_failed:act_interrupted_before_dispatch")
6114                );
6115            }
6116        }
6117    }
6118
6119    #[tokio::test]
6120    async fn orphaned_review_without_decision_retries_without_reconciliation_pause() {
6121        let (store, _database) = test_store().await;
6122        let (goal, mandate) = controller("owner-session", 1);
6123        let run = claim_and_start_run(&store, &goal, &mandate).await;
6124        let root_attempt = store
6125            .claim_task_with_lease(
6126                run.root_task_id.as_deref().unwrap(),
6127                "crashing-reviewer",
6128                Some("profile-task-lead"),
6129                180,
6130            )
6131            .await
6132            .unwrap()
6133            .unwrap();
6134        sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
6135            .bind((chrono::Utc::now() - chrono::Duration::seconds(1)).to_rfc3339())
6136            .bind(&root_attempt.id)
6137            .execute(&store.pool)
6138            .await
6139            .unwrap();
6140
6141        assert!(
6142            store
6143                .claim_due_mandates(1, "orphan-recovery", 300)
6144                .await
6145                .unwrap()
6146                .is_empty()
6147        );
6148
6149        let recovered_mandate = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6150        assert_eq!(recovered_mandate.status, MandateStatus::Active);
6151        assert!(recovered_mandate.next_review_at > chrono::Utc::now().to_rfc3339());
6152        assert_eq!(
6153            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6154            "active"
6155        );
6156        let recovered_run = store
6157            .get_goal_runs(&goal.id)
6158            .await
6159            .unwrap()
6160            .into_iter()
6161            .find(|candidate| candidate.id == run.id)
6162            .unwrap();
6163        assert_eq!(recovered_run.status, "failed");
6164        assert_eq!(
6165            recovered_run.outcome_summary.as_deref(),
6166            Some("mandate_review_failed:decision_missing")
6167        );
6168
6169        let root = store
6170            .get_task(run.root_task_id.as_deref().unwrap())
6171            .await
6172            .unwrap()
6173            .unwrap();
6174        assert_eq!(root.status, "cancelled");
6175        let notification: (String, String) = sqlx::query_as(
6176            "SELECT notification_type, message FROM notification_queue
6177             WHERE id = ?",
6178        )
6179        .bind(format!("mandate-run-notice:{}", run.id))
6180        .fetch_one(&store.pool)
6181        .await
6182        .unwrap();
6183        assert_eq!(notification.0, "mandate_review_failed");
6184        assert!(notification.1.contains("before it decided anything"));
6185        assert!(!notification.1.contains("decision missing"));
6186        assert!(notification.1.contains("Nothing was done"));
6187        assert!(!notification.1.contains("check the account"));
6188    }
6189
6190    #[tokio::test]
6191    async fn stale_controller_repair_cannot_revive_an_owner_cancellation() {
6192        let (store, _database) = test_store().await;
6193        let (goal, mandate) = controller("owner-session", 1);
6194        store
6195            .create_mandate_controller(&goal, &mandate)
6196            .await
6197            .unwrap();
6198        assert!(
6199            store
6200                .transition_mandate_status(
6201                    &mandate.id,
6202                    MandateStatus::Active,
6203                    MandateStatus::Cancelled,
6204                )
6205                .await
6206                .unwrap()
6207        );
6208
6209        assert!(
6210            !store
6211                .keep_mandate_controller_active(&mandate.id, mandate.version)
6212                .await
6213                .unwrap()
6214        );
6215        assert_eq!(
6216            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6217            "cancelled"
6218        );
6219    }
6220
6221    /// An executor's blocker is input to the task lead, which owns the run's
6222    /// A mandate step that depends on another has its dependency row from the
6223    /// moment it is written, so a claim waits for the prerequisite (live
6224    /// 2026-11-21: the rows came only from a rebuild at the next start).
6225    #[tokio::test]
6226    async fn a_mandate_step_waits_for_its_prerequisite_from_its_write() {
6227        let (store, _database) = test_store().await;
6228        let (goal, mandate) = controller("owner-session", 2);
6229        let run = claim_and_start_run(&store, &goal, &mandate).await;
6230        let act = MandateDecisionCycle::new(
6231            &mandate.id,
6232            &run.id,
6233            MandateDecisionOutcome::Act,
6234            "Two ordered steps are warranted",
6235            mandate.version,
6236        );
6237        let intention = Intention::new(
6238            &mandate.id,
6239            &act.id,
6240            &run.id,
6241            "Draft, then post, one bounded note",
6242            "It advances the mandate",
6243        );
6244        store
6245            .record_mandate_decision(&act, Some(&intention), None)
6246            .await
6247            .unwrap();
6248        let root_task_id = run.root_task_id.as_deref().unwrap();
6249        let root_attempt = store
6250            .claim_task_with_lease(
6251                root_task_id,
6252                "root-worker",
6253                Some("profile-task-lead"),
6254                7_200,
6255            )
6256            .await
6257            .unwrap()
6258            .unwrap();
6259        let mut first = review_root(&goal, &run.id, "step-first");
6260        first.task_order = 1;
6261        let mut second = review_root(&goal, &run.id, "step-second");
6262        second.task_order = 2;
6263        second.depends_on = Some(serde_json::json!(["step-first"]).to_string());
6264        for task in [&first, &second] {
6265            assert!(
6266                store
6267                    .create_mandate_task_from_attempt(
6268                        task,
6269                        &mandate.id,
6270                        mandate.version,
6271                        &run.id,
6272                        &root_attempt.id,
6273                        16,
6274                    )
6275                    .await
6276                    .unwrap()
6277            );
6278        }
6279        let rows: Vec<String> = sqlx::query_scalar(
6280            "SELECT depends_on_task_id FROM task_dependencies WHERE task_id = 'step-second'",
6281        )
6282        .fetch_all(&store.pool)
6283        .await
6284        .unwrap();
6285        assert_eq!(rows, ["step-first"]);
6286        assert!(
6287            store
6288                .claim_mandate_task_from_attempt(
6289                    "step-second",
6290                    "executor-worker",
6291                    &mandate.id,
6292                    mandate.version,
6293                    &run.id,
6294                    &root_attempt.id,
6295                    7_200,
6296                )
6297                .await
6298                .unwrap()
6299                .is_none(),
6300            "not claimed before its prerequisite is done"
6301        );
6302    }
6303
6304    /// outcome: the mandate run stays running so the lead can still call the
6305    /// model (budget fence) and finalize. The lead's own blocker still blocks.
6306    #[tokio::test]
6307    async fn executor_blocker_leaves_the_mandate_run_to_its_task_lead() {
6308        let (store, _database) = test_store().await;
6309        let (goal, mandate) = controller("owner-session", 2);
6310        let run = claim_and_start_run(&store, &goal, &mandate).await;
6311        let act = MandateDecisionCycle::new(
6312            &mandate.id,
6313            &run.id,
6314            MandateDecisionOutcome::Act,
6315            "One bounded note is warranted",
6316            mandate.version,
6317        );
6318        let intention = Intention::new(
6319            &mandate.id,
6320            &act.id,
6321            &run.id,
6322            "Post one bounded note",
6323            "It advances the mandate",
6324        );
6325        store
6326            .record_mandate_decision(&act, Some(&intention), None)
6327            .await
6328            .unwrap();
6329        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6330        let blocked = |reason: &str| crate::traits::TaskAttemptPatch {
6331            status: "blocked".to_string(),
6332            result: None,
6333            error: None,
6334            blocker: Some(reason.to_string()),
6335            context: None,
6336            handoff: None,
6337        };
6338        async fn run_status(store: &SqliteWorkStore, run_id: &str) -> String {
6339            sqlx::query_scalar::<_, String>("SELECT status FROM goal_runs WHERE id = ?")
6340                .bind(run_id)
6341                .fetch_one(&store.pool)
6342                .await
6343                .unwrap()
6344        }
6345
6346        assert!(
6347            store
6348                .patch_task_from_attempt(
6349                    &fence.worker_attempt.id,
6350                    &fence.worker_attempt.lease_token,
6351                    &blocked("the target is unreachable"),
6352                )
6353                .await
6354                .unwrap()
6355        );
6356        assert_eq!(run_status(&store, &run.id).await, "running");
6357
6358        assert!(
6359            store
6360                .patch_task_from_attempt(
6361                    &fence.root_attempt.id,
6362                    &fence.root_attempt.lease_token,
6363                    &blocked("the lead cannot continue"),
6364                )
6365                .await
6366                .unwrap()
6367        );
6368        assert_eq!(run_status(&store, &run.id).await, "blocked");
6369    }
6370
6371    #[tokio::test]
6372    async fn lifecycle_transition_revokes_open_cycle_and_stale_owner_snapshot() {
6373        let (store, _database) = test_store().await;
6374        let (goal, mandate) = controller("owner-session", 2);
6375        let run = claim_and_start_run(&store, &goal, &mandate).await;
6376        let act = MandateDecisionCycle::new(
6377            &mandate.id,
6378            &run.id,
6379            MandateDecisionOutcome::Act,
6380            "A bounded action was justified before the pause",
6381            mandate.version,
6382        );
6383        let intention = Intention::new(
6384            &mandate.id,
6385            &act.id,
6386            &run.id,
6387            "Perform one bounded action",
6388            "It advances the mandate",
6389        );
6390        store
6391            .record_mandate_decision(&act, Some(&intention), None)
6392            .await
6393            .unwrap();
6394        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6395
6396        let mut stale_update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6397        stale_update.version += 1;
6398        stale_update.objective = "A stale owner snapshot".to_string();
6399
6400        assert!(
6401            store
6402                .transition_mandate_status(
6403                    &mandate.id,
6404                    MandateStatus::Active,
6405                    MandateStatus::Paused,
6406                )
6407                .await
6408                .unwrap()
6409        );
6410        let paused = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6411        assert_eq!(paused.status, MandateStatus::Paused);
6412        assert_eq!(paused.version, mandate.version + 1);
6413        assert!(
6414            store
6415                .get_current_goal_run(&goal.id)
6416                .await
6417                .unwrap()
6418                .is_none()
6419        );
6420        assert_eq!(
6421            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
6422            "cancelled"
6423        );
6424        assert_eq!(
6425            store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
6426            IntentionStatus::Suspended
6427        );
6428        assert!(
6429            store
6430                .reserve_mandate_action_attempt(&reservation(
6431                    &mandate,
6432                    &act,
6433                    &run,
6434                    &fence,
6435                    1,
6436                    1,
6437                    chrono::Utc::now(),
6438                ))
6439                .await
6440                .unwrap()
6441                .is_none()
6442        );
6443
6444        assert!(
6445            store
6446                .transition_mandate_status(
6447                    &mandate.id,
6448                    MandateStatus::Paused,
6449                    MandateStatus::Active,
6450                )
6451                .await
6452                .unwrap()
6453        );
6454        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6455        assert_eq!(resumed.version, mandate.version + 2);
6456        assert!(
6457            store
6458                .get_current_goal_run(&goal.id)
6459                .await
6460                .unwrap()
6461                .is_none()
6462        );
6463
6464        // The update was prepared before the lifecycle epoch changed, so its
6465        // CAS must fail instead of restoring its stale active status/policy.
6466        assert!(store.update_mandate(&stale_update).await.is_err());
6467
6468        let mut stale_cancel_racer = resumed;
6469        stale_cancel_racer.version += 1;
6470        stale_cancel_racer.objective = "Must not resurrect after cancel".to_string();
6471        assert!(
6472            store
6473                .transition_mandate_status(
6474                    &mandate.id,
6475                    MandateStatus::Active,
6476                    MandateStatus::Cancelled,
6477                )
6478                .await
6479                .unwrap()
6480        );
6481        assert!(store.update_mandate(&stale_cancel_racer).await.is_err());
6482        let cancelled = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6483        assert_eq!(cancelled.status, MandateStatus::Cancelled);
6484        assert_eq!(cancelled.version, mandate.version + 3);
6485    }
6486
6487    #[tokio::test]
6488    async fn policy_update_marks_unclaimed_reservation_never_dispatched_and_releases_rolling_quota()
6489    {
6490        let (store, _database) = test_store().await;
6491        let (goal, mandate) = controller("owner-session", 2);
6492        let run = claim_and_start_run(&store, &goal, &mandate).await;
6493        let act = MandateDecisionCycle::new(
6494            &mandate.id,
6495            &run.id,
6496            MandateDecisionOutcome::Act,
6497            "A bounded action was justified before the policy update",
6498            mandate.version,
6499        );
6500        let intention = Intention::new(
6501            &mandate.id,
6502            &act.id,
6503            &run.id,
6504            "Perform one bounded action",
6505            "It tests pre-dispatch invalidation",
6506        );
6507        store
6508            .record_mandate_decision(&act, Some(&intention), None)
6509            .await
6510            .unwrap();
6511        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6512        let now = chrono::Utc::now();
6513        let unclaimed = reservation(&mandate, &act, &run, &fence, 1, 41, now);
6514        assert!(
6515            store
6516                .reserve_mandate_action_attempt(&unclaimed)
6517                .await
6518                .unwrap()
6519                .is_some()
6520        );
6521
6522        let mut updated = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6523        updated.version += 1;
6524        updated
6525            .constraints
6526            .push("Owner narrowed the policy".to_string());
6527        store.update_mandate(&updated).await.unwrap();
6528
6529        let attempts = store
6530            .list_mandate_mutation_attempts_for_run(&run.id)
6531            .await
6532            .unwrap();
6533        assert_eq!(attempts.len(), 1);
6534        assert_eq!(
6535            attempts[0].status,
6536            MandateMutationAttemptStatus::NeverDispatched
6537        );
6538        assert!(attempts[0].completed_at.is_some());
6539        let quota = store
6540            .get_mandate_mutation_quota_state(
6541                &mandate.id,
6542                &(now + chrono::Duration::seconds(1)).to_rfc3339(),
6543            )
6544            .await
6545            .unwrap()
6546            .unwrap();
6547        assert_eq!(quota.reserved_in_rolling_24h, 0);
6548        assert_eq!(quota.remaining_in_rolling_24h, 24);
6549    }
6550
6551    #[tokio::test]
6552    async fn pause_marks_claimed_unresolved_reservation_ambiguous_and_run_reconciliation_required()
6553    {
6554        let (store, _database) = test_store().await;
6555        let (goal, mandate) = controller("owner-session", 1);
6556        let run = claim_and_start_run(&store, &goal, &mandate).await;
6557        let act = MandateDecisionCycle::new(
6558            &mandate.id,
6559            &run.id,
6560            MandateDecisionOutcome::Act,
6561            "One mutation was authorized before the pause",
6562            mandate.version,
6563        );
6564        let intention = Intention::new(
6565            &mandate.id,
6566            &act.id,
6567            &run.id,
6568            "Perform one bounded action",
6569            "It tests claimed-dispatch invalidation",
6570        );
6571        store
6572            .record_mandate_decision(&act, Some(&intention), None)
6573            .await
6574            .unwrap();
6575        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6576        let now = chrono::Utc::now();
6577        let claimed = reservation(&mandate, &act, &run, &fence, 1, 42, now);
6578        assert!(
6579            store
6580                .reserve_mandate_action_attempt(&claimed)
6581                .await
6582                .unwrap()
6583                .is_some()
6584        );
6585        assert!(
6586            store
6587                .claim_mandate_mutation_dispatch(&dispatch_claim(
6588                    &claimed,
6589                    now + chrono::Duration::milliseconds(1),
6590                ))
6591                .await
6592                .unwrap()
6593        );
6594
6595        assert!(
6596            store
6597                .transition_mandate_status(
6598                    &mandate.id,
6599                    MandateStatus::Active,
6600                    MandateStatus::Paused,
6601                )
6602                .await
6603                .unwrap()
6604        );
6605        let attempts = store
6606            .list_mandate_mutation_attempts_for_run(&run.id)
6607            .await
6608            .unwrap();
6609        assert_eq!(attempts.len(), 1);
6610        assert_eq!(attempts[0].status, MandateMutationAttemptStatus::Ambiguous);
6611        assert!(attempts[0].completed_at.is_some());
6612        let closed_run = store
6613            .get_goal_runs(&goal.id)
6614            .await
6615            .unwrap()
6616            .into_iter()
6617            .find(|candidate| candidate.id == run.id)
6618            .unwrap();
6619        assert_eq!(closed_run.status, "cancelled");
6620        assert_eq!(
6621            closed_run.outcome_summary.as_deref(),
6622            Some("mandate_reconciliation_required:lifecycle_invalidated_after_dispatch_claim")
6623        );
6624        let notice_count: i64 = sqlx::query_scalar(
6625            "SELECT COUNT(*) FROM notification_queue
6626             WHERE id = ? AND notification_type = 'mandate_reconciliation_required'
6627               AND priority = 'critical' AND expires_at IS NULL",
6628        )
6629        .bind(format!("mandate-run-notice:{}", run.id))
6630        .fetch_one(&store.pool)
6631        .await
6632        .unwrap();
6633        assert_eq!(notice_count, 1);
6634        let suspended = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6635        assert_eq!(suspended.status, MandateStatus::AwaitingInput);
6636        assert_eq!(
6637            suspended.suspension.as_ref().map(|value| value.kind),
6638            Some(MandateSuspensionKind::ReconciliationRequired)
6639        );
6640        assert!(
6641            store
6642                .resolve_mandate_suspension(
6643                    &mandate.id,
6644                    suspended.version,
6645                    MandateSuspensionKind::ReconciliationRequired,
6646                    None,
6647                    Some(MandateReconciliationResolution::ConfirmedNoEffect),
6648                    "I inspected the exact target and confirmed no effect occurred.",
6649                    "owner-session",
6650                )
6651                .await
6652                .unwrap()
6653        );
6654        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6655        assert_eq!(resumed.status, MandateStatus::Active);
6656        assert!(resumed.suspension.is_none());
6657        let reconciliations: i64 = sqlx::query_scalar(
6658            "SELECT COUNT(*) FROM mandate_reconciliations
6659             WHERE mandate_id = ? AND resolution = 'confirmed_no_effect'",
6660        )
6661        .bind(&mandate.id)
6662        .fetch_one(&store.pool)
6663        .await
6664        .unwrap();
6665        assert_eq!(reconciliations, 1);
6666    }
6667
6668    #[tokio::test]
6669    async fn policy_update_with_claimed_unresolved_mutation_lands_awaiting_input() {
6670        let (store, _database) = test_store().await;
6671        let (goal, mandate) = controller("owner-session", 1);
6672        let run = claim_and_start_run(&store, &goal, &mandate).await;
6673        let act = MandateDecisionCycle::new(
6674            &mandate.id,
6675            &run.id,
6676            MandateDecisionOutcome::Act,
6677            "One action was authorized under the old policy",
6678            mandate.version,
6679        );
6680        let intention = Intention::new(
6681            &mandate.id,
6682            &act.id,
6683            &run.id,
6684            "Perform one bounded action",
6685            "It tests policy-race reconciliation",
6686        );
6687        store
6688            .record_mandate_decision(&act, Some(&intention), None)
6689            .await
6690            .unwrap();
6691        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
6692        let now = chrono::Utc::now();
6693        let claimed = reservation(&mandate, &act, &run, &fence, 1, 43, now);
6694        assert!(
6695            store
6696                .reserve_mandate_action_attempt(&claimed)
6697                .await
6698                .unwrap()
6699                .is_some()
6700        );
6701        assert!(
6702            store
6703                .claim_mandate_mutation_dispatch(&dispatch_claim(
6704                    &claimed,
6705                    now + chrono::Duration::milliseconds(1),
6706                ))
6707                .await
6708                .unwrap()
6709        );
6710
6711        let mut updated = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6712        updated.version += 1;
6713        updated
6714            .constraints
6715            .push("Owner narrowed the policy after dispatch".to_string());
6716        store.update_mandate(&updated).await.unwrap();
6717
6718        let stored = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6719        assert_eq!(stored.version, updated.version);
6720        assert_eq!(stored.status, MandateStatus::AwaitingInput);
6721        assert_eq!(
6722            store.get_goal(&goal.id).await.unwrap().unwrap().status,
6723            "paused"
6724        );
6725        assert_eq!(
6726            store
6727                .list_mandate_mutation_attempts_for_run(&run.id)
6728                .await
6729                .unwrap()[0]
6730                .status,
6731            MandateMutationAttemptStatus::Ambiguous
6732        );
6733        let notices: i64 =
6734            sqlx::query_scalar("SELECT COUNT(*) FROM notification_queue WHERE id = ?")
6735                .bind(format!("mandate-run-notice:{}", run.id))
6736                .fetch_one(&store.pool)
6737                .await
6738                .unwrap();
6739        assert_eq!(notices, 1);
6740    }
6741
6742    #[tokio::test]
6743    async fn due_review_lease_has_one_winner_and_requires_its_token_to_release() {
6744        let (store, _database) = test_store().await;
6745        let (goal, mandate) = controller("owner-session", 2);
6746        store
6747            .create_mandate_controller(&goal, &mandate)
6748            .await
6749            .unwrap();
6750
6751        let (left, right) = tokio::join!(
6752            store.claim_due_mandates(1, "heartbeat-a", 300),
6753            store.claim_due_mandates(1, "heartbeat-b", 300)
6754        );
6755        let mut winners = left.unwrap();
6756        winners.extend(right.unwrap());
6757        assert_eq!(winners.len(), 1);
6758        let lease_token = winners[0].review_lease_token.clone().unwrap();
6759        assert!(
6760            !store
6761                .release_mandate_review_lease(
6762                    &mandate.id,
6763                    "wrong-token",
6764                    &(chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339(),
6765                )
6766                .await
6767                .unwrap()
6768        );
6769
6770        let retry_at = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
6771        assert!(
6772            store
6773                .release_mandate_review_lease(&mandate.id, &lease_token, &retry_at)
6774                .await
6775                .unwrap()
6776        );
6777        let released = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6778        assert_eq!(released.next_review_at, retry_at);
6779        assert!(released.review_lease_token.is_none());
6780        assert!(
6781            store
6782                .claim_due_mandates(1, "heartbeat-c", 300)
6783                .await
6784                .unwrap()
6785                .is_empty()
6786        );
6787    }
6788
6789    #[tokio::test]
6790    async fn claiming_reviews_atomically_closes_expired_mandates_and_controllers() {
6791        let (store, _database) = test_store().await;
6792        let (goal, mut mandate) = controller("owner-session", 2);
6793        mandate.expires_at = Some((chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339());
6794        store
6795            .create_mandate_controller(&goal, &mandate)
6796            .await
6797            .unwrap();
6798
6799        assert!(
6800            store
6801                .claim_due_mandates(1, "heartbeat", 300)
6802                .await
6803                .unwrap()
6804                .is_empty()
6805        );
6806        assert_eq!(
6807            store
6808                .get_mandate(&mandate.id)
6809                .await
6810                .unwrap()
6811                .unwrap()
6812                .status,
6813            MandateStatus::Completed
6814        );
6815        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
6816        assert_eq!(controller.status, "completed");
6817        assert!(controller.completed_at.is_some());
6818    }
6819
6820    #[tokio::test]
6821    async fn decision_validates_policy_version_and_commits_transition_atomically() {
6822        let (store, _database) = test_store().await;
6823        let (goal, mandate) = controller("owner-session", 2);
6824        let run = claim_and_start_run(&store, &goal, &mandate).await;
6825
6826        let stale = MandateDecisionCycle::new(
6827            &mandate.id,
6828            &run.id,
6829            MandateDecisionOutcome::Wait,
6830            "Nothing useful yet",
6831            mandate.version + 1,
6832        );
6833        assert!(
6834            store
6835                .record_mandate_decision(&stale, None, None)
6836                .await
6837                .is_err()
6838        );
6839        assert!(
6840            store
6841                .get_mandate_decision_for_run(&run.id)
6842                .await
6843                .unwrap()
6844                .is_none()
6845        );
6846        assert!(
6847            store
6848                .get_mandate(&mandate.id)
6849                .await
6850                .unwrap()
6851                .unwrap()
6852                .review_lease_token
6853                .is_some()
6854        );
6855
6856        let mut wait = MandateDecisionCycle::new(
6857            &mandate.id,
6858            &run.id,
6859            MandateDecisionOutcome::Wait,
6860            "No action clears the quality threshold",
6861            mandate.version,
6862        );
6863        wait.reconsider_at = Some((chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339());
6864        let before = chrono::Utc::now();
6865        store
6866            .record_mandate_decision(&wait, None, None)
6867            .await
6868            .unwrap();
6869
6870        let loaded = store.get_mandate(&mandate.id).await.unwrap().unwrap();
6871        assert_eq!(loaded.status, MandateStatus::Active);
6872        assert!(loaded.review_lease_token.is_none());
6873        let next = chrono::DateTime::parse_from_rfc3339(&loaded.next_review_at)
6874            .unwrap()
6875            .with_timezone(&chrono::Utc);
6876        assert!(next >= before + chrono::Duration::seconds(mandate.min_review_secs - 1));
6877        let stored_decision = store
6878            .get_mandate_decision_for_run(&run.id)
6879            .await
6880            .unwrap()
6881            .unwrap();
6882        assert_eq!(stored_decision.mandate_version, mandate.version);
6883        assert_eq!(stored_decision.reconsider_at, Some(loaded.next_review_at));
6884        let history = store.list_mandate_decisions(&mandate.id, 10).await.unwrap();
6885        assert_eq!(history.len(), 1);
6886        assert_eq!(history[0].id, stored_decision.id);
6887        assert_eq!(history[0].outcome, MandateDecisionOutcome::Wait);
6888    }
6889
6890    /// A bounded mandate's objective control is advisory: its decisions do
6891    /// not wait on a measurement. Autopilot keeps the measured control loop.
6892    #[tokio::test]
6893    async fn bounded_mandate_with_objective_control_decides_without_a_measurement() {
6894        for (mode, gated) in [
6895            (MandateAutonomyMode::Bounded, false),
6896            (MandateAutonomyMode::Autopilot, true),
6897        ] {
6898            let (store, _database) = test_store().await;
6899            let (goal, mut mandate) = controller("owner-session", 1);
6900            mandate.autonomy_mode = mode;
6901            mandate.objective_control = Some(objective_control());
6902            let run = claim_and_start_run(&store, &goal, &mandate).await;
6903            let wait = MandateDecisionCycle::new(
6904                &mandate.id,
6905                &run.id,
6906                MandateDecisionOutcome::Wait,
6907                "Nothing new is worth acting on yet",
6908                mandate.version,
6909            );
6910            let result = store.record_mandate_decision(&wait, None, None).await;
6911            if gated {
6912                let error = result.expect_err("autopilot decisions need a measurement");
6913                assert!(
6914                    error
6915                        .to_string()
6916                        .contains("receipt-backed metric measurement"),
6917                    "{error}"
6918                );
6919            } else {
6920                result.expect("a bounded mandate decides without a measurement");
6921                let stored = store
6922                    .get_mandate_decision_for_run(&run.id)
6923                    .await
6924                    .unwrap()
6925                    .expect("decision stored");
6926                assert_eq!(stored.outcome, MandateDecisionOutcome::Wait);
6927            }
6928        }
6929    }
6930
6931    #[tokio::test]
6932    async fn act_for_value_contract_requires_exact_owner_criterion_and_full_judgment() {
6933        let (store, _database) = test_store().await;
6934        let (goal, mut mandate) = controller("owner-session", 1);
6935        mandate.success_criteria = vec![
6936            "Each intervention provides verified useful information to the audience".to_string(),
6937        ];
6938        let run = claim_and_start_run(&store, &goal, &mandate).await;
6939        let act = MandateDecisionCycle::new(
6940            &mandate.id,
6941            &run.id,
6942            MandateDecisionOutcome::Act,
6943            "Current evidence supports one bounded useful intervention",
6944            mandate.version,
6945        );
6946        let mut intention = Intention::new(
6947            &mandate.id,
6948            &act.id,
6949            &run.id,
6950            "Provide one verified useful update",
6951            "The intervention advances the confirmed value criterion",
6952        );
6953        intention.value_criterion = Some("Publish something on every review".to_string());
6954        intention.expected_benefit =
6955            Some("Give the audience current, grounded information".to_string());
6956        intention.risk = Some("Low volume limits attention and reputation costs".to_string());
6957        intention.invalidation_criteria =
6958            Some("The information is stale, duplicate, or unsupported".to_string());
6959
6960        let error = store
6961            .record_mandate_decision(&act, Some(&intention), None)
6962            .await
6963            .unwrap_err();
6964        assert!(
6965            error
6966                .to_string()
6967                .contains("not an exact owner-authored success criterion")
6968        );
6969
6970        intention.value_criterion = mandate.success_criteria.first().cloned();
6971        store
6972            .record_mandate_decision(&act, Some(&intention), None)
6973            .await
6974            .unwrap();
6975        assert_eq!(
6976            store.list_intentions(&mandate.id, 1).await.unwrap()[0],
6977            intention
6978        );
6979    }
6980
6981    #[tokio::test]
6982    async fn action_reservations_require_a_unique_live_proof_and_respect_the_cycle_cap() {
6983        let (store, _database) = test_store().await;
6984        let (goal, mandate) = controller("owner-session", 2);
6985        let run = claim_and_start_run(&store, &goal, &mandate).await;
6986        let act = MandateDecisionCycle::new(
6987            &mandate.id,
6988            &run.id,
6989            MandateDecisionOutcome::Act,
6990            "A sourced reply is timely and useful",
6991            mandate.version,
6992        );
6993        let intention = Intention::new(
6994            &mandate.id,
6995            &act.id,
6996            &run.id,
6997            "Post one sourced reply",
6998            "It contributes concrete information",
6999        );
7000        store
7001            .record_mandate_decision(&act, Some(&intention), None)
7002            .await
7003            .unwrap();
7004        assert_eq!(
7005            store.list_intentions(&mandate.id, 10).await.unwrap(),
7006            vec![intention]
7007        );
7008        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7009        let now = chrono::Utc::now();
7010        let first = reservation(&mandate, &act, &run, &fence, 1, 10, now);
7011
7012        assert!(
7013            store
7014                .reserve_mandate_action_attempt(&first)
7015                .await
7016                .unwrap()
7017                .is_some()
7018        );
7019        assert!(
7020            store
7021                .reserve_mandate_action_attempt(&first)
7022                .await
7023                .unwrap()
7024                .is_none()
7025        );
7026        assert!(
7027            store
7028                .reserve_mandate_action_attempt(&reservation(
7029                    &mandate,
7030                    &act,
7031                    &run,
7032                    &fence,
7033                    2,
7034                    11,
7035                    now + chrono::Duration::seconds(901),
7036                ))
7037                .await
7038                .unwrap()
7039                .is_some()
7040        );
7041        assert!(
7042            store
7043                .reserve_mandate_action_attempt(&reservation(
7044                    &mandate,
7045                    &act,
7046                    &run,
7047                    &fence,
7048                    3,
7049                    12,
7050                    now + chrono::Duration::seconds(1_802),
7051                ))
7052                .await
7053                .unwrap()
7054                .is_none()
7055        );
7056    }
7057
7058    #[tokio::test]
7059    async fn owner_policy_update_invalidates_an_existing_action_budget() {
7060        let (store, _database) = test_store().await;
7061        let (goal, mandate) = controller("owner-session", 3);
7062        let run = claim_and_start_run(&store, &goal, &mandate).await;
7063        let act = MandateDecisionCycle::new(
7064            &mandate.id,
7065            &run.id,
7066            MandateDecisionOutcome::Act,
7067            "One action currently fits the policy",
7068            mandate.version,
7069        );
7070        let intention = Intention::new(
7071            &mandate.id,
7072            &act.id,
7073            &run.id,
7074            "Perform the authorized action",
7075            "It advances the mandate",
7076        );
7077        store
7078            .record_mandate_decision(&act, Some(&intention), None)
7079            .await
7080            .unwrap();
7081        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7082        let now = chrono::Utc::now();
7083        assert!(
7084            store
7085                .reserve_mandate_action_attempt(&reservation(
7086                    &mandate, &act, &run, &fence, 1, 20, now,
7087                ))
7088                .await
7089                .unwrap()
7090                .is_some()
7091        );
7092
7093        let mut owner_update = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7094        owner_update.version += 1;
7095        owner_update
7096            .constraints
7097            .push("New owner constraint".to_string());
7098        store.update_mandate(&owner_update).await.unwrap();
7099
7100        assert!(
7101            store
7102                .reserve_mandate_action_attempt(&reservation(
7103                    &mandate,
7104                    &act,
7105                    &run,
7106                    &fence,
7107                    2,
7108                    21,
7109                    now + chrono::Duration::seconds(901),
7110                ))
7111                .await
7112                .unwrap()
7113                .is_none()
7114        );
7115    }
7116
7117    #[tokio::test]
7118    async fn concurrent_reservations_have_one_last_slot_winner() {
7119        let (store, _database) = test_store().await;
7120        let (goal, mut mandate) = controller("owner-session", 1);
7121        mandate.authority.max_mutating_actions_per_rolling_24h = 1;
7122        let run = claim_and_start_run(&store, &goal, &mandate).await;
7123        let act = MandateDecisionCycle::new(
7124            &mandate.id,
7125            &run.id,
7126            MandateDecisionOutcome::Act,
7127            "One exact action is justified",
7128            mandate.version,
7129        );
7130        let intention = Intention::new(
7131            &mandate.id,
7132            &act.id,
7133            &run.id,
7134            "Perform exactly one action",
7135            "It tests the atomic quota fence",
7136        );
7137        store
7138            .record_mandate_decision(&act, Some(&intention), None)
7139            .await
7140            .unwrap();
7141        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7142        let now = chrono::Utc::now();
7143        let left = reservation(&mandate, &act, &run, &fence, 1, 101, now);
7144        let right = reservation(&mandate, &act, &run, &fence, 1, 102, now);
7145        let (left, right) = tokio::join!(
7146            store.reserve_mandate_action_attempt(&left),
7147            store.reserve_mandate_action_attempt(&right),
7148        );
7149        let winners = [left.unwrap(), right.unwrap()]
7150            .into_iter()
7151            .filter(Option::is_some)
7152            .count();
7153        assert_eq!(winners, 1);
7154        let attempts = store
7155            .list_mandate_mutation_attempts_for_run(&run.id)
7156            .await
7157            .unwrap();
7158        assert_eq!(attempts.len(), 1);
7159    }
7160
7161    async fn record_refused_receipt(
7162        store: &SqliteWorkStore,
7163        task_id: &str,
7164        reason_code: &str,
7165        effect: &str,
7166    ) {
7167        let data = serde_json::json!({
7168            "task_id": task_id,
7169            "receipt": {
7170                "invocation_stage": "rejected_before_dispatch",
7171                "outcome_status": "blocked",
7172                "access_denial": {"reason_code": reason_code},
7173                "semantics": {"effect": effect},
7174            },
7175        });
7176        sqlx::query(
7177            "INSERT INTO events (session_id, event_type, data, created_at, task_id)
7178             VALUES ('owner-session', 'tool_result', ?, ?, ?)",
7179        )
7180        .bind(data.to_string())
7181        .bind(chrono::Utc::now().to_rfc3339())
7182        .bind(task_id)
7183        .execute(&store.pool)
7184        .await
7185        .unwrap();
7186    }
7187
7188    /// An ACT whose worker was refused before dispatch and reported success.
7189    /// `receipt` is the refusal's (reason code, effect), when there is one.
7190    async fn finalize_refused_act(
7191        receipt: Option<(&str, &str)>,
7192    ) -> (
7193        SqliteWorkStore,
7194        tempfile::NamedTempFile,
7195        Task,
7196        GoalRun,
7197        MandateRunFinalizationResult,
7198    ) {
7199        let (store, database) = test_store().await;
7200        let (goal, mandate) = controller("owner-session", 1);
7201        let run = claim_and_start_run(&store, &goal, &mandate).await;
7202        let act = MandateDecisionCycle::new(
7203            &mandate.id,
7204            &run.id,
7205            MandateDecisionOutcome::Act,
7206            "Post one update",
7207            mandate.version,
7208        );
7209        let intention = Intention::new(&mandate.id, &act.id, &run.id, "Post", "Useful");
7210        store
7211            .record_mandate_decision(&act, Some(&intention), None)
7212            .await
7213            .unwrap();
7214        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7215        if let Some((reason_code, effect)) = receipt {
7216            record_refused_receipt(&store, &fence.worker_task.id, reason_code, effect).await;
7217        }
7218        complete_mutation_fence(&store, &fence).await;
7219        let result = store
7220            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7221                mandate_id: mandate.id.clone(),
7222                expected_mandate_version: mandate.version,
7223                goal_run_id: run.id.clone(),
7224                finalized_at: chrono::Utc::now().to_rfc3339(),
7225            })
7226            .await
7227            .unwrap();
7228        (store, database, fence.worker_task, run, result)
7229    }
7230
7231    #[tokio::test]
7232    async fn a_mutation_refused_before_dispatch_names_its_gate() {
7233        let (store, _database, worker, run, result) =
7234            finalize_refused_act(Some(("untrusted_egress_denied", "Mutation"))).await;
7235
7236        let gate = MandateDispatchGate::UntrustedContentCheck;
7237        let reason = MandateReconciliationReason::ActBlockedBeforeDispatch { gate };
7238        let MandateRunFinalizationResult::ReconciliationRequired {
7239            reason: actual,
7240            counts,
7241        } = result
7242        else {
7243            panic!("expected reconciliation, got {result:?}");
7244        };
7245        assert_eq!(actual, reason);
7246        assert_eq!(counts.mutation_reservations, 0);
7247        assert_eq!(counts.failed_or_blocked_tasks, 1, "{counts:?}");
7248
7249        let (status, blocker): (String, Option<String>) =
7250            sqlx::query_as("SELECT status, blocker FROM tasks WHERE id = ?")
7251                .bind(&worker.id)
7252                .fetch_one(&store.pool)
7253                .await
7254                .unwrap();
7255        assert_eq!(status, "blocked");
7256        assert!(
7257            blocker.unwrap().contains(gate.owner_label()),
7258            "the task records its gate"
7259        );
7260        let outcome: String =
7261            sqlx::query_scalar("SELECT outcome_summary FROM goal_runs WHERE id = ?")
7262                .bind(&run.id)
7263                .fetch_one(&store.pool)
7264                .await
7265                .unwrap();
7266        assert_eq!(
7267            outcome,
7268            "mandate_reconciliation_required:act_blocked_before_dispatch:untrusted_content_check"
7269        );
7270    }
7271
7272    /// Without a refused mutation on a receipt there is no gate to name: a
7273    /// refused read, or no receipt at all, leaves an ACT whose ledger proves
7274    /// it changed nothing, which is retried without asking the owner.
7275    #[tokio::test]
7276    async fn only_a_refused_mutation_counts_as_blocked_before_dispatch() {
7277        for receipt in [None, Some(("untrusted_egress_denied", "ReadOnly"))] {
7278            let (store, _database, worker, run, result) = finalize_refused_act(receipt).await;
7279            assert_eq!(
7280                result,
7281                MandateRunFinalizationResult::Rejected {
7282                    reason: MandateFinalizationRejectReason::ActChangedNothing,
7283                },
7284                "{receipt:?}"
7285            );
7286            let (mandate_status, intention_status): (String, String) = sqlx::query_as(
7287                "SELECT m.status, i.status FROM goal_runs r
7288                 JOIN mandates m ON m.goal_id = r.goal_id
7289                 JOIN intentions i ON i.goal_run_id = r.id
7290                 WHERE r.id = ?",
7291            )
7292            .bind(&run.id)
7293            .fetch_one(&store.pool)
7294            .await
7295            .unwrap();
7296            assert_eq!(mandate_status, "active", "no owner reconciliation");
7297            assert_eq!(intention_status, "failed");
7298            let status: String = sqlx::query_scalar("SELECT status FROM tasks WHERE id = ?")
7299                .bind(&worker.id)
7300                .fetch_one(&store.pool)
7301                .await
7302                .unwrap();
7303            assert_eq!(status, "completed");
7304        }
7305    }
7306
7307    #[test]
7308    fn the_owner_notice_names_the_gate_and_says_nothing_went_out() {
7309        let notice = crate::traits::MandateRunNotification::new(
7310            "mandate-synthetic",
7311            1,
7312            "goal-synthetic",
7313            "run-synthetic",
7314            "owner-session",
7315            crate::traits::MandateRunNotificationKind::ReconciliationRequired {
7316                reason: MandateReconciliationReason::ActBlockedBeforeDispatch {
7317                    gate: MandateDispatchGate::UntrustedContentCheck,
7318                },
7319            },
7320            MandateRunProofCounts::default(),
7321            "2026-11-10T00:00:00Z",
7322        );
7323
7324        let message = notice.message();
7325
7326        assert!(message.contains("nothing was published"), "{message}");
7327        assert!(
7328            message.contains("untrusted-content safety check"),
7329            "{message}"
7330        );
7331    }
7332
7333    #[tokio::test]
7334    async fn proof_distinguishes_never_dispatched_from_claimed_ambiguity() {
7335        for claim_before_finalization in [false, true] {
7336            let (store, _database) = test_store().await;
7337            let (goal, mandate) = controller("owner-session", 1);
7338            let run = claim_and_start_run(&store, &goal, &mandate).await;
7339            let act = MandateDecisionCycle::new(
7340                &mandate.id,
7341                &run.id,
7342                MandateDecisionOutcome::Act,
7343                "Exercise the finalizer crash-window classification",
7344                mandate.version,
7345            );
7346            let intention = Intention::new(
7347                &mandate.id,
7348                &act.id,
7349                &run.id,
7350                "Attempt one governed mutation",
7351                "The proof must classify its exact dispatch state",
7352            );
7353            store
7354                .record_mandate_decision(&act, Some(&intention), None)
7355                .await
7356                .unwrap();
7357            let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
7358            let now = chrono::Utc::now();
7359            let reserved = reservation(&mandate, &act, &run, &fence, 1, 451, now);
7360            assert!(
7361                store
7362                    .reserve_mandate_action_attempt(&reserved)
7363                    .await
7364                    .unwrap()
7365                    .is_some()
7366            );
7367            if claim_before_finalization {
7368                assert!(
7369                    store
7370                        .claim_mandate_mutation_dispatch(&dispatch_claim(
7371                            &reserved,
7372                            now + chrono::Duration::milliseconds(1),
7373                        ))
7374                        .await
7375                        .unwrap()
7376                );
7377            }
7378            complete_mutation_fence(&store, &fence).await;
7379
7380            let result = store
7381                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7382                    mandate_id: mandate.id.clone(),
7383                    expected_mandate_version: mandate.version,
7384                    goal_run_id: run.id.clone(),
7385                    finalized_at: (now + chrono::Duration::seconds(1)).to_rfc3339(),
7386                })
7387                .await
7388                .unwrap();
7389            if claim_before_finalization {
7390                let MandateRunFinalizationResult::ReconciliationRequired { reason, counts } =
7391                    result
7392                else {
7393                    panic!("a claimed dispatch with no outcome must fail closed: {result:?}")
7394                };
7395                assert_eq!(
7396                    reason,
7397                    MandateReconciliationReason::MutationOutcomeAmbiguous
7398                );
7399                assert_eq!(counts.ambiguous_or_reserved_mutations, 1);
7400                assert_eq!(counts.never_dispatched_mutations, 0);
7401            } else {
7402                // Reserved but never dispatched: provably no effect.
7403                assert_eq!(
7404                    result,
7405                    MandateRunFinalizationResult::Rejected {
7406                        reason: MandateFinalizationRejectReason::ActChangedNothing,
7407                    }
7408                );
7409            }
7410            let attempts = store
7411                .list_mandate_mutation_attempts_for_run(&run.id)
7412                .await
7413                .unwrap();
7414            assert_eq!(attempts.len(), 1);
7415            assert_eq!(
7416                attempts[0].status,
7417                if claim_before_finalization {
7418                    MandateMutationAttemptStatus::Ambiguous
7419                } else {
7420                    MandateMutationAttemptStatus::NeverDispatched
7421                }
7422            );
7423        }
7424    }
7425
7426    #[tokio::test]
7427    async fn evidence_receipts_accept_either_tool_call_id_or_receipt_result_id() {
7428        let (store, _database) = test_store().await;
7429        let (goal, mut mandate) = controller("owner-session", 1);
7430        mandate.objective_control = Some(objective_control());
7431        let run = claim_and_start_run(&store, &goal, &mandate).await;
7432        let task_id = run.root_task_id.as_deref().unwrap();
7433        sqlx::query(
7434            "INSERT INTO events
7435                (session_id, event_type, data, created_at, task_id, tool_name)
7436             VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
7437        )
7438        .bind("owner-session")
7439        .bind(
7440            serde_json::json!({
7441                "task_id": task_id,
7442                "tool_call_id": "call_synthetic_metric",
7443                "name": "http_request",
7444                "result": "synthetic metric value",
7445                "success": true,
7446                "duration_ms": 1,
7447                "receipt": {
7448                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
7449                    "outcome_status": "succeeded",
7450                    "outcome_evidence": "structured_metadata",
7451                    "result_provenance": { "result_id": "sha256:synthetic-metric-digest" }
7452                }
7453            })
7454            .to_string(),
7455        )
7456        .bind(chrono::Utc::now().to_rfc3339())
7457        .bind(task_id)
7458        .execute(&store.pool)
7459        .await
7460        .unwrap();
7461
7462        for receipt_id in ["call_synthetic_metric", "sha256:synthetic-metric-digest"] {
7463            let measurement = MandateObjectiveMeasurement::new(
7464                &mandate.id,
7465                mandate.version,
7466                &run.id,
7467                12_000_000,
7468                9_500,
7469                vec![receipt_id.to_string()],
7470                &chrono::Utc::now().to_rfc3339(),
7471            );
7472            store
7473                .record_mandate_objective_measurement(&measurement)
7474                .await
7475                .unwrap_or_else(|error| panic!("{receipt_id} should be accepted: {error}"));
7476        }
7477        let invented = MandateObjectiveMeasurement::new(
7478            &mandate.id,
7479            mandate.version,
7480            &run.id,
7481            12_000_000,
7482            9_500,
7483            vec!["sha256:not-a-receipt".to_string()],
7484            &chrono::Utc::now().to_rfc3339(),
7485        );
7486        assert!(
7487            store
7488                .record_mandate_objective_measurement(&invented)
7489                .await
7490                .is_err()
7491        );
7492    }
7493
7494    #[tokio::test]
7495    async fn runtime_fallback_wait_bypasses_semantic_gates_and_finalizes_as_deliberator_failure() {
7496        let (store, _database) = test_store().await;
7497        let (goal, mut mandate) = controller("owner-session", 1);
7498        // The measured control loop (gate, stagnation) is autopilot's.
7499        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
7500        mandate.objective_control = Some(objective_control());
7501        let run = claim_and_start_run(&store, &goal, &mandate).await;
7502
7503        // A model-authored WAIT on a controlled mandate still needs a
7504        // current-run measurement.
7505        let model_wait = MandateDecisionCycle::new(
7506            &mandate.id,
7507            &run.id,
7508            MandateDecisionOutcome::Wait,
7509            "model decided to wait without measuring",
7510            mandate.version,
7511        );
7512        let error = store
7513            .record_mandate_decision(&model_wait, None, None)
7514            .await
7515            .unwrap_err();
7516        assert!(error.to_string().contains("metric measurement"), "{error}");
7517
7518        // The runtime fallback carries no authority and must always persist,
7519        // regardless of objective control state.
7520        let fallback =
7521            MandateDecisionCycle::runtime_fallback_wait(&mandate, &run.id, chrono::Utc::now());
7522        assert!(fallback.is_runtime_fallback());
7523        store
7524            .record_mandate_decision(&fallback, None, None)
7525            .await
7526            .unwrap();
7527        let mut spoofed = fallback.clone();
7528        spoofed.id = uuid::Uuid::new_v4().to_string();
7529        spoofed.evidence_receipt_ids = vec!["call_anything".to_string()];
7530        assert!(
7531            store
7532                .record_mandate_decision(&spoofed, None, None)
7533                .await
7534                .is_err()
7535        );
7536
7537        let root_attempt = store
7538            .claim_task_with_lease(
7539                run.root_task_id.as_deref().unwrap(),
7540                "fallback-root",
7541                Some("profile-task-lead"),
7542                7_200,
7543            )
7544            .await
7545            .unwrap()
7546            .unwrap();
7547        assert!(
7548            store
7549                .patch_task_from_attempt(
7550                    &root_attempt.id,
7551                    &root_attempt.lease_token,
7552                    &crate::traits::TaskAttemptPatch {
7553                        status: "completed".to_string(),
7554                        result: Some("task lead returned without a decision".to_string()),
7555                        ..Default::default()
7556                    },
7557                )
7558                .await
7559                .unwrap()
7560        );
7561        let result = store
7562            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7563                mandate_id: mandate.id.clone(),
7564                expected_mandate_version: mandate.version,
7565                goal_run_id: run.id.clone(),
7566                finalized_at: chrono::Utc::now().to_rfc3339(),
7567            })
7568            .await
7569            .unwrap();
7570        assert_eq!(
7571            result,
7572            MandateRunFinalizationResult::Rejected {
7573                reason: MandateFinalizationRejectReason::DeliberatorFailed
7574            }
7575        );
7576        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7577        assert_eq!(current.status, MandateStatus::Active);
7578        assert_eq!(
7579            store.get_goal_runs(&goal.id).await.unwrap()[0]
7580                .outcome_summary
7581                .as_deref(),
7582            Some("mandate_review_failed:deliberator_failed")
7583        );
7584    }
7585
7586    #[tokio::test]
7587    async fn missing_decision_closes_run_schedules_retry_and_commits_review_failed_notice() {
7588        let (store, _database) = test_store().await;
7589        let (goal, mandate) = controller("owner-session", 1);
7590        let run = claim_and_start_run(&store, &goal, &mandate).await;
7591        let root_attempt = store
7592            .claim_task_with_lease(
7593                run.root_task_id.as_deref().unwrap(),
7594                "decision-missing-root",
7595                Some("profile-task-lead"),
7596                7_200,
7597            )
7598            .await
7599            .unwrap()
7600            .unwrap();
7601        assert!(
7602            store
7603                .patch_task_from_attempt(
7604                    &root_attempt.id,
7605                    &root_attempt.lease_token,
7606                    &crate::traits::TaskAttemptPatch {
7607                        status: "completed".to_string(),
7608                        result: Some("task lead returned without a decision".to_string()),
7609                        ..Default::default()
7610                    },
7611                )
7612                .await
7613                .unwrap()
7614        );
7615        let finalized_at = chrono::Utc::now();
7616
7617        let result = store
7618            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7619                mandate_id: mandate.id.clone(),
7620                expected_mandate_version: mandate.version,
7621                goal_run_id: run.id.clone(),
7622                finalized_at: finalized_at.to_rfc3339(),
7623            })
7624            .await
7625            .unwrap();
7626        assert_eq!(
7627            result,
7628            MandateRunFinalizationResult::Rejected {
7629                reason: MandateFinalizationRejectReason::DecisionMissing
7630            }
7631        );
7632        assert_eq!(
7633            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
7634            "failed"
7635        );
7636        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
7637        assert_eq!(current.status, MandateStatus::Active);
7638        assert!(
7639            chrono::DateTime::parse_from_rfc3339(&current.next_review_at)
7640                .unwrap()
7641                .with_timezone(&chrono::Utc)
7642                >= finalized_at + chrono::Duration::seconds(mandate.min_review_secs)
7643        );
7644        let controller = store.get_goal(&goal.id).await.unwrap().unwrap();
7645        assert_eq!(controller.status, "active");
7646        assert_eq!(controller.dispatch_failures, 1);
7647        let queued: i64 = sqlx::query_scalar(
7648            "SELECT COUNT(*) FROM notification_queue
7649             WHERE id = ? AND notification_type = 'mandate_review_failed'
7650               AND priority = 'critical' AND expires_at IS NULL",
7651        )
7652        .bind(format!("mandate-run-notice:{}", run.id))
7653        .fetch_one(&store.pool)
7654        .await
7655        .unwrap();
7656        assert_eq!(queued, 1);
7657    }
7658
7659    #[tokio::test]
7660    async fn invalid_decision_state_pauses_controller_and_commits_review_failed_notice() {
7661        let (store, _database) = test_store().await;
7662        let (goal, mandate) = controller("owner-session", 1);
7663        let run = claim_and_start_run(&store, &goal, &mandate).await;
7664        let root_attempt = store
7665            .claim_task_with_lease(
7666                run.root_task_id.as_deref().unwrap(),
7667                "invalid-decision-root",
7668                Some("profile-task-lead"),
7669                7_200,
7670            )
7671            .await
7672            .unwrap()
7673            .unwrap();
7674        let decision = MandateDecisionCycle::new(
7675            &mandate.id,
7676            &run.id,
7677            MandateDecisionOutcome::Act,
7678            "Persist a valid row before simulating corruption",
7679            mandate.version,
7680        );
7681        let intention = Intention::new(
7682            &mandate.id,
7683            &decision.id,
7684            &run.id,
7685            "A committed intention that cannot belong to WAIT",
7686            "It creates a valid but inconsistent persisted decision state",
7687        );
7688        store
7689            .record_mandate_decision(&decision, Some(&intention), Some(&root_attempt.id))
7690            .await
7691            .unwrap();
7692        sqlx::query("UPDATE mandate_decision_cycles SET outcome = 'wait' WHERE id = ?")
7693            .bind(&decision.id)
7694            .execute(&store.pool)
7695            .await
7696            .unwrap();
7697        assert!(
7698            store
7699                .patch_task_from_attempt(
7700                    &root_attempt.id,
7701                    &root_attempt.lease_token,
7702                    &crate::traits::TaskAttemptPatch {
7703                        status: "completed".to_string(),
7704                        result: Some("invalid decision state simulated".to_string()),
7705                        ..Default::default()
7706                    },
7707                )
7708                .await
7709                .unwrap()
7710        );
7711
7712        let result = store
7713            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7714                mandate_id: mandate.id.clone(),
7715                expected_mandate_version: mandate.version,
7716                goal_run_id: run.id.clone(),
7717                finalized_at: chrono::Utc::now().to_rfc3339(),
7718            })
7719            .await
7720            .unwrap();
7721        assert_eq!(
7722            result,
7723            MandateRunFinalizationResult::Rejected {
7724                reason: MandateFinalizationRejectReason::InvalidDecisionState
7725            }
7726        );
7727        assert_eq!(
7728            store
7729                .get_mandate(&mandate.id)
7730                .await
7731                .unwrap()
7732                .unwrap()
7733                .status,
7734            MandateStatus::AwaitingInput
7735        );
7736        assert_eq!(
7737            store.get_goal(&goal.id).await.unwrap().unwrap().status,
7738            "paused"
7739        );
7740        assert_eq!(
7741            store.get_goal_runs(&goal.id).await.unwrap()[0].status,
7742            "failed"
7743        );
7744        let queued: i64 = sqlx::query_scalar(
7745            "SELECT COUNT(*) FROM notification_queue
7746             WHERE id = ? AND notification_type = 'mandate_review_failed'
7747               AND priority = 'critical' AND expires_at IS NULL",
7748        )
7749        .bind(format!("mandate-run-notice:{}", run.id))
7750        .fetch_one(&store.pool)
7751        .await
7752        .unwrap();
7753        assert_eq!(queued, 1);
7754    }
7755
7756    #[tokio::test]
7757    async fn ask_and_stop_atomically_change_mandate_and_controller_status() {
7758        for (outcome, expected_mandate, expected_goal) in [
7759            (
7760                MandateDecisionOutcome::Ask,
7761                MandateStatus::AwaitingInput,
7762                "paused",
7763            ),
7764            (
7765                MandateDecisionOutcome::Stop,
7766                MandateStatus::Completed,
7767                "completed",
7768            ),
7769        ] {
7770            let (store, _database) = test_store().await;
7771            let (goal, mandate) = controller("owner-session", 1);
7772            let run = claim_and_start_run(&store, &goal, &mandate).await;
7773            let root_attempt = store
7774                .claim_task_with_lease(
7775                    run.root_task_id.as_deref().unwrap(),
7776                    "non-action-root",
7777                    Some("profile-task-lead"),
7778                    7_200,
7779                )
7780                .await
7781                .unwrap()
7782                .unwrap();
7783            let mut decision = MandateDecisionCycle::new(
7784                &mandate.id,
7785                &run.id,
7786                outcome,
7787                "The mandate cannot safely proceed",
7788                mandate.version,
7789            );
7790            if outcome == MandateDecisionOutcome::Ask {
7791                decision.question = Some("May I broaden the allowed target?".to_string());
7792            } else {
7793                decision.termination_kind = Some(MandateTerminationKind::SafetyTermination);
7794            }
7795            store
7796                .record_mandate_decision(&decision, None, Some(&root_attempt.id))
7797                .await
7798                .unwrap();
7799            assert_eq!(
7800                store
7801                    .get_mandate(&mandate.id)
7802                    .await
7803                    .unwrap()
7804                    .unwrap()
7805                    .status,
7806                MandateStatus::Active,
7807                "the lifecycle transition remains provisional until proof finalization"
7808            );
7809            assert_eq!(
7810                store.get_goal(&goal.id).await.unwrap().unwrap().status,
7811                "active"
7812            );
7813            assert!(
7814                store
7815                    .patch_task_from_attempt(
7816                        &root_attempt.id,
7817                        &root_attempt.lease_token,
7818                        &crate::traits::TaskAttemptPatch {
7819                            status: "completed".to_string(),
7820                            result: Some("non-action decision durably recorded".to_string()),
7821                            ..Default::default()
7822                        },
7823                    )
7824                    .await
7825                    .unwrap()
7826            );
7827            let result = store
7828                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7829                    mandate_id: mandate.id.clone(),
7830                    expected_mandate_version: mandate.version,
7831                    goal_run_id: run.id.clone(),
7832                    finalized_at: chrono::Utc::now().to_rfc3339(),
7833                })
7834                .await
7835                .unwrap();
7836            assert!(matches!(
7837                result,
7838                MandateRunFinalizationResult::NonActionSatisfied {
7839                    outcome: finalized_outcome,
7840                    ..
7841                } if finalized_outcome == outcome
7842            ));
7843            assert_eq!(
7844                store
7845                    .get_mandate(&mandate.id)
7846                    .await
7847                    .unwrap()
7848                    .unwrap()
7849                    .status,
7850                expected_mandate
7851            );
7852            assert_eq!(
7853                store.get_goal(&goal.id).await.unwrap().unwrap().status,
7854                expected_goal
7855            );
7856        }
7857    }
7858
7859    #[tokio::test]
7860    async fn receipt_backed_stop_and_learning_are_same_mandate_only() {
7861        let (store, _database) = test_store().await;
7862        let (goal, mut mandate) = controller("owner-session", 0);
7863        mandate.success_criteria = vec!["Account stewardship is no longer needed".to_string()];
7864        let run = claim_and_start_run(&store, &goal, &mandate).await;
7865        let root_task_id = run.root_task_id.as_deref().unwrap();
7866        let root_attempt = store
7867            .claim_task_with_lease(
7868                root_task_id,
7869                "receipt-backed-stop",
7870                Some("profile-task-lead"),
7871                7_200,
7872            )
7873            .await
7874            .unwrap()
7875            .unwrap();
7876
7877        let receipt = aidaemon_events::ToolReceiptV1::from_metadata(
7878            &crate::traits::ToolCallMetadata {
7879                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
7880                semantics: crate::traits::ToolCallSemantics::observation(),
7881                ..Default::default()
7882            },
7883            crate::traits::ToolOutcomeStatus::Succeeded,
7884            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
7885            None,
7886        );
7887        let result = aidaemon_events::ToolResultData {
7888            message_id: None,
7889            tool_call_id: "observation-receipt-1".to_string(),
7890            name: "web_fetch".to_string(),
7891            result: "bounded observation".to_string(),
7892            success: true,
7893            duration_ms: 1,
7894            error: None,
7895            task_id: Some(root_task_id.to_string()),
7896            annotations: vec![],
7897            turn_id: None,
7898            attachments: vec![],
7899            receipt: Some(receipt),
7900        };
7901        sqlx::query(
7902            "INSERT INTO events (session_id, event_type, data, created_at, task_id, tool_name)
7903             VALUES (?, 'tool_result', ?, ?, ?, 'web_fetch')",
7904        )
7905        .bind("specialist:mandate")
7906        .bind(serde_json::to_string(&result).unwrap())
7907        .bind(chrono::Utc::now().to_rfc3339())
7908        .bind(root_task_id)
7909        .execute(&store.pool)
7910        .await
7911        .unwrap();
7912
7913        let mut decision = MandateDecisionCycle::new(
7914            &mandate.id,
7915            &run.id,
7916            MandateDecisionOutcome::Stop,
7917            "A current structured observation proves the owner criterion",
7918            mandate.version,
7919        );
7920        decision.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
7921        decision.activity_level = MandateActivityLevel::Urgent;
7922        decision.termination_match = mandate.success_criteria.first().cloned();
7923        decision.evidence_receipt_ids = vec!["observation-receipt-1".to_string()];
7924        let note = MandateLearningNote::new(
7925            &mandate.id,
7926            mandate.version,
7927            &decision.id,
7928            "Explicit verification is more reliable than inferred completion",
7929            vec!["observation-receipt-1".to_string()],
7930        );
7931        store
7932            .record_mandate_decision_with_updates(
7933                &decision,
7934                None,
7935                Some(&MandateOperatingUpdates {
7936                    learning_note: Some(note.clone()),
7937                }),
7938                Some(&root_attempt.id),
7939            )
7940            .await
7941            .unwrap();
7942        assert_eq!(
7943            store
7944                .list_mandate_learning_notes(&mandate.id, 10)
7945                .await
7946                .unwrap(),
7947            vec![note]
7948        );
7949        assert_eq!(
7950            store
7951                .get_mandate_decision_for_run(&run.id)
7952                .await
7953                .unwrap()
7954                .unwrap()
7955                .activity_level,
7956            MandateActivityLevel::Urgent
7957        );
7958
7959        assert!(
7960            store
7961                .patch_task_from_attempt(
7962                    &root_attempt.id,
7963                    &root_attempt.lease_token,
7964                    &crate::traits::TaskAttemptPatch {
7965                        status: "completed".to_string(),
7966                        result: Some("receipt-backed STOP recorded".to_string()),
7967                        ..Default::default()
7968                    },
7969                )
7970                .await
7971                .unwrap()
7972        );
7973        let finalized = store
7974            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
7975                mandate_id: mandate.id.clone(),
7976                expected_mandate_version: mandate.version,
7977                goal_run_id: run.id,
7978                finalized_at: chrono::Utc::now().to_rfc3339(),
7979            })
7980            .await
7981            .unwrap();
7982        assert!(matches!(
7983            finalized,
7984            MandateRunFinalizationResult::NonActionSatisfied {
7985                outcome: MandateDecisionOutcome::Stop,
7986                ..
7987            }
7988        ));
7989    }
7990
7991    #[tokio::test]
7992    async fn ask_and_stop_crashes_remain_reconcilable_until_proof_finalization() {
7993        for outcome in [MandateDecisionOutcome::Ask, MandateDecisionOutcome::Stop] {
7994            let (store, _database) = test_store().await;
7995            let (goal, mandate) = controller("owner-session", 1);
7996            let run = claim_and_start_run(&store, &goal, &mandate).await;
7997            let root_attempt = store
7998                .claim_task_with_lease(
7999                    run.root_task_id.as_deref().unwrap(),
8000                    "crashing-non-action-root",
8001                    Some("profile-task-lead"),
8002                    7_200,
8003                )
8004                .await
8005                .unwrap()
8006                .unwrap();
8007            let mut decision = MandateDecisionCycle::new(
8008                &mandate.id,
8009                &run.id,
8010                outcome,
8011                "Record the non-action decision before the simulated crash",
8012                mandate.version,
8013            );
8014            if outcome == MandateDecisionOutcome::Ask {
8015                decision.question = Some("May I broaden the exact target?".to_string());
8016            } else {
8017                decision.termination_kind = Some(MandateTerminationKind::SafetyTermination);
8018            }
8019            store
8020                .record_mandate_decision(&decision, None, Some(&root_attempt.id))
8021                .await
8022                .unwrap();
8023            assert_eq!(
8024                store
8025                    .get_mandate(&mandate.id)
8026                    .await
8027                    .unwrap()
8028                    .unwrap()
8029                    .status,
8030                MandateStatus::Active
8031            );
8032            sqlx::query("UPDATE task_attempts SET lease_expires_at = ? WHERE id = ?")
8033                .bind((chrono::Utc::now() - chrono::Duration::seconds(1)).to_rfc3339())
8034                .bind(&root_attempt.id)
8035                .execute(&store.pool)
8036                .await
8037                .unwrap();
8038
8039            assert!(
8040                store
8041                    .claim_due_mandates(1, "post-crash-reconciler", 300)
8042                    .await
8043                    .unwrap()
8044                    .is_empty()
8045            );
8046            assert_eq!(
8047                store
8048                    .get_mandate(&mandate.id)
8049                    .await
8050                    .unwrap()
8051                    .unwrap()
8052                    .status,
8053                MandateStatus::AwaitingInput
8054            );
8055            assert_eq!(
8056                store.get_goal(&goal.id).await.unwrap().unwrap().status,
8057                "paused"
8058            );
8059            assert_eq!(
8060                store.get_goal_runs(&goal.id).await.unwrap()[0].status,
8061                "cancelled"
8062            );
8063        }
8064    }
8065
8066    #[tokio::test]
8067    async fn mandate_schema_and_rows_survive_an_idempotent_reopen() {
8068        let (store, database) = test_store().await;
8069        let (goal, mandate) = controller("owner-session", 1);
8070        store
8071            .create_mandate_controller(&goal, &mandate)
8072            .await
8073            .unwrap();
8074        store.pool.close().await;
8075        drop(store);
8076
8077        let reopened = open_for_tests(database.path().to_str().unwrap()).await;
8078        let loaded = reopened.get_mandate(&mandate.id).await.unwrap().unwrap();
8079        assert_eq!(loaded.goal_id, goal.id);
8080        assert_eq!(loaded.version, mandate.version);
8081        assert_eq!(loaded.next_review_at, mandate.next_review_at);
8082    }
8083
8084    /// Seed one objective reading on a closed prior review run, as the
8085    /// history of an earlier cycle would leave it.
8086    async fn seed_prior_measurement(
8087        store: &SqliteWorkStore,
8088        mandate: &Mandate,
8089        current_run: &GoalRun,
8090        value_micros: i64,
8091        confidence_bps: i64,
8092        hours_ago: i64,
8093    ) {
8094        let run_id = uuid::Uuid::new_v4().to_string();
8095        sqlx::query(
8096            "INSERT INTO goal_runs (id, project_id, goal_id, trigger_type, status)
8097             SELECT ?, project_id, goal_id, 'mandate', 'completed' FROM goal_runs WHERE id = ?",
8098        )
8099        .bind(&run_id)
8100        .bind(&current_run.id)
8101        .execute(&store.pool)
8102        .await
8103        .unwrap();
8104        seed_measurement_on_run(
8105            store,
8106            mandate,
8107            &run_id,
8108            value_micros,
8109            confidence_bps,
8110            hours_ago,
8111        )
8112        .await;
8113    }
8114
8115    async fn seed_measurement_on_run(
8116        store: &SqliteWorkStore,
8117        mandate: &Mandate,
8118        run_id: &str,
8119        value_micros: i64,
8120        confidence_bps: i64,
8121        hours_ago: i64,
8122    ) {
8123        let observed_at = (chrono::Utc::now() - chrono::Duration::hours(hours_ago)).to_rfc3339();
8124        sqlx::query(
8125            "INSERT INTO mandate_objective_measurements
8126                (id, mandate_id, mandate_version, goal_run_id, value_micros, confidence_bps,
8127                 evidence_receipt_ids_json, attributed_intention_ids_json, observed_at, created_at)
8128             VALUES (?, ?, ?, ?, ?, ?, '[\"call_synthetic_seed\"]', '[]', ?, ?)",
8129        )
8130        .bind(uuid::Uuid::new_v4().to_string())
8131        .bind(&mandate.id)
8132        .bind(mandate.version)
8133        .bind(run_id)
8134        .bind(value_micros)
8135        .bind(confidence_bps)
8136        .bind(&observed_at)
8137        .bind(&observed_at)
8138        .execute(&store.pool)
8139        .await
8140        .unwrap();
8141    }
8142
8143    /// Measurements are read, not judged: flat (or unreadable) readings
8144    /// never refuse a WAIT; whether to change course is the reviewer's call.
8145    #[tokio::test]
8146    async fn flat_measurements_never_refuse_a_wait() {
8147        let (store, _database) = test_store().await;
8148        let (goal, mut mandate) = controller("owner-session", 1);
8149        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
8150        mandate.objective_control = Some(objective_control());
8151        let run = claim_and_start_run(&store, &goal, &mandate).await;
8152        for hours_ago in 2..=5 {
8153            seed_prior_measurement(&store, &mandate, &run, 10_000_000, 9_000, hours_ago).await;
8154        }
8155        seed_prior_measurement(&store, &mandate, &run, 0, 0, 1).await;
8156        seed_measurement_on_run(&store, &mandate, &run.id, 10_000_000, 9_000, 0).await;
8157
8158        let wait = MandateDecisionCycle::new(
8159            &mandate.id,
8160            &run.id,
8161            MandateDecisionOutcome::Wait,
8162            "no change observed",
8163            mandate.version,
8164        );
8165        store
8166            .record_mandate_decision(&wait, None, None)
8167            .await
8168            .expect("a flat metric must not force the mandate out of WAIT");
8169    }
8170
8171    #[tokio::test]
8172    async fn success_stop_requires_a_credible_current_measurement() {
8173        let (store, _database) = test_store().await;
8174        let (goal, mut mandate) = controller("owner-session", 1);
8175        // STOP on target is part of autopilot's measured control loop.
8176        mandate.autonomy_mode = MandateAutonomyMode::Autopilot;
8177        let control = objective_control();
8178        let target = control.target_micros;
8179        mandate.objective_control = Some(control);
8180        mandate.success_criteria = vec!["Synthetic interactions reach the target".to_string()];
8181        let run = claim_and_start_run(&store, &goal, &mandate).await;
8182        seed_measurement_on_run(&store, &mandate, &run.id, target, 0, 0).await;
8183
8184        let mut stop = MandateDecisionCycle::new(
8185            &mandate.id,
8186            &run.id,
8187            MandateDecisionOutcome::Stop,
8188            "target reached",
8189            mandate.version,
8190        );
8191        stop.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
8192        stop.termination_match = Some("Synthetic interactions reach the target".to_string());
8193        stop.evidence_receipt_ids = vec![];
8194        let error = store
8195            .record_mandate_decision(&stop, None, None)
8196            .await
8197            .unwrap_err();
8198        assert!(error.to_string().contains("credible"), "{error}");
8199    }
8200
8201    /// A bounded mandate's advisory control does not gate a success STOP on
8202    /// a target-reaching measurement; the owner criterion match still does.
8203    #[tokio::test]
8204    async fn bounded_success_stop_does_not_require_a_target_measurement() {
8205        let (store, _database) = test_store().await;
8206        let (goal, mut mandate) = controller("owner-session", 1);
8207        mandate.objective_control = Some(objective_control());
8208        mandate.success_criteria = vec!["One grounded note is posted".to_string()];
8209        let run = claim_and_start_run(&store, &goal, &mandate).await;
8210        let mut stop = MandateDecisionCycle::new(
8211            &mandate.id,
8212            &run.id,
8213            MandateDecisionOutcome::Stop,
8214            "the note is posted",
8215            mandate.version,
8216        );
8217        stop.termination_kind = Some(MandateTerminationKind::SuccessCriteriaSatisfied);
8218        stop.termination_match = Some("One grounded note is posted".to_string());
8219        let root_task_id = run.root_task_id.clone().expect("review root task");
8220        let receipt = aidaemon_events::ToolReceiptV1::from_metadata(
8221            &crate::traits::ToolCallMetadata {
8222                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
8223                semantics: crate::traits::ToolCallSemantics::observation(),
8224                ..Default::default()
8225            },
8226            crate::traits::ToolOutcomeStatus::Succeeded,
8227            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
8228            None,
8229        );
8230        let result = aidaemon_events::ToolResultData {
8231            message_id: None,
8232            tool_call_id: "call_read_notes".to_string(),
8233            name: "http_request".to_string(),
8234            result: "one note posted".to_string(),
8235            success: true,
8236            duration_ms: 1,
8237            error: None,
8238            task_id: Some(root_task_id.clone()),
8239            annotations: vec![],
8240            turn_id: None,
8241            attachments: vec![],
8242            receipt: Some(receipt),
8243        };
8244        sqlx::query(
8245            "INSERT INTO events (session_id, event_type, data, created_at, task_id, tool_name)
8246             VALUES ('specialist:mandate', 'tool_result', ?, ?, ?, 'http_request')",
8247        )
8248        .bind(serde_json::to_string(&result).unwrap())
8249        .bind(chrono::Utc::now().to_rfc3339())
8250        .bind(&root_task_id)
8251        .execute(&store.pool)
8252        .await
8253        .unwrap();
8254        stop.evidence_receipt_ids = vec!["call_read_notes".to_string()];
8255        store
8256            .record_mandate_decision(&stop, None, None)
8257            .await
8258            .expect("a bounded mandate stops on its criterion");
8259    }
8260
8261    /// Drive one review to a finalized ASK exactly as the task lead would,
8262    /// leaving the mandate parked in `awaiting_input` with its question.
8263    async fn park_mandate_on_ask(
8264        store: &SqliteWorkStore,
8265        goal: &Goal,
8266        mandate: &Mandate,
8267        question: &str,
8268    ) -> GoalRun {
8269        let run = claim_and_start_run(store, goal, mandate).await;
8270        let root_attempt = store
8271            .claim_task_with_lease(
8272                run.root_task_id.as_deref().unwrap(),
8273                "ask-root",
8274                Some("profile-task-lead"),
8275                7_200,
8276            )
8277            .await
8278            .unwrap()
8279            .unwrap();
8280        let mut decision = MandateDecisionCycle::new(
8281            &mandate.id,
8282            &run.id,
8283            MandateDecisionOutcome::Ask,
8284            "owner judgment requested",
8285            mandate.version,
8286        );
8287        decision.question = Some(question.to_string());
8288        store
8289            .record_mandate_decision(&decision, None, Some(&root_attempt.id))
8290            .await
8291            .unwrap();
8292        assert!(
8293            store
8294                .patch_task_from_attempt(
8295                    &root_attempt.id,
8296                    &root_attempt.lease_token,
8297                    &crate::traits::TaskAttemptPatch {
8298                        status: "completed".to_string(),
8299                        result: Some("ASK recorded".to_string()),
8300                        ..Default::default()
8301                    },
8302                )
8303                .await
8304                .unwrap()
8305        );
8306        store
8307            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
8308                mandate_id: mandate.id.clone(),
8309                expected_mandate_version: mandate.version,
8310                goal_run_id: run.id.clone(),
8311                finalized_at: chrono::Utc::now().to_rfc3339(),
8312            })
8313            .await
8314            .unwrap();
8315        let parked = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8316        assert_eq!(parked.status, MandateStatus::AwaitingInput);
8317        run
8318    }
8319
8320    async fn make_review_due(store: &SqliteWorkStore, mandate: &Mandate) {
8321        sqlx::query("UPDATE mandates SET next_review_at = ? WHERE id = ?")
8322            .bind((chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339())
8323            .bind(&mandate.id)
8324            .execute(&store.pool)
8325            .await
8326            .unwrap();
8327    }
8328
8329    /// Drive one review to a finalized WAIT carrying `owner_alert`, as the
8330    /// task lead would. Returns the commit error when the decision is refused.
8331    async fn finalize_wait_with_alert(
8332        store: &SqliteWorkStore,
8333        goal: &Goal,
8334        mandate: &Mandate,
8335        alert: &str,
8336    ) -> anyhow::Result<()> {
8337        let run = claim_and_start_run(store, goal, mandate).await;
8338        let root_attempt = store
8339            .claim_task_with_lease(
8340                run.root_task_id.as_deref().unwrap(),
8341                "alert-root",
8342                Some("profile-task-lead"),
8343                7_200,
8344            )
8345            .await
8346            .unwrap()
8347            .unwrap();
8348        let mut decision = MandateDecisionCycle::new(
8349            &mandate.id,
8350            &run.id,
8351            MandateDecisionOutcome::Wait,
8352            "the watched page answered 503",
8353            mandate.version,
8354        );
8355        decision.owner_alert = Some(alert.to_string());
8356        store
8357            .record_mandate_decision(&decision, None, Some(&root_attempt.id))
8358            .await?;
8359        assert!(
8360            store
8361                .patch_task_from_attempt(
8362                    &root_attempt.id,
8363                    &root_attempt.lease_token,
8364                    &crate::traits::TaskAttemptPatch {
8365                        status: "completed".to_string(),
8366                        result: Some("WAIT recorded".to_string()),
8367                        ..Default::default()
8368                    },
8369                )
8370                .await
8371                .unwrap()
8372        );
8373        store
8374            .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
8375                mandate_id: mandate.id.clone(),
8376                expected_mandate_version: mandate.version,
8377                goal_run_id: run.id.clone(),
8378                finalized_at: chrono::Utc::now().to_rfc3339(),
8379            })
8380            .await
8381            .unwrap();
8382        Ok(())
8383    }
8384
8385    #[tokio::test]
8386    async fn a_granted_owner_alert_reaches_the_owner_and_the_mandate_keeps_running() {
8387        let (store, _database) = test_store().await;
8388        let (goal, mut mandate) = controller("owner-session", 0);
8389        mandate.authority.owner_alerts = true;
8390        finalize_wait_with_alert(
8391            &store,
8392            &goal,
8393            &mandate,
8394            "The watched page is down (HTTP 503).",
8395        )
8396        .await
8397        .expect("a granted alert commits with its WAIT");
8398        let message = sqlx::query_scalar::<_, String>(
8399            "SELECT message FROM notification_queue
8400             WHERE goal_id = ? AND notification_type = 'mandate_alert'",
8401        )
8402        .bind(&goal.id)
8403        .fetch_one(&store.pool)
8404        .await
8405        .unwrap();
8406        assert!(
8407            message.contains("The watched page is down (HTTP 503)."),
8408            "{message}"
8409        );
8410        let after = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8411        assert_eq!(after.status, MandateStatus::Active);
8412    }
8413
8414    #[tokio::test]
8415    async fn an_owner_alert_without_the_grant_is_refused() {
8416        let (store, _database) = test_store().await;
8417        let (goal, mandate) = controller("owner-session", 0);
8418        assert!(!mandate.authority.owner_alerts);
8419        let refused =
8420            finalize_wait_with_alert(&store, &goal, &mandate, "The watched page is down.").await;
8421        assert!(refused.is_err(), "an alert needs the owner's grant");
8422        let alerts = sqlx::query_scalar::<_, i64>(
8423            "SELECT COUNT(*) FROM notification_queue WHERE notification_type = 'mandate_alert'",
8424        )
8425        .fetch_one(&store.pool)
8426        .await
8427        .unwrap();
8428        assert_eq!(alerts, 0);
8429    }
8430
8431    #[tokio::test]
8432    async fn ask_notice_carries_the_generated_question_for_the_owner() {
8433        let (store, _database) = test_store().await;
8434        let (goal, mandate) = controller("owner-session", 1);
8435        park_mandate_on_ask(&store, &goal, &mandate, "May I also read reply counts?").await;
8436        let message = sqlx::query_scalar::<_, String>(
8437            "SELECT message FROM notification_queue
8438             WHERE goal_id = ? AND notification_type = 'mandate_ask'",
8439        )
8440        .bind(&goal.id)
8441        .fetch_one(&store.pool)
8442        .await
8443        .unwrap();
8444        assert!(
8445            message.contains("May I also read reply counts?"),
8446            "{message}"
8447        );
8448    }
8449
8450    #[tokio::test]
8451    async fn unanswered_ask_resumes_within_existing_authority_at_its_reconsider_time() {
8452        let (store, _database) = test_store().await;
8453        let (goal, mandate) = controller("owner-session", 1);
8454        park_mandate_on_ask(&store, &goal, &mandate, "May I also read reply counts?").await;
8455
8456        // Not yet due: the owner still has the full reconsider window.
8457        assert!(
8458            store
8459                .claim_due_mandates(10, "synthetic-heartbeat", 300)
8460                .await
8461                .unwrap()
8462                .is_empty()
8463        );
8464        assert_eq!(
8465            store
8466                .get_mandate(&mandate.id)
8467                .await
8468                .unwrap()
8469                .unwrap()
8470                .status,
8471            MandateStatus::AwaitingInput
8472        );
8473
8474        make_review_due(&store, &mandate).await;
8475        let claimed = store
8476            .claim_due_mandates(10, "synthetic-heartbeat", 300)
8477            .await
8478            .unwrap();
8479        assert_eq!(claimed.len(), 1, "an unanswered ASK must not park forever");
8480        let resumed = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8481        assert_eq!(resumed.status, MandateStatus::Active);
8482        assert!(resumed.suspension.is_none());
8483        assert_eq!(
8484            resumed.authority, mandate.authority,
8485            "resuming without an answer must not change authority"
8486        );
8487        assert_eq!(
8488            store.get_goal(&goal.id).await.unwrap().unwrap().status,
8489            "active"
8490        );
8491        let notice = sqlx::query_scalar::<_, String>(
8492            "SELECT message FROM notification_queue
8493             WHERE goal_id = ? AND notification_type = 'mandate_ask_timeout'",
8494        )
8495        .bind(&goal.id)
8496        .fetch_one(&store.pool)
8497        .await
8498        .unwrap();
8499        assert!(notice.contains("May I also read reply counts?"), "{notice}");
8500        // Named by the objective the owner confirmed, in plain language.
8501        assert!(notice.starts_with("Your automation \""), "{notice}");
8502        assert!(notice.contains("No reply is needed"), "{notice}");
8503        assert!(!notice.contains("within its current authority"), "{notice}");
8504    }
8505
8506    #[tokio::test]
8507    async fn safety_suspensions_never_auto_resume() {
8508        let (store, _database) = test_store().await;
8509        let (goal, mandate) = controller("owner-session", 1);
8510        store
8511            .create_mandate_controller(&goal, &mandate)
8512            .await
8513            .unwrap();
8514        let suspension = MandateSuspension::new(
8515            MandateSuspensionKind::ReconciliationRequired,
8516            Some("synthetic".to_string()),
8517        );
8518        sqlx::query(
8519            "UPDATE mandates SET status = 'awaiting_input', suspension_json = ?,
8520                 confirmed_at = COALESCE(confirmed_at, ?)
8521             WHERE id = ?",
8522        )
8523        .bind(serde_json::to_string(&suspension).unwrap())
8524        .bind(chrono::Utc::now().to_rfc3339())
8525        .bind(&mandate.id)
8526        .execute(&store.pool)
8527        .await
8528        .unwrap();
8529        make_review_due(&store, &mandate).await;
8530        assert!(
8531            store
8532                .claim_due_mandates(10, "synthetic-heartbeat", 300)
8533                .await
8534                .unwrap()
8535                .is_empty()
8536        );
8537        assert_eq!(
8538            store
8539                .get_mandate(&mandate.id)
8540                .await
8541                .unwrap()
8542                .unwrap()
8543                .status,
8544            MandateStatus::AwaitingInput
8545        );
8546    }
8547
8548    async fn start_existing_claimed_run(
8549        store: &SqliteWorkStore,
8550        goal: &Goal,
8551        mandate: &Mandate,
8552    ) -> GoalRun {
8553        let claimed = store
8554            .claim_due_mandates(1, "test-heartbeat-next", 300)
8555            .await
8556            .unwrap();
8557        assert_eq!(claimed.len(), 1);
8558        assert_eq!(claimed[0].id, mandate.id);
8559        let root_task_id = uuid::Uuid::new_v4().to_string();
8560        let run = store
8561            .start_goal_run(&goal.id, "mandate", None, Some(&root_task_id))
8562            .await
8563            .unwrap();
8564        store
8565            .create_task(&review_root(goal, &run.id, &root_task_id))
8566            .await
8567            .unwrap();
8568        sqlx::query("UPDATE goal_runs SET status = 'running' WHERE id = ?")
8569            .bind(&run.id)
8570            .execute(&store.pool)
8571            .await
8572            .unwrap();
8573        run
8574    }
8575
8576    /// Settle a dispatched attempt with an explicit completion time, as the
8577    /// canonical tool-result append does at its own event time. Quota and
8578    /// cooldown tests need the time chosen; the transition is the same.
8579    async fn finish_attempt(
8580        store: &SqliteWorkStore,
8581        reservation: &MandateMutationReservation,
8582        status: MandateMutationAttemptStatus,
8583        http_status: Option<u16>,
8584        completed_at: chrono::DateTime<chrono::Utc>,
8585    ) -> bool {
8586        sqlx::query(
8587            "UPDATE mandate_mutation_attempts
8588             SET status = ?, outcome_evidence = ?, http_status = ?, completed_at = ?
8589             WHERE mandate_id = ? AND mandate_version = ?
8590               AND decision_cycle_id = ? AND reserved_action_attempt = ?
8591               AND action_digest = ? AND goal_run_id = ?
8592               AND task_id = ? AND task_attempt_id = ? AND tool_call_id = ?
8593               AND status = 'reserved' AND dispatch_claimed_at IS NOT NULL",
8594        )
8595        .bind(match status {
8596            MandateMutationAttemptStatus::Succeeded => "succeeded",
8597            MandateMutationAttemptStatus::Failed => "failed",
8598            MandateMutationAttemptStatus::Ambiguous => "ambiguous",
8599            other => panic!("not a post-dispatch outcome: {other:?}"),
8600        })
8601        .bind("structured_metadata")
8602        .bind(http_status.map(i64::from))
8603        .bind(completed_at.to_rfc3339())
8604        .bind(&reservation.grant.mandate_id)
8605        .bind(reservation.grant.mandate_version)
8606        .bind(&reservation.grant.decision_cycle_id)
8607        .bind(reservation.grant.reserved_action_attempt)
8608        .bind(&reservation.grant.action_digest)
8609        .bind(&reservation.goal_run_id)
8610        .bind(&reservation.task_id)
8611        .bind(&reservation.task_attempt_id)
8612        .bind(&reservation.tool_call_id)
8613        .execute(&store.pool)
8614        .await
8615        .unwrap()
8616        .rows_affected()
8617            == 1
8618    }
8619
8620    #[tokio::test]
8621    async fn cooldown_failure_and_rolling_expiry_are_cross_cycle_safety_state() {
8622        let (store, _database) = test_store().await;
8623        let (goal, mut mandate) = controller("owner-session", 2);
8624        mandate.authority.max_mutating_actions_per_rolling_24h = 2;
8625        let run = claim_and_start_run(&store, &goal, &mandate).await;
8626        let act = MandateDecisionCycle::new(
8627            &mandate.id,
8628            &run.id,
8629            MandateDecisionOutcome::Act,
8630            "Two spaced actions fit the envelope",
8631            mandate.version,
8632        );
8633        let intention = Intention::new(
8634            &mandate.id,
8635            &act.id,
8636            &run.id,
8637            "Perform two governed actions",
8638            "It tests rolling quota semantics",
8639        );
8640        store
8641            .record_mandate_decision(&act, Some(&intention), None)
8642            .await
8643            .unwrap();
8644        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
8645        let base = chrono::Utc::now();
8646        let first = reservation(&mandate, &act, &run, &fence, 1, 201, base);
8647        assert!(
8648            store
8649                .reserve_mandate_action_attempt(&first)
8650                .await
8651                .unwrap()
8652                .is_some()
8653        );
8654        assert!(
8655            store
8656                .claim_mandate_mutation_dispatch(&dispatch_claim(
8657                    &first,
8658                    base + chrono::Duration::milliseconds(1),
8659                ))
8660                .await
8661                .unwrap()
8662        );
8663        assert!(
8664            !store
8665                .claim_mandate_mutation_dispatch(&dispatch_claim(
8666                    &first,
8667                    base + chrono::Duration::milliseconds(2),
8668                ))
8669                .await
8670                .unwrap()
8671        );
8672        assert!(
8673            finish_attempt(
8674                &store,
8675                &first,
8676                MandateMutationAttemptStatus::Failed,
8677                Some(400),
8678                base + chrono::Duration::seconds(1)
8679            )
8680            .await
8681        );
8682        let too_soon = reservation(
8683            &mandate,
8684            &act,
8685            &run,
8686            &fence,
8687            2,
8688            202,
8689            base + chrono::Duration::seconds(899),
8690        );
8691        assert!(
8692            store
8693                .reserve_mandate_action_attempt(&too_soon)
8694                .await
8695                .unwrap()
8696                .is_none()
8697        );
8698        let cooldown = store
8699            .get_mandate_mutation_quota_state(
8700                &mandate.id,
8701                &(base + chrono::Duration::seconds(899)).to_rfc3339(),
8702            )
8703            .await
8704            .unwrap()
8705            .unwrap();
8706        assert_eq!(
8707            cooldown.block_reason,
8708            Some(MandateMutationQuotaBlockReason::Cooldown)
8709        );
8710        assert_eq!(cooldown.reserved_in_rolling_24h, 1);
8711
8712        let second = reservation(
8713            &mandate,
8714            &act,
8715            &run,
8716            &fence,
8717            2,
8718            203,
8719            base + chrono::Duration::seconds(900),
8720        );
8721        assert!(
8722            store
8723                .reserve_mandate_action_attempt(&second)
8724                .await
8725                .unwrap()
8726                .is_some()
8727        );
8728        let full = store
8729            .get_mandate_mutation_quota_state(
8730                &mandate.id,
8731                &(base + chrono::Duration::seconds(901)).to_rfc3339(),
8732            )
8733            .await
8734            .unwrap()
8735            .unwrap();
8736        assert_eq!(
8737            full.block_reason,
8738            Some(MandateMutationQuotaBlockReason::Rolling24hExhausted)
8739        );
8740        assert_eq!(full.remaining_in_rolling_24h, 0);
8741
8742        let observation = crate::traits::ToolCallSemantics::observation().with_target_hint(
8743            crate::traits::ToolTargetHintKind::Url,
8744            "https://api.x.com/2/tweets",
8745        );
8746        assert!(
8747            crate::authority::authorize_mandate_observation(
8748                &mandate,
8749                "http_request",
8750                r#"{"method":"GET","url":"https://api.x.com/2/tweets"}"#,
8751                &observation,
8752                &(base + chrono::Duration::seconds(901)),
8753            )
8754            .is_ok()
8755        );
8756
8757        let expired = store
8758            .get_mandate_mutation_quota_state(
8759                &mandate.id,
8760                &(base + chrono::Duration::hours(24) + chrono::Duration::seconds(1)).to_rfc3339(),
8761            )
8762            .await
8763            .unwrap()
8764            .unwrap();
8765        assert_eq!(expired.reserved_in_rolling_24h, 1);
8766        assert_eq!(expired.remaining_in_rolling_24h, 1);
8767        assert!(expired.available_now);
8768    }
8769
8770    #[tokio::test]
8771    async fn rolling_quota_survives_policy_versions_pause_resume_and_new_cycles() {
8772        let (store, _database) = test_store().await;
8773        let (goal, mut mandate) = controller("owner-session", 1);
8774        mandate.authority.max_mutating_actions_per_rolling_24h = 1;
8775        let first_run = claim_and_start_run(&store, &goal, &mandate).await;
8776        let first_act = MandateDecisionCycle::new(
8777            &mandate.id,
8778            &first_run.id,
8779            MandateDecisionOutcome::Act,
8780            "Use the sole daily slot",
8781            mandate.version,
8782        );
8783        let first_intention = Intention::new(
8784            &mandate.id,
8785            &first_act.id,
8786            &first_run.id,
8787            "Use one daily action",
8788            "It tests cross-cycle accounting",
8789        );
8790        store
8791            .record_mandate_decision(&first_act, Some(&first_intention), None)
8792            .await
8793            .unwrap();
8794        let first_fence = claim_mutation_fence(&store, &goal, &mandate, &first_run).await;
8795        let base = chrono::Utc::now();
8796        let first = reservation(&mandate, &first_act, &first_run, &first_fence, 1, 301, base);
8797        assert!(
8798            store
8799                .reserve_mandate_action_attempt(&first)
8800                .await
8801                .unwrap()
8802                .is_some()
8803        );
8804        assert!(
8805            store
8806                .claim_mandate_mutation_dispatch(&dispatch_claim(
8807                    &first,
8808                    base + chrono::Duration::milliseconds(1),
8809                ))
8810                .await
8811                .unwrap()
8812        );
8813        assert!(
8814            finish_attempt(
8815                &store,
8816                &first,
8817                MandateMutationAttemptStatus::Failed,
8818                Some(400),
8819                base + chrono::Duration::seconds(1)
8820            )
8821            .await
8822        );
8823        assert!(
8824            store
8825                .transition_mandate_status(
8826                    &mandate.id,
8827                    MandateStatus::Active,
8828                    MandateStatus::Paused,
8829                )
8830                .await
8831                .unwrap()
8832        );
8833        assert!(
8834            store
8835                .transition_mandate_status(
8836                    &mandate.id,
8837                    MandateStatus::Paused,
8838                    MandateStatus::Active,
8839                )
8840                .await
8841                .unwrap()
8842        );
8843        let current = store.get_mandate(&mandate.id).await.unwrap().unwrap();
8844        assert!(current.version > mandate.version);
8845        let second_run = start_existing_claimed_run(&store, &goal, &current).await;
8846        let second_act = MandateDecisionCycle::new(
8847            &current.id,
8848            &second_run.id,
8849            MandateDecisionOutcome::Act,
8850            "A new cycle still sees the old reservation",
8851            current.version,
8852        );
8853        let second_intention = Intention::new(
8854            &current.id,
8855            &second_act.id,
8856            &second_run.id,
8857            "Try another action",
8858            "The daily ledger must reject it",
8859        );
8860        // The new cycle's ACT is refused when it is committed: the store
8861        // reads the same rolling ledger across policy versions.
8862        let refused = store
8863            .record_mandate_decision(&second_act, Some(&second_intention), None)
8864            .await
8865            .expect_err("ACT must be refused while the rolling quota is used up");
8866        assert!(
8867            refused
8868                .to_string()
8869                .starts_with("mandate_mutation_quota_unavailable: choose WAIT"),
8870            "{refused}"
8871        );
8872        let quota = store
8873            .get_mandate_mutation_quota_state(
8874                &current.id,
8875                &(base + chrono::Duration::seconds(901)).to_rfc3339(),
8876            )
8877            .await
8878            .unwrap()
8879            .unwrap();
8880        assert_eq!(quota.reserved_in_rolling_24h, 1);
8881        assert_eq!(
8882            quota.block_reason,
8883            Some(MandateMutationQuotaBlockReason::Rolling24hExhausted)
8884        );
8885    }
8886
8887    #[tokio::test]
8888    async fn canonical_tool_result_atomically_projects_the_mandate_ledger() {
8889        let (store, _database) = test_store().await;
8890        let (goal, mandate) = controller("owner-session", 1);
8891        let run = claim_and_start_run(&store, &goal, &mandate).await;
8892        let decision = MandateDecisionCycle::new(
8893            &mandate.id,
8894            &run.id,
8895            MandateDecisionOutcome::Act,
8896            "Exercise atomic receipt projection",
8897            mandate.version,
8898        );
8899        let intention = Intention::new(
8900            &mandate.id,
8901            &decision.id,
8902            &run.id,
8903            "Issue one governed request",
8904            "The event and ledger must commit together",
8905        );
8906        store
8907            .record_mandate_decision(&decision, Some(&intention), None)
8908            .await
8909            .unwrap();
8910        let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
8911        let now = chrono::Utc::now();
8912        let reservation = reservation(&mandate, &decision, &run, &fence, 1, 777, now);
8913        store
8914            .reserve_mandate_action_attempt(&reservation)
8915            .await
8916            .unwrap()
8917            .expect("reserved mutation");
8918        assert!(
8919            store
8920                .claim_mandate_mutation_dispatch(&dispatch_claim(
8921                    &reservation,
8922                    now + chrono::Duration::milliseconds(1),
8923                ))
8924                .await
8925                .unwrap()
8926        );
8927
8928        let semantics = crate::traits::ToolCallSemantics::mutation_with(
8929            crate::traits::ToolMutationEffects::EXTERNAL_DELIVERY,
8930        );
8931        let mut receipt = aidaemon_events::ToolReceiptV1::from_metadata(
8932            &crate::traits::ToolCallMetadata {
8933                outcome_status: Some(crate::traits::ToolOutcomeStatus::Succeeded),
8934                http_status: Some(201),
8935                semantics,
8936                ..Default::default()
8937            },
8938            crate::traits::ToolOutcomeStatus::Succeeded,
8939            aidaemon_events::ToolOutcomeEvidenceSource::StructuredMetadata,
8940            Some("mandate-atomic-receipt".to_string()),
8941        );
8942        receipt.mandate_authority = Some(reservation.grant.clone());
8943        let result = aidaemon_events::ToolResultData {
8944            message_id: None,
8945            tool_call_id: reservation.tool_call_id.clone(),
8946            name: "http_request".to_string(),
8947            result: "created".to_string(),
8948            success: true,
8949            duration_ms: 1,
8950            error: None,
8951            task_id: Some(fence.worker_task.id.clone()),
8952            annotations: vec![],
8953            turn_id: None,
8954            attachments: vec![],
8955            receipt: Some(receipt),
8956        };
8957        let event_store = aidaemon_events::EventStore::on_paths(
8958            store.pool(),
8959            aidaemon_tools::LexicalPaths::daemon_host(),
8960            Arc::new(aidaemon_events::NoEventHost),
8961        )
8962        .await
8963        .unwrap();
8964        event_store
8965            .append(aidaemon_events::Event::new(
8966                "specialist:mandate",
8967                aidaemon_events::EventType::ToolResult,
8968                serde_json::to_value(result).unwrap(),
8969            ))
8970            .await
8971            .unwrap();
8972
8973        let attempts = store
8974            .list_mandate_mutation_attempts_for_run(&run.id)
8975            .await
8976            .unwrap();
8977        assert_eq!(attempts.len(), 1);
8978        assert_eq!(attempts[0].status, MandateMutationAttemptStatus::Succeeded);
8979    }
8980
8981    #[tokio::test]
8982    async fn strict_receipts_finalize_act_and_mixed_failure_fails_closed() {
8983        for include_failure in [false, true] {
8984            let (store, _database) = test_store().await;
8985            let cycle_cap = if include_failure { 2 } else { 1 };
8986            let (goal, mut mandate) = controller("owner-session", cycle_cap);
8987            mandate.authority.max_mutating_actions_per_rolling_24h = cycle_cap;
8988            let run = claim_and_start_run(&store, &goal, &mandate).await;
8989            let act = MandateDecisionCycle::new(
8990                &mandate.id,
8991                &run.id,
8992                MandateDecisionOutcome::Act,
8993                "Execute and prove the governed action",
8994                mandate.version,
8995            );
8996            let intention = Intention::new(
8997                &mandate.id,
8998                &act.id,
8999                &run.id,
9000                "Execute governed mutation",
9001                "Strict receipts determine completion",
9002            );
9003            store
9004                .record_mandate_decision(&act, Some(&intention), None)
9005                .await
9006                .unwrap();
9007            let fence = claim_mutation_fence(&store, &goal, &mandate, &run).await;
9008            let base = chrono::Utc::now();
9009            let first = reservation(&mandate, &act, &run, &fence, 1, 401, base);
9010            assert!(
9011                store
9012                    .reserve_mandate_action_attempt(&first)
9013                    .await
9014                    .unwrap()
9015                    .is_some()
9016            );
9017            assert!(
9018                store
9019                    .claim_mandate_mutation_dispatch(&dispatch_claim(
9020                        &first,
9021                        base + chrono::Duration::milliseconds(1),
9022                    ))
9023                    .await
9024                    .unwrap()
9025            );
9026            assert!(
9027                finish_attempt(
9028                    &store,
9029                    &first,
9030                    MandateMutationAttemptStatus::Succeeded,
9031                    Some(200),
9032                    base + chrono::Duration::seconds(1)
9033                )
9034                .await
9035            );
9036            if include_failure {
9037                let second = reservation(
9038                    &mandate,
9039                    &act,
9040                    &run,
9041                    &fence,
9042                    2,
9043                    402,
9044                    base + chrono::Duration::seconds(900),
9045                );
9046                assert!(
9047                    store
9048                        .reserve_mandate_action_attempt(&second)
9049                        .await
9050                        .unwrap()
9051                        .is_some()
9052                );
9053                assert!(
9054                    store
9055                        .claim_mandate_mutation_dispatch(&dispatch_claim(
9056                            &second,
9057                            base + chrono::Duration::milliseconds(900_001),
9058                        ))
9059                        .await
9060                        .unwrap()
9061                );
9062                assert!(
9063                    finish_attempt(
9064                        &store,
9065                        &second,
9066                        MandateMutationAttemptStatus::Failed,
9067                        Some(400),
9068                        base + chrono::Duration::seconds(901)
9069                    )
9070                    .await
9071                );
9072            }
9073            complete_mutation_fence(&store, &fence).await;
9074            let result = store
9075                .finalize_mandate_run_from_proof(&MandateRunFinalizationRequest {
9076                    mandate_id: mandate.id.clone(),
9077                    expected_mandate_version: mandate.version,
9078                    goal_run_id: run.id.clone(),
9079                    finalized_at: (base + chrono::Duration::seconds(1_000)).to_rfc3339(),
9080                })
9081                .await
9082                .unwrap();
9083            if include_failure {
9084                assert!(matches!(
9085                    result,
9086                    MandateRunFinalizationResult::ReconciliationRequired {
9087                        reason: MandateReconciliationReason::MutationOutcomeFailed,
9088                        ..
9089                    }
9090                ));
9091                assert_eq!(
9092                    store.get_goal_runs(&goal.id).await.unwrap()[0].status,
9093                    "failed"
9094                );
9095                assert!(
9096                    store
9097                        .get_current_goal_run(&goal.id)
9098                        .await
9099                        .unwrap()
9100                        .is_none()
9101                );
9102                assert_eq!(
9103                    store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
9104                    IntentionStatus::Suspended
9105                );
9106                assert_eq!(
9107                    store
9108                        .get_mandate(&mandate.id)
9109                        .await
9110                        .unwrap()
9111                        .unwrap()
9112                        .status,
9113                    MandateStatus::AwaitingInput
9114                );
9115                assert_eq!(
9116                    store.get_goal(&goal.id).await.unwrap().unwrap().status,
9117                    "paused"
9118                );
9119            } else {
9120                assert!(matches!(
9121                    result,
9122                    MandateRunFinalizationResult::ActSatisfied { .. }
9123                ));
9124                assert_eq!(
9125                    store.get_goal_runs(&goal.id).await.unwrap()[0].status,
9126                    "completed"
9127                );
9128                assert_eq!(
9129                    store.list_intentions(&mandate.id, 1).await.unwrap()[0].status,
9130                    IntentionStatus::Satisfied
9131                );
9132            }
9133        }
9134    }
9135}