Skip to main content

aidaemon_work/tools/
objective_status.rs

1//! One authoritative lifecycle readout for goal-backed objectives.
2//!
3//! An objective's health lives in typed durable state (schedules, goal runs,
4//! recovery disposition, and mandate control). The scheduled-goal and mandate
5//! collections are different universes, so a shared projection must preserve
6//! both the exact goal identity and which collection supplied each row. A
7//! complete collection may prove absence only inside that collection; a
8//! truncated or unqueried collection may not.
9
10use std::collections::{BTreeMap, BTreeSet};
11
12/// Durable collections that can contribute an objective row. These names are
13/// deliberately about source membership, not about what a row happens to say:
14/// a mandate-controller goal with no cron row is still a mandate controller,
15/// and does not prove that some unrelated scheduled objective is absent.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
17pub enum ObjectiveCollection {
18    ScheduledGoals,
19    MandateControllers,
20}
21
22impl ObjectiveCollection {
23    pub const fn as_str(self) -> &'static str {
24        match self {
25            Self::ScheduledGoals => "scheduled_goals",
26            Self::MandateControllers => "mandate_controllers",
27        }
28    }
29
30    pub const fn resource_id(self) -> &'static str {
31        match self {
32            Self::ScheduledGoals => "objective_collection:scheduled_goals",
33            Self::MandateControllers => "objective_collection:mandate_controllers",
34        }
35    }
36
37    fn target_hint(self) -> crate::traits::ToolTargetHint {
38        crate::traits::ToolTargetHint::new(
39            crate::traits::ToolTargetHintKind::ResourceId,
40            self.resource_id(),
41        )
42        .expect("objective collection IDs are nonempty constants")
43    }
44
45    /// What an adapter enumerating this collection advertises to the
46    /// checklist: the collection ID, every objective facet, and the
47    /// `objective:` member namespace `objective_resource_id` mints.
48    pub fn stable_subject(self) -> crate::traits::StableObservationSubject {
49        crate::traits::StableObservationSubject::collection(
50            self.resource_id(),
51            &OBJECTIVE_STATUS_FACETS,
52            OBJECTIVE_MEMBER_NAMESPACE,
53            match self {
54                Self::ScheduledGoals => "every scheduled goal",
55                Self::MandateControllers => "every mandate-controlled goal",
56            },
57        )
58    }
59}
60
61pub const OBJECTIVE_MEMBER_NAMESPACE: &str = "objective:";
62
63pub const OBJECTIVE_STATUS_FACETS: [crate::traits::ToolSemanticFacet; 6] = [
64    crate::traits::ToolSemanticFacet::Schedule,
65    crate::traits::ToolSemanticFacet::RunState,
66    crate::traits::ToolSemanticFacet::Recovery,
67    crate::traits::ToolSemanticFacet::Control,
68    crate::traits::ToolSemanticFacet::Measurement,
69    crate::traits::ToolSemanticFacet::Ownership,
70];
71
72pub fn objective_resource_id(goal_id: &str) -> String {
73    use sha2::{Digest, Sha256};
74
75    // The checklist needs a stable exact identity, while owner-facing tool
76    // output must not expose internal database UUIDs. A full digest keeps the
77    // mapping deterministic without relying on display prose or row order.
78    format!(
79        "{OBJECTIVE_MEMBER_NAMESPACE}sha256:{}",
80        hex::encode(Sha256::digest(goal_id.as_bytes()))
81    )
82}
83
84/// Coverage for one collection enumeration. `complete` is derived rather than
85/// supplied so callers cannot accidentally label a limited result authoritative.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct ObjectiveCollectionCoverage {
88    pub collection: ObjectiveCollection,
89    pub total: usize,
90    pub returned: usize,
91}
92
93impl ObjectiveCollectionCoverage {
94    pub fn new(
95        collection: ObjectiveCollection,
96        total: usize,
97        returned: usize,
98    ) -> anyhow::Result<Self> {
99        anyhow::ensure!(
100            returned <= total,
101            "objective collection {} returned {returned} rows from a total of {total}",
102            collection.as_str()
103        );
104        Ok(Self {
105            collection,
106            total,
107            returned,
108        })
109    }
110
111    pub const fn is_complete(self) -> bool {
112        self.returned == self.total
113    }
114
115    pub fn as_json(self) -> serde_json::Value {
116        serde_json::json!({
117            "name": self.collection.as_str(),
118            "resource_id": self.collection.resource_id(),
119            "complete": self.is_complete(),
120            "total": self.total,
121            "returned": self.returned,
122            "absence_semantics": if self.is_complete() {
123                "authoritative_within_collection"
124            } else {
125                "unknown_outside_returned_rows"
126            },
127        })
128    }
129}
130
131/// Upper bound on scheduled rows any surface returns in one enumeration.
132pub const SCHEDULED_COLLECTION_LIMIT: usize = 100;
133
134/// Enumerate the scheduled-goal collection the same way on every owner
135/// surface. The collection is daemon-wide: a goal's `session_id` records the
136/// channel session that created it, not an authority boundary, and one owner
137/// routinely reaches the daemon through several sessions (two Telegram bots,
138/// a Slack DM). A surface that filters this collection by session while still
139/// labeling its coverage `complete` turns a goal created through a sibling
140/// owner session into an authoritative "absent" (R53). `total` therefore
141/// counts every scheduled goal, so truncation stays honest as `partial`.
142pub async fn load_scheduled_goal_collection<S>(
143    state: &S,
144    limit: usize,
145) -> anyhow::Result<(Vec<crate::traits::Goal>, ObjectiveCollectionCoverage)>
146where
147    S: crate::traits::GoalScheduleStore + ?Sized,
148{
149    let mut goals = state.get_scheduled_goals().await?;
150    goals.sort_by(|left, right| {
151        let left_rank = usize::from(left.status != "active");
152        let right_rank = usize::from(right.status != "active");
153        left_rank
154            .cmp(&right_rank)
155            .then_with(|| right.updated_at.cmp(&left.updated_at))
156            .then_with(|| left.id.cmp(&right.id))
157    });
158    let total = goals.len();
159    goals.truncate(limit.clamp(1, SCHEDULED_COLLECTION_LIMIT));
160    let coverage =
161        ObjectiveCollectionCoverage::new(ObjectiveCollection::ScheduledGoals, total, goals.len())?;
162    Ok((goals, coverage))
163}
164
165/// The only three defensible answers to collection membership. In particular,
166/// not seeing a subject in a limited collection is `Unknown`, never `Absent`.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum ObjectiveCollectionMembership {
169    Present,
170    Absent,
171    Unknown,
172}
173
174/// Subject-keyed row in the canonical objective portfolio. The stable goal ID
175/// is retained even when a public renderer elects not to display internal IDs.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct ObjectivePortfolioRow {
178    pub goal_id: String,
179    pub source_membership: BTreeSet<ObjectiveCollection>,
180    pub status: ObjectiveStatus,
181}
182
183impl ObjectivePortfolioRow {
184    pub fn subject_hint(&self) -> crate::traits::ToolTargetHint {
185        crate::traits::ToolTargetHint::new(
186            crate::traits::ToolTargetHintKind::ResourceId,
187            objective_resource_id(&self.goal_id),
188        )
189        .expect("validated objective goal IDs are nonempty")
190    }
191
192    pub fn source_membership_json(&self) -> serde_json::Value {
193        serde_json::Value::Array(
194            self.source_membership
195                .iter()
196                .map(|collection| serde_json::Value::String(collection.as_str().to_string()))
197                .collect(),
198        )
199    }
200
201    pub fn source_membership_label(&self) -> String {
202        self.source_membership
203            .iter()
204            .map(|collection| collection.as_str())
205            .collect::<Vec<_>>()
206            .join(", ")
207    }
208}
209
210/// A portfolio joins rows only by stable goal ID. It intentionally does not
211/// attempt to infer that similar objective prose, account configuration, row
212/// order, or one collection's first result refers to another collection's row.
213#[derive(Debug, Default)]
214pub struct ObjectivePortfolio {
215    subjects: BTreeMap<String, ObjectivePortfolioRow>,
216    coverage: BTreeMap<ObjectiveCollection, ObjectiveCollectionCoverage>,
217}
218
219impl ObjectivePortfolio {
220    pub fn record_collection(
221        &mut self,
222        coverage: ObjectiveCollectionCoverage,
223    ) -> anyhow::Result<()> {
224        if let Some(existing) = self.coverage.get(&coverage.collection) {
225            anyhow::ensure!(
226                existing == &coverage,
227                "objective collection {} was enumerated with conflicting coverage",
228                coverage.collection.as_str()
229            );
230            return Ok(());
231        }
232        self.coverage.insert(coverage.collection, coverage);
233        Ok(())
234    }
235
236    pub fn insert(&mut self, row: ObjectivePortfolioRow) -> anyhow::Result<()> {
237        match self.subjects.get_mut(&row.goal_id) {
238            Some(existing) => {
239                anyhow::ensure!(
240                    existing.status == row.status,
241                    "objective subject {} was projected with conflicting lifecycle state",
242                    row.goal_id
243                );
244                existing.source_membership.extend(row.source_membership);
245            }
246            None => {
247                self.subjects.insert(row.goal_id.clone(), row);
248            }
249        }
250        Ok(())
251    }
252
253    pub fn subject(&self, goal_id: &str) -> Option<&ObjectivePortfolioRow> {
254        self.subjects.get(goal_id)
255    }
256
257    pub fn subjects(&self) -> impl Iterator<Item = &ObjectivePortfolioRow> {
258        self.subjects.values()
259    }
260
261    pub fn membership(
262        &self,
263        goal_id: &str,
264        collection: ObjectiveCollection,
265    ) -> ObjectiveCollectionMembership {
266        if self
267            .subjects
268            .get(goal_id)
269            .is_some_and(|row| row.source_membership.contains(&collection))
270        {
271            return ObjectiveCollectionMembership::Present;
272        }
273        match self.coverage.get(&collection) {
274            Some(coverage) if coverage.is_complete() => ObjectiveCollectionMembership::Absent,
275            _ => ObjectiveCollectionMembership::Unknown,
276        }
277    }
278
279    pub fn collection_scope_json(
280        &self,
281        primary: ObjectiveCollection,
282    ) -> anyhow::Result<serde_json::Value> {
283        let coverage = self.coverage.get(&primary).copied().ok_or_else(|| {
284            anyhow::anyhow!(
285                "objective collection {} has no coverage record",
286                primary.as_str()
287            )
288        })?;
289        let not_enumerated = [
290            ObjectiveCollection::ScheduledGoals,
291            ObjectiveCollection::MandateControllers,
292        ]
293        .into_iter()
294        .filter(|collection| !self.coverage.contains_key(collection))
295        .map(|collection| serde_json::Value::String(collection.as_str().to_string()))
296        .collect::<Vec<_>>();
297        let mut value = coverage.as_json();
298        value["not_enumerated"] = serde_json::Value::Array(not_enumerated);
299        Ok(value)
300    }
301
302    /// Convert the canonical subject-keyed snapshot into durable receipt
303    /// assertions. Renderers may reorder or truncate prose, but the adapter's
304    /// exact subject/facet and collection coverage remain stable evidence.
305    pub fn receipt_evidence(
306        &self,
307    ) -> (
308        Vec<crate::traits::ToolObservationEvidence>,
309        Vec<crate::traits::ToolCollectionObservation>,
310    ) {
311        let observations = self
312            .subjects
313            .values()
314            .map(|row| {
315                let mut observation = crate::traits::ToolObservationEvidence::new(
316                    row.subject_hint(),
317                    &OBJECTIVE_STATUS_FACETS,
318                );
319                for collection in &row.source_membership {
320                    observation = observation.with_source_collection(collection.target_hint());
321                }
322                observation
323            })
324            .collect::<Vec<_>>();
325        let collections = self
326            .coverage
327            .values()
328            .map(|coverage| {
329                let members = self
330                    .subjects
331                    .values()
332                    .filter(|row| row.source_membership.contains(&coverage.collection))
333                    .map(ObjectivePortfolioRow::subject_hint)
334                    .collect::<Vec<_>>();
335                crate::traits::ToolCollectionObservation {
336                    collection: coverage.collection.target_hint(),
337                    facets: OBJECTIVE_STATUS_FACETS.to_vec(),
338                    completeness: if coverage.is_complete() {
339                        crate::traits::ToolCollectionCompleteness::Complete
340                    } else {
341                        crate::traits::ToolCollectionCompleteness::Partial
342                    },
343                    returned_count: coverage.returned,
344                    total_count: Some(coverage.total),
345                    members,
346                }
347            })
348            .collect();
349        (observations, collections)
350    }
351}
352
353/// Typed lifecycle snapshot for one goal-backed objective.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct ObjectiveStatus {
356    /// What wakes this objective next.
357    pub wake: ObjectiveWake,
358    /// Latest goal run: (status, finished-or-started timestamp, summary).
359    pub latest_run: Option<(String, String, Option<String>)>,
360    /// Recovery ledger: (disposition, consecutive_failures, failure_budget).
361    pub recovery: Option<(&'static str, u16, u16)>,
362    /// Terminal run history counts (bounded by the store's returned window).
363    pub runs_completed: usize,
364    pub runs_failed: usize,
365    /// Delegated control-loop facet; `None` means no mandate governs this
366    /// goal, which every surface must render as an explicit "control absent"
367    /// rather than leaving the question unanswerable.
368    pub control: Option<ObjectiveControlFacet>,
369}
370
371/// What wakes an objective. A mandate wakes from its own review clock and
372/// never uses `goal_schedules`, so an empty schedule list says nothing about
373/// a mandate controller.
374#[derive(Debug, Clone, PartialEq, Eq)]
375pub enum ObjectiveWake {
376    GoalSchedule {
377        /// Earliest next occurrence among active schedules; `None` when all
378        /// are paused.
379        next_run_at: Option<String>,
380    },
381    MandateClock {
382        next_review_at: String,
383    },
384    /// A mandate that is not active: nothing will wake it.
385    MandateHalted {
386        status: String,
387        /// The typed suspension reason, when it is suspended.
388        reason: Option<String>,
389    },
390    None,
391}
392
393impl ObjectiveWake {
394    /// `wake_source` on structured surfaces.
395    pub fn source(&self) -> &'static str {
396        match self {
397            Self::GoalSchedule { .. } => "goal_schedule",
398            Self::MandateClock { .. } => "mandate_clock",
399            Self::MandateHalted { .. } | Self::None => "none",
400        }
401    }
402
403    /// `schedule_state` on structured surfaces.
404    pub fn state(&self) -> &'static str {
405        match self {
406            Self::GoalSchedule {
407                next_run_at: Some(_),
408            } => "active",
409            Self::GoalSchedule { next_run_at: None } => "paused",
410            Self::MandateClock { .. } => "mandate_clock",
411            Self::MandateHalted { .. } => "mandate_halted",
412            Self::None => "missing",
413        }
414    }
415
416    /// When the objective wakes next, whatever wakes it.
417    pub fn next_at(&self) -> Option<&str> {
418        match self {
419            Self::GoalSchedule { next_run_at } => next_run_at.as_deref(),
420            Self::MandateClock { next_review_at } => Some(next_review_at),
421            Self::MandateHalted { .. } | Self::None => None,
422        }
423    }
424
425    fn describe(&self) -> String {
426        match self {
427            Self::GoalSchedule {
428                next_run_at: Some(next),
429            } => format!("schedule active (next {})", shown_time(next)),
430            Self::GoalSchedule { next_run_at: None } => "schedule paused".to_string(),
431            Self::MandateClock { next_review_at } => {
432                format!("mandate clock (next review {})", shown_time(next_review_at))
433            }
434            Self::MandateHalted {
435                reason: Some(reason),
436                ..
437            } => format!("suspended ({reason}), no review scheduled"),
438            Self::MandateHalted { status, .. } => format!("{status}, no review scheduled"),
439            Self::None => "schedule missing".to_string(),
440        }
441    }
442}
443
444/// Typed delegation/control readout for one goal-backed objective, derived
445/// from the goal's mandate row and its recorded objective measurements.
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct ObjectiveControlFacet {
448    pub mandate_status: String,
449    pub autonomy_mode: String,
450    /// Owner-confirmed control-loop metric, when the mandate has one.
451    pub metric_name: Option<String>,
452    pub measurement_count: usize,
453    /// Distinct `account:` / `auth_profile:` identities from the mandate's
454    /// authority scopes: the typed answer to "which owned account and
455    /// credentials is this objective delegated to?".
456    pub delegated_identities: Vec<String>,
457}
458
459/// Project the goal's mandate row into the control facet. `None` in means no
460/// mandate exists for the goal; measurement rows without a mandate cannot
461/// exist, so the absent case always carries zero measurements.
462pub fn objective_control_facet(
463    mandate: Option<&crate::traits::Mandate>,
464    measurement_count: usize,
465) -> Option<ObjectiveControlFacet> {
466    mandate.map(|mandate| {
467        let mut delegated_identities = Vec::new();
468        for scope in &mandate.authority.operation_scopes {
469            for prefix in &scope.target_prefixes {
470                if (prefix.starts_with("account:") || prefix.starts_with("auth_profile:"))
471                    && !delegated_identities.contains(prefix)
472                {
473                    delegated_identities.push(prefix.clone());
474                }
475            }
476        }
477        ObjectiveControlFacet {
478            mandate_status: mandate.status.to_string(),
479            autonomy_mode: mandate.autonomy_mode.to_string(),
480            metric_name: mandate
481                .objective_control
482                .as_ref()
483                .map(|control| control.metric_name.clone()),
484            measurement_count,
485            delegated_identities,
486        }
487    })
488}
489
490/// The control facet as typed JSON for structured surfaces. The absent case
491/// is the literal string "absent" rather than an object: R47 showed that an
492/// audit reads the mere presence of a populated `objective_control` object as
493/// "control exists", so absence must not be expressed through a shape that
494/// exists. Present control is an object; absent control is unmistakably not.
495pub fn objective_control_json(control: Option<&ObjectiveControlFacet>) -> serde_json::Value {
496    match control {
497        Some(facet) => serde_json::json!({
498            "mandate_status": facet.mandate_status,
499            "autonomy_mode": facet.autonomy_mode,
500            "metric": facet.metric_name,
501            "measurement_count": facet.measurement_count,
502            "delegated_identities": facet.delegated_identities,
503        }),
504        None => serde_json::json!("absent"),
505    }
506}
507
508/// Project one exact goal into a portfolio row. All typed inputs are checked
509/// against the requested subject before any field is aggregated. This is the
510/// central defense against projecting goal B's mandate or run state onto goal
511/// A merely because the rows were adjacent or fetched by the same audit.
512pub fn objective_portfolio_row(
513    goal_id: &str,
514    enumerated_from: ObjectiveCollection,
515    schedules: &[crate::traits::GoalSchedule],
516    runs: &[crate::traits::GoalRun],
517    recovery: Option<&crate::traits::ScheduledRecoveryState>,
518    mandate: Option<&crate::traits::Mandate>,
519    measurement_count: usize,
520) -> anyhow::Result<ObjectivePortfolioRow> {
521    anyhow::ensure!(!goal_id.trim().is_empty(), "objective subject is empty");
522    for schedule in schedules {
523        anyhow::ensure!(
524            schedule.goal_id == goal_id,
525            "schedule {} belongs to goal {}, not objective subject {goal_id}",
526            schedule.id,
527            schedule.goal_id
528        );
529    }
530    for run in runs {
531        anyhow::ensure!(
532            run.goal_id == goal_id,
533            "goal run {} belongs to goal {}, not objective subject {goal_id}",
534            run.id,
535            run.goal_id
536        );
537    }
538    if let Some(recovery) = recovery {
539        anyhow::ensure!(
540            recovery.goal_id == goal_id,
541            "recovery state belongs to goal {}, not objective subject {goal_id}",
542            recovery.goal_id
543        );
544    }
545    if let Some(mandate) = mandate {
546        anyhow::ensure!(
547            mandate.goal_id == goal_id,
548            "mandate {} belongs to goal {}, not objective subject {goal_id}",
549            mandate.id,
550            mandate.goal_id
551        );
552    } else {
553        anyhow::ensure!(
554            measurement_count == 0,
555            "objective subject {goal_id} has measurements without a mandate"
556        );
557    }
558
559    // Membership records which collection enumeration returned this subject,
560    // not which facet rows happened to be joined while projecting it. A
561    // scheduled audit may read a mandate facet without enumerating (or being
562    // authorized to enumerate) the mandate collection; that cannot become a
563    // collection-membership claim.
564    let source_membership = BTreeSet::from([enumerated_from]);
565
566    let wake = match mandate {
567        Some(mandate) => match mandate.scheduled_next_review() {
568            Some(next_review_at) => ObjectiveWake::MandateClock {
569                next_review_at: next_review_at.to_string(),
570            },
571            None => ObjectiveWake::MandateHalted {
572                status: mandate.status.to_string(),
573                reason: mandate.suspension.as_ref().map(|suspension| {
574                    suspension
575                        .reason_code
576                        .clone()
577                        .unwrap_or_else(|| suspension.kind.as_str().to_string())
578                }),
579            },
580        },
581        None if schedules.is_empty() => ObjectiveWake::None,
582        None => ObjectiveWake::GoalSchedule {
583            next_run_at: schedules
584                .iter()
585                .filter(|schedule| !schedule.is_paused)
586                .map(|schedule| schedule.next_run_at.clone())
587                .min(),
588        },
589    };
590    let latest_run = runs.first().map(|run| {
591        (
592            run.status.clone(),
593            run.completed_at
594                .clone()
595                .unwrap_or_else(|| run.started_at.clone()),
596            run.outcome_summary.clone(),
597        )
598    });
599    let runs_completed = runs.iter().filter(|run| run.status == "completed").count();
600    let runs_failed = runs
601        .iter()
602        .filter(|run| matches!(run.status.as_str(), "failed" | "blocked" | "cancelled"))
603        .count();
604    let recovery = recovery.map(|recovery| {
605        (
606            recovery.disposition.as_str(),
607            recovery.consecutive_failures,
608            recovery.failure_budget,
609        )
610    });
611    Ok(ObjectivePortfolioRow {
612        goal_id: goal_id.to_string(),
613        source_membership,
614        status: ObjectiveStatus {
615            wake,
616            latest_run,
617            recovery,
618            runs_completed,
619            runs_failed,
620            control: objective_control_facet(mandate, measurement_count),
621        },
622    })
623}
624
625/// Render the snapshot as a single plain-text line for list surfaces.
626pub fn render_objective_status_line(status: &ObjectiveStatus) -> String {
627    let mut line = status.wake.describe();
628    match &status.latest_run {
629        Some((run_status, at, summary)) => {
630            line.push_str(&format!("; last run {run_status} at {at}"));
631            if let Some(summary) = summary {
632                let summary = summary.trim();
633                if !summary.is_empty() {
634                    line.push_str(" — ");
635                    line.push_str(&aidaemon_events::text::truncate_str(summary, 140));
636                }
637            }
638        }
639        None => line.push_str("; no runs recorded"),
640    }
641    if let Some((disposition, failures, budget)) = &status.recovery {
642        line.push_str(&format!(
643            "; recovery {disposition} ({failures}/{budget} failures)"
644        ));
645    }
646    line.push_str(&format!(
647        "; run history {} completed / {} failed",
648        status.runs_completed, status.runs_failed
649    ));
650    match &status.control {
651        Some(control) => {
652            let metric = control
653                .metric_name
654                .as_deref()
655                .map(|name| format!("metric {name}"))
656                .unwrap_or_else(|| "no metric loop".to_string());
657            let identities = if control.delegated_identities.is_empty() {
658                "no delegated account".to_string()
659            } else {
660                format!("delegated to {}", control.delegated_identities.join(", "))
661            };
662            line.push_str(&format!(
663                "; control {} ({}; {}; {}; {} measurements)",
664                control.mandate_status,
665                control.autonomy_mode,
666                metric,
667                identities,
668                control.measurement_count
669            ));
670        }
671        None => line.push_str(
672            "; control absent (no mandate; no delegated account or credentials; 0 measurements)",
673        ),
674    }
675    line
676}
677
678/// A stored time as the owner reads it ("2:39 PM ET"); unreadable values
679/// as stored.
680fn shown_time(value: &str) -> String {
681    crate::schedule::owner_time_rfc3339(value).unwrap_or_else(|| value.to_string())
682}