Skip to main content

aidaemon_memory/
trajectory.rs

1//! Learning from what tasks did: a host's task history as typed trace
2//! events, and the procedures, error solutions and expertise memory learns
3//! from them.
4
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7
8use aidaemon_core::{Message, ModelRequest, Provider};
9use chrono::{DateTime, Utc};
10use serde_json::Value;
11use tracing::{info, warn};
12
13use crate::embed::Embedder;
14use crate::learning::{ErrorSolution, Procedure, embedding_of, error_pattern};
15use crate::stores::MemoryStores;
16use crate::text::truncate_chars;
17
18/// How a task ended.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum TaskEnding {
21    Succeeded,
22    Partial,
23    Failed,
24}
25
26/// One event of a session's task history, as the host recorded it.
27#[derive(Debug, Clone, PartialEq)]
28pub enum TraceEvent {
29    TaskStarted {
30        task_id: String,
31        /// The request the task serves.
32        description: String,
33    },
34    ToolCalled {
35        task_id: Option<String>,
36        name: String,
37        /// A short description of the call's arguments.
38        summary: Option<String>,
39        /// The call's arguments, when the host's record of the call is whole.
40        arguments: Option<Value>,
41    },
42    ToolReturned {
43        task_id: Option<String>,
44        name: String,
45        succeeded: bool,
46        result: String,
47    },
48    /// An error the run hit (with the tool involved, if any).
49    Failed {
50        task_id: Option<String>,
51        message: String,
52        tool: Option<String>,
53    },
54    TaskEnded {
55        task_id: String,
56        outcome: TaskEnding,
57        duration_secs: f64,
58    },
59    /// A message from the user. A host leaves out the ones it wrote itself
60    /// (continuations of a run, for example).
61    UserMessage {
62        content: String,
63        at: DateTime<Utc>,
64        /// The owner wrote it: their role, not a mandate worker, and not
65        /// wrapped untrusted external data. Only such a message can make a
66        /// remembered fact owner-stated.
67        owner_authored: bool,
68    },
69    /// A check the run went through.
70    DecisionPoint(DecisionPoint),
71}
72
73impl TraceEvent {
74    /// The task whose work this event records. User messages and decision
75    /// points are not work: they never affect which tasks exist, their
76    /// order, or how far an error looks for its recovery.
77    fn work_task_id(&self) -> Option<&str> {
78        match self {
79            Self::TaskStarted { task_id, .. } | Self::TaskEnded { task_id, .. } => Some(task_id),
80            Self::ToolCalled { task_id, .. }
81            | Self::ToolReturned { task_id, .. }
82            | Self::Failed { task_id, .. } => task_id.as_deref(),
83            Self::UserMessage { .. } | Self::DecisionPoint(_) => None,
84        }
85    }
86
87    fn is_work(&self) -> bool {
88        !matches!(self, Self::UserMessage { .. } | Self::DecisionPoint(_))
89    }
90}
91
92/// A check a task's run went through, with what the host recorded about it.
93#[derive(Debug, Clone, PartialEq)]
94pub struct DecisionPoint {
95    pub task_id: String,
96    /// A stable name for the kind of check, such as `tool_budget_block`.
97    pub code: String,
98    /// Whether it was at least a warning. Anything lighter teaches nothing.
99    pub warning: bool,
100    pub details: DecisionDetails,
101    /// How the host's last end record for the task says it ended; `None`
102    /// when it has none or cannot read it.
103    pub task_ending: Option<TaskEnding>,
104}
105
106/// The fields of a decision point the failure patterns read. Absent or
107/// mistyped values read as their default.
108#[derive(Debug, Clone, Default, PartialEq, Eq)]
109pub struct DecisionDetails {
110    pub tool: Option<String>,
111    pub count: u64,
112    pub action: Option<String>,
113    pub consecutive_count: u64,
114    pub unique_args: u64,
115    pub is_diverse: bool,
116    pub tools: Vec<String>,
117    pub prior_semantic_failures: u64,
118    pub prior_calls: u64,
119    pub required_evidence_kind: Option<String>,
120    pub target: Option<String>,
121    pub stall_mode: Option<String>,
122}
123
124impl DecisionDetails {
125    /// The fields of a host's free-form decision metadata.
126    pub fn from_metadata(metadata: &Value) -> Self {
127        let text = |key: &str| {
128            metadata
129                .get(key)
130                .and_then(Value::as_str)
131                .map(str::to_string)
132        };
133        let number = |key: &str| metadata.get(key).and_then(Value::as_u64).unwrap_or(0);
134        Self {
135            tool: text("tool"),
136            count: number("count"),
137            action: text("action"),
138            consecutive_count: number("consecutive_count"),
139            unique_args: number("unique_args"),
140            is_diverse: metadata
141                .get("is_diverse")
142                .and_then(Value::as_bool)
143                .unwrap_or(false),
144            tools: metadata
145                .get("tools")
146                .and_then(Value::as_array)
147                .map(|items| {
148                    items
149                        .iter()
150                        .filter_map(|item| item.as_str().map(str::to_string))
151                        .collect()
152                })
153                .unwrap_or_default(),
154            prior_semantic_failures: number("prior_semantic_failures"),
155            prior_calls: number("prior_calls"),
156            required_evidence_kind: text("required_evidence_kind"),
157            target: text("target"),
158            stall_mode: text("stall_mode"),
159        }
160    }
161}
162
163/// A plan the session finished, with the steps that completed.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct CompletedPlan {
166    pub id: String,
167    pub description: String,
168    pub completed_steps: Vec<String>,
169}
170
171/// A successful task with at least two tool calls: a candidate procedure.
172#[derive(Debug, Clone, PartialEq)]
173pub struct ProcedureCandidate {
174    pub task_id: String,
175    pub description: String,
176    /// `tool: summary`, one per call, in order.
177    pub steps: Vec<String>,
178    pub duration_secs: f64,
179}
180
181/// The successful tasks in `trace` worth turning into procedures, in the
182/// order they started.
183pub fn procedure_candidates(trace: &[TraceEvent]) -> Vec<ProcedureCandidate> {
184    let mut order: Vec<&str> = Vec::new();
185    let mut by_task: HashMap<&str, Vec<&TraceEvent>> = HashMap::new();
186    for event in trace {
187        if let Some(task_id) = event.work_task_id() {
188            if !by_task.contains_key(task_id) {
189                order.push(task_id);
190            }
191            by_task.entry(task_id).or_default().push(event);
192        }
193    }
194    let mut candidates = Vec::new();
195    for task_id in order {
196        let events = &by_task[task_id];
197        let description = events.iter().find_map(|event| match event {
198            TraceEvent::TaskStarted { description, .. } => Some(description.clone()),
199            _ => None,
200        });
201        let ending = events.iter().find_map(|event| match event {
202            TraceEvent::TaskEnded {
203                outcome,
204                duration_secs,
205                ..
206            } => Some((*outcome, *duration_secs)),
207            _ => None,
208        });
209        let (Some(description), Some((TaskEnding::Succeeded, duration_secs))) =
210            (description, ending)
211        else {
212            continue;
213        };
214        let steps: Vec<String> = events
215            .iter()
216            .filter_map(|event| match event {
217                TraceEvent::ToolCalled { name, summary, .. } => Some(format!(
218                    "{name}: {}",
219                    summary.clone().unwrap_or_else(|| "...".to_string())
220                )),
221                _ => None,
222            })
223            .collect();
224        if steps.len() >= 2 {
225            candidates.push(ProcedureCandidate {
226                task_id: task_id.to_string(),
227                description,
228                steps,
229                duration_secs,
230            });
231        }
232    }
233    candidates
234}
235
236/// A procedure observed once, from a successful task.
237pub fn procedure_from_task(candidate: &ProcedureCandidate) -> Procedure {
238    let now = Utc::now();
239    let short_id: String = candidate.task_id.chars().take(8).collect();
240    Procedure {
241        id: 0,
242        name: format!("auto_{short_id}"),
243        trigger_pattern: candidate.description.clone(),
244        steps: candidate.steps.clone(),
245        success_count: 1,
246        failure_count: 0,
247        avg_duration_secs: Some(candidate.duration_secs as f32),
248        last_used_at: Some(now),
249        created_at: now,
250        updated_at: now,
251    }
252}
253
254/// A procedure from a completed plan's finished steps, or `None` for fewer
255/// than two.
256pub fn procedure_from_plan(
257    plan_id: &str,
258    description: &str,
259    completed_steps: Vec<String>,
260) -> Option<Procedure> {
261    if completed_steps.len() < 2 {
262        return None;
263    }
264    let now = Utc::now();
265    let short_id: String = plan_id.chars().take(8).collect();
266    Some(Procedure {
267        id: 0,
268        name: format!("plan_{short_id}"),
269        trigger_pattern: description.to_string(),
270        steps: completed_steps,
271        success_count: 1,
272        failure_count: 0,
273        avg_duration_secs: None,
274        last_used_at: Some(now),
275        created_at: now,
276        updated_at: now,
277    })
278}
279
280/// Enough evidence to keep a procedure: at least two steps, observed
281/// working, never failing.
282pub fn meets_evidence_gate(procedure: &Procedure) -> bool {
283    procedure.steps.len() >= 2 && procedure.failure_count == 0 && procedure.success_count >= 1
284}
285
286/// A procedure is a duplicate when an existing trigger is this similar.
287const DUPLICATE_SIMILARITY: f32 = 0.85;
288
289/// Whether a new procedure's trigger embedding duplicates an existing one.
290pub fn duplicates_existing_trigger(trigger: &[f32], existing: &[Vec<f32>]) -> bool {
291    existing
292        .iter()
293        .any(|other| crate::embed::cosine(trigger, other) > DUPLICATE_SIMILARITY)
294}
295
296/// Error-solution pairs: an error followed, within the next nine events,
297/// by a successful tool result. A later success is a correlation, not
298/// proof, so a pair starts with no credit; it earns it on verified reuse.
299pub fn error_solutions(trace: &[TraceEvent]) -> Vec<ErrorSolution> {
300    let work: Vec<&TraceEvent> = trace.iter().filter(|event| event.is_work()).collect();
301    let mut solutions = Vec::new();
302    for (index, event) in work.iter().copied().enumerate() {
303        let TraceEvent::Failed { message, tool, .. } = event else {
304            continue;
305        };
306        let recovery = work
307            .iter()
308            .copied()
309            .take(work.len().min(index + 10))
310            .skip(index + 1)
311            .find_map(|next| match next {
312                TraceEvent::ToolReturned {
313                    name,
314                    succeeded: true,
315                    result,
316                    ..
317                } => Some((name.clone(), truncate(result, 200))),
318                _ => None,
319            });
320        if let Some((recovered_with, summary)) = recovery {
321            let now = Utc::now();
322            solutions.push(ErrorSolution {
323                id: 0,
324                error_pattern: error_pattern(message),
325                domain: tool.clone(),
326                solution_summary: format!("Used {recovered_with} to resolve"),
327                solution_steps: Some(vec![summary]),
328                success_count: 0,
329                failure_count: 0,
330                last_used_at: Some(now),
331                created_at: now,
332            });
333        }
334    }
335    solutions
336}
337
338/// One expertise observation per ended task: the domain its tools belong
339/// to, and whether it succeeded.
340pub fn expertise_updates(trace: &[TraceEvent]) -> Vec<(String, bool)> {
341    trace
342        .iter()
343        .filter_map(|event| match event {
344            TraceEvent::TaskEnded {
345                task_id, outcome, ..
346            } => task_domain(task_id, trace)
347                .map(|domain| (domain, *outcome == TaskEnding::Succeeded)),
348            _ => None,
349        })
350        .collect()
351}
352
353/// The domain of a task, from the tools it called.
354fn task_domain(task_id: &str, trace: &[TraceEvent]) -> Option<String> {
355    let tools: Vec<&str> = trace
356        .iter()
357        .filter_map(|event| match event {
358            TraceEvent::ToolCalled {
359                task_id: Some(id),
360                name,
361                ..
362            } if id == task_id => Some(name.as_str()),
363            _ => None,
364        })
365        .collect();
366    if tools.is_empty() {
367        return None;
368    }
369    Some(
370        if tools.contains(&"terminal") {
371            if tools.iter().any(|tool| tool.contains("git")) {
372                "git"
373            } else {
374                "shell"
375            }
376        } else if tools
377            .iter()
378            .any(|tool| *tool == "web_search" || *tool == "web_fetch")
379        {
380            "research"
381        } else if tools.contains(&"browser") {
382            "browser"
383        } else {
384            "general"
385        }
386        .to_string(),
387    )
388}
389
390/// A lesson from a decision point that signals trouble.
391#[derive(Debug, Clone, PartialEq)]
392pub struct FailurePattern {
393    pub trigger_context: String,
394    pub action: String,
395    pub description: String,
396    pub confidence: f32,
397}
398
399/// The failure patterns in `trace`: one per warning-level decision point
400/// with a known code, and per task at most one for each trigger and action.
401pub fn failure_patterns(trace: &[TraceEvent]) -> Vec<FailurePattern> {
402    let mut seen: HashSet<(String, String, String)> = HashSet::new();
403    let mut patterns = Vec::new();
404    for (index, event) in trace.iter().enumerate() {
405        let TraceEvent::DecisionPoint(decision) = event else {
406            continue;
407        };
408        if !decision.warning {
409            continue;
410        }
411        let recovery_tool = trace[index + 1..].iter().find_map(|next| match next {
412            TraceEvent::ToolReturned {
413                task_id: Some(task_id),
414                name,
415                succeeded: true,
416                ..
417            } if *task_id == decision.task_id => Some(name.as_str()),
418            _ => None,
419        });
420        let Some(pattern) = failure_pattern(decision, recovery_tool) else {
421            continue;
422        };
423        if seen.insert((
424            decision.task_id.clone(),
425            pattern.trigger_context.clone(),
426            pattern.action.clone(),
427        )) {
428            patterns.push(pattern);
429        }
430    }
431    patterns
432}
433
434fn failure_pattern(
435    decision: &DecisionPoint,
436    recovery_tool: Option<&str>,
437) -> Option<FailurePattern> {
438    let code = decision.code.as_str();
439    let details = &decision.details;
440    let tool = details.tool.as_deref().unwrap_or("unknown_tool");
441    let recovery_suffix = recovery_tool
442        .map(|tool| format!(" Previous successful recoveries switched to {tool}."))
443        .unwrap_or_default();
444    let confidence = |base: f32| failure_confidence(base, decision.task_ending, recovery_tool);
445    let pattern = |trigger_context: String, action: &str, description: String, base: f32| {
446        Some(FailurePattern {
447            trigger_context,
448            action: action.to_string(),
449            description,
450            confidence: confidence(base),
451        })
452    };
453
454    match code {
455        "repetitive_call_detection" => {
456            let count = details.count;
457            let hard_stop = details.action.as_deref().unwrap_or("redirect") == "hard_stop";
458            let description = if count > 0 {
459                format!(
460                    "After {count} repeated calls to {tool}, stop retrying the same operation and pivot to a different tool or summarize the blocker.{recovery_suffix}"
461                )
462            } else {
463                format!(
464                    "Repeated calls to {tool} tend to become a dead-end loop; pivot to a different tool or summarize the blocker sooner.{recovery_suffix}"
465                )
466            };
467            pattern(
468                format!("{code}:{tool}"),
469                if hard_stop {
470                    "stop_retrying_identical_calls"
471                } else {
472                    "pivot_to_alternate_tool_or_strategy"
473                },
474                description,
475                if hard_stop { 0.74 } else { 0.62 },
476            )
477        }
478        "consecutive_same_tool_detection" => {
479            let description = if details.is_diverse {
480                format!(
481                    "Even varied {tool} calls can become a loop after {} consecutive uses; switch tools or summarize progress before continuing.{recovery_suffix}",
482                    details.consecutive_count
483                )
484            } else {
485                format!(
486                    "Long {tool} streaks with only {} distinct argument sets usually indicate a loop; change tools or adjust strategy before continuing.{recovery_suffix}",
487                    details.unique_args
488                )
489            };
490            pattern(
491                format!("{code}:{tool}"),
492                "switch_tools_before_long_streaks",
493                description,
494                if details.is_diverse { 0.54 } else { 0.68 },
495            )
496        }
497        "alternating_pattern_detection" => {
498            let mut tools = details.tools.clone();
499            if tools.is_empty() {
500                tools.push("unknown_pair".to_string());
501            }
502            tools.sort();
503            let tool_pair = tools.join(" <-> ");
504            pattern(
505                format!("{code}:{}", tools.join("+")),
506                "break_alternating_tool_loops",
507                format!(
508                    "Alternating between {tool_pair} with low call diversity usually indicates a loop; commit to one path or choose a third tool instead of bouncing between them.{recovery_suffix}"
509                ),
510                0.72,
511            )
512        }
513        "tool_budget_block" => {
514            let semantic_failures = details.prior_semantic_failures;
515            let description = if semantic_failures > 0 {
516                format!(
517                    "Once {tool} has repeated the same semantic failure {semantic_failures} times, stop retrying it and switch strategy earlier.{recovery_suffix}"
518                )
519            } else {
520                format!(
521                    "After {} repeated {tool} calls without enough progress, stop retrying the blocked tool and switch strategy earlier.{recovery_suffix}",
522                    details.prior_calls
523                )
524            };
525            pattern(
526                format!("{code}:{tool}"),
527                "stop_retrying_blocked_tool",
528                description,
529                if semantic_failures > 0 { 0.74 } else { 0.68 },
530            )
531        }
532        "missing_pre_execution_evidence" => {
533            let evidence_kind = details
534                .required_evidence_kind
535                .as_deref()
536                .unwrap_or("direct evidence");
537            let target = details.target.as_deref().unwrap_or("current target");
538            pattern(
539                format!("{code}:{tool}:{evidence_kind}"),
540                "gather_direct_evidence_before_mutation",
541                format!(
542                    "Before using {tool}, gather {evidence_kind} for {target} instead of mutating from memory or inference alone.{recovery_suffix}"
543                ),
544                0.82,
545            )
546        }
547        "plan_rejected" => pattern(
548            code.to_string(),
549            "replan_first_risky_step_before_execution",
550            format!(
551                "When the structured first-step plan is rejected, revise the target or first action before executing again.{recovery_suffix}"
552            ),
553            0.74,
554        ),
555        "critique_rejected" => pattern(
556            code.to_string(),
557            "address_critique_before_retry",
558            format!(
559                "If the critique pass rejects the first risky action, fix the missing evidence or target assumptions before retrying.{recovery_suffix}"
560            ),
561            0.76,
562        ),
563        "target_scope_violation" => pattern(
564            format!("{code}:{tool}"),
565            "confirm_target_scope_before_mutation",
566            format!(
567                "If {tool} attempts to act outside the compiled target scope, stop and confirm the correct repo/file target before retrying.{recovery_suffix}"
568            ),
569            0.86,
570        ),
571        "tool_contract_violation" => pattern(
572            format!("{code}:{tool}"),
573            "fix_tool_arguments_before_retry",
574            format!(
575                "Deterministic argument-contract failures on {tool} should be corrected locally before retrying the step.{recovery_suffix}"
576            ),
577            0.72,
578        ),
579        "contradictory_file_evidence" => pattern(
580            code.to_string(),
581            "recheck_conflicting_state_before_completion",
582            format!(
583                "When file evidence contradicts itself, re-read the target before claiming completion instead of trusting stale state.{recovery_suffix}"
584            ),
585            0.80,
586        ),
587        "verification_pending" | "verification_unavailable_in_phase" => pattern(
588            code.to_string(),
589            "run_verification_before_claiming_success",
590            format!(
591                "Do not claim success while verification is pending; either run the check or surface a precise partial result.{recovery_suffix}"
592            ),
593            0.82,
594        ),
595        "validation_budget_exhausted" | "execution_budget_exhausted" => pattern(
596            code.to_string(),
597            "reduce_scope_when_budget_exhausts",
598            format!(
599                "When execution or validation budget is exhausted, reduce scope or checkpoint progress instead of pushing through unverified completion.{recovery_suffix}"
600            ),
601            0.70,
602        ),
603        "pre_tool_deferral_stall" => pattern(
604            code.to_string(),
605            "ask_clarifying_question_or_take_next_tool_step",
606            format!(
607                "Repeatedly deferring before taking any tool step leads to failure; ask one concrete clarification question or take the next tool action earlier.{recovery_suffix}"
608            ),
609            0.72,
610        ),
611        "stall" => pattern(
612            format!(
613                "{code}:{}",
614                details.stall_mode.as_deref().unwrap_or("generic")
615            ),
616            "summarize_progress_or_change_strategy",
617            format!(
618                "When iterations stop producing new evidence, stop looping, summarize what is known, and change strategy instead of continuing the same pattern.{recovery_suffix}"
619            ),
620            0.76,
621        ),
622        "hard_iteration_cap" => pattern(
623            code.to_string(),
624            "finish_before_hard_iteration_cap",
625            format!(
626                "As the hard iteration cap approaches, stop repeating work and return the best partial answer or next concrete step earlier.{recovery_suffix}"
627            ),
628            0.60,
629        ),
630        "task_timeout" => pattern(
631            code.to_string(),
632            "checkpoint_and_reduce_scope_before_timeout",
633            format!(
634                "Long-running tasks that approach the timeout should checkpoint progress and reduce scope earlier instead of continuing the same loop.{recovery_suffix}"
635            ),
636            0.64,
637        ),
638        "task_token_budget" => pattern(
639            code.to_string(),
640            "reduce_token_spend_and_checkpoint",
641            format!(
642                "When task token spend stays high, reduce scope, checkpoint findings, or stop earlier instead of consuming the full task budget.{recovery_suffix}"
643            ),
644            0.68,
645        ),
646        "scheduled_run_budget" => pattern(
647            code.to_string(),
648            "checkpoint_scheduled_run_before_budget_exhaustion",
649            format!(
650                "Scheduled runs should bail out once progress slows; checkpoint the current state instead of burning the full per-run token budget.{recovery_suffix}"
651            ),
652            0.70,
653        ),
654        "goal_daily_token_budget" => pattern(
655            code.to_string(),
656            "checkpoint_goal_work_before_daily_budget_exhaustion",
657            format!(
658                "For recurring goal work, avoid spending the full daily budget in one pass; checkpoint progress and defer the rest earlier.{recovery_suffix}"
659            ),
660            0.70,
661        ),
662        "daily_token_budget" => pattern(
663            code.to_string(),
664            "checkpoint_before_daily_budget_exhaustion",
665            format!(
666                "When the session is nearing the daily token budget, checkpoint useful progress and stop earlier instead of exhausting the remaining budget.{recovery_suffix}"
667            ),
668            0.70,
669        ),
670        "task_token_budget_warning" => pattern(
671            code.to_string(),
672            "reduce_token_spend_before_budget_warning",
673            format!(
674                "High token-spend phases should trigger earlier summarization or scope reduction before the task budget is exhausted.{recovery_suffix}"
675            ),
676            0.45,
677        ),
678        "soft_iteration_warning" => pattern(
679            code.to_string(),
680            "adjust_strategy_before_soft_iteration_warning",
681            format!(
682                "When the soft iteration warning appears, summarize progress or change strategy instead of continuing the same loop.{recovery_suffix}"
683            ),
684            0.45,
685        ),
686        _ => None,
687    }
688}
689
690fn failure_confidence(
691    base: f32,
692    task_ending: Option<TaskEnding>,
693    recovery_tool: Option<&str>,
694) -> f32 {
695    let ending_bonus = match task_ending {
696        Some(TaskEnding::Failed) => 0.08,
697        Some(TaskEnding::Partial) => 0.04,
698        Some(TaskEnding::Succeeded) | None => 0.0,
699    };
700    let recovery_bonus = if recovery_tool.is_some() { 0.03 } else { 0.0 };
701    (base + ending_bonus + recovery_bonus).clamp(0.1, 0.96)
702}
703
704/// What one pass over a trace wrote.
705#[derive(Debug, Default, Clone, PartialEq, Eq)]
706pub struct LearningReport {
707    pub procedures: usize,
708    pub error_solutions: usize,
709    pub expertise_updates: usize,
710    pub failure_patterns: usize,
711}
712
713/// The tool that writes facts in the daemon's own memory, whose calls say
714/// which user message a fact came from.
715const REMEMBER_FACT_TOOL: &str = "remember_fact";
716
717/// Learns from what a session's tasks did and writes it through the stores:
718/// procedures, error solutions, expertise, failure patterns and the
719/// provenance of facts written along the way.
720pub struct TaskLearner {
721    stores: Arc<dyn MemoryStores>,
722    embedder: Option<Arc<dyn Embedder>>,
723    enhancer: Option<ProcedureEnhancer>,
724    evidence_gate: bool,
725}
726
727impl TaskLearner {
728    pub fn new(stores: Arc<dyn MemoryStores>) -> Self {
729        Self {
730            stores,
731            embedder: None,
732            enhancer: None,
733            evidence_gate: false,
734        }
735    }
736
737    /// Recognizes duplicates and stores trigger embeddings with `embedder`.
738    pub fn with_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
739        self.embedder = Some(embedder);
740        self
741    }
742
743    /// Rewrites procedures into reusable ones with `enhancer`.
744    pub fn with_enhancer(mut self, enhancer: ProcedureEnhancer) -> Self {
745        self.enhancer = Some(enhancer);
746        self
747    }
748
749    /// Keeps only procedures with enough evidence ([`meets_evidence_gate`]).
750    pub fn with_evidence_gate(mut self, enforce: bool) -> Self {
751        self.evidence_gate = enforce;
752        self
753    }
754
755    /// Learn from `trace` and the session's finished `plans`. A row that
756    /// cannot be written is logged and skipped.
757    pub async fn learn(&self, trace: &[TraceEvent], plans: &[CompletedPlan]) -> LearningReport {
758        let mut report = LearningReport::default();
759        self.learn_procedures(trace, &mut report).await;
760        self.learn_plans(plans, &mut report).await;
761        for solution in error_solutions(trace) {
762            match self
763                .stores
764                .record_error_solution_observation(&solution)
765                .await
766            {
767                Ok(()) => report.error_solutions += 1,
768                Err(e) => warn!("Failed to save error solution: {e}"),
769            }
770        }
771        for (domain, success) in expertise_updates(trace) {
772            match self.stores.record_task_outcome(&domain, success).await {
773                Ok(()) => report.expertise_updates += 1,
774                Err(e) => warn!("Failed to update expertise: {e}"),
775            }
776        }
777        for pattern in failure_patterns(trace) {
778            match self
779                .stores
780                .record_behavior_pattern(
781                    "failure",
782                    &pattern.description,
783                    Some(&pattern.trigger_context),
784                    Some(&pattern.action),
785                    pattern.confidence,
786                    1,
787                )
788                .await
789            {
790                Ok(()) => report.failure_patterns += 1,
791                Err(error) => warn!(
792                    trigger_context = %pattern.trigger_context,
793                    action = %pattern.action,
794                    %error,
795                    "Failed to record failure pattern from decision point"
796                ),
797            }
798        }
799        self.stamp_fact_provenance(trace).await;
800        report
801    }
802
803    /// Candidates are all checked against what was stored before this pass,
804    /// and enhanced, before the first one is saved.
805    async fn learn_procedures(&self, trace: &[TraceEvent], report: &mut LearningReport) {
806        let mut procedures = Vec::new();
807        for candidate in procedure_candidates(trace) {
808            if self.is_duplicate(&candidate.description).await {
809                continue;
810            }
811            let procedure = procedure_from_task(&candidate);
812            procedures.push(self.enhanced(procedure, &candidate.description).await);
813        }
814        for procedure in procedures {
815            if self.evidence_gate && !meets_evidence_gate(&procedure) {
816                info!(
817                    trigger = %procedure.trigger_pattern,
818                    steps = procedure.steps.len(),
819                    "Skipping procedure without sufficient evidence"
820                );
821                continue;
822            }
823            match self.stores.record_procedure_observation(&procedure).await {
824                Ok(()) => {
825                    self.store_trigger_embedding(&procedure).await;
826                    report.procedures += 1;
827                }
828                Err(e) => warn!("Failed to save procedure: {e}"),
829            }
830        }
831    }
832
833    /// Plans go one by one, so each sees the ones saved before it.
834    async fn learn_plans(&self, plans: &[CompletedPlan], report: &mut LearningReport) {
835        for plan in plans {
836            if plan.completed_steps.len() < 2 || self.is_duplicate(&plan.description).await {
837                continue;
838            }
839            let Some(procedure) =
840                procedure_from_plan(&plan.id, &plan.description, plan.completed_steps.clone())
841            else {
842                continue;
843            };
844            let procedure = self.enhanced(procedure, &plan.description).await;
845            if self.evidence_gate && !meets_evidence_gate(&procedure) {
846                info!(
847                    trigger = %procedure.trigger_pattern,
848                    "Skipping plan-based procedure without evidence"
849                );
850                continue;
851            }
852            match self.stores.record_procedure_observation(&procedure).await {
853                Ok(()) => {
854                    self.store_trigger_embedding(&procedure).await;
855                    report.procedures += 1;
856                }
857                Err(e) => warn!("Failed to save plan-based procedure: {e}"),
858            }
859        }
860    }
861
862    /// Whether a stored procedure's trigger is close to `description`. Any
863    /// failure to tell reads as not a duplicate.
864    async fn is_duplicate(&self, description: &str) -> bool {
865        let Some(embedder) = &self.embedder else {
866            return false;
867        };
868        let Ok(new_embedding) = embedding_of(embedder.as_ref(), description).await else {
869            return false;
870        };
871        let Ok(existing) = self.stores.procedure_trigger_embeddings().await else {
872            return false;
873        };
874        duplicates_existing_trigger(&new_embedding, &existing)
875    }
876
877    /// `procedure` rewritten by the model, or unchanged when there is no
878    /// model or it declines.
879    async fn enhanced(&self, procedure: Procedure, task_description: &str) -> Procedure {
880        let Some(enhancer) = &self.enhancer else {
881            return procedure;
882        };
883        enhancer
884            .enhance(&procedure, task_description)
885            .await
886            .unwrap_or(procedure)
887    }
888
889    async fn store_trigger_embedding(&self, procedure: &Procedure) {
890        let Some(embedder) = &self.embedder else {
891            return;
892        };
893        if let Ok(embedding) = embedding_of(embedder.as_ref(), &procedure.trigger_pattern).await {
894            let _ = self
895                .stores
896                .set_procedure_trigger_embedding(&procedure.name, &embedding)
897                .await;
898        }
899    }
900
901    /// Mark each fact written by the remember tool as stated by the owner
902    /// or derived. Owner-stated (`user_stated`, rank 2) needs the call's
903    /// typed `evidence`: a quote the model gives as the owner's words, found
904    /// in the last user message, which the owner wrote. A value that merely
905    /// occurs in the message ("blue" in "I don't like blue", or in pasted
906    /// text) proves nothing; without such a quote the fact is `derived`.
907    async fn stamp_fact_provenance(&self, trace: &[TraceEvent]) {
908        let mut last_user_message: Option<(&str, DateTime<Utc>, bool)> = None;
909        for event in trace {
910            match event {
911                TraceEvent::UserMessage {
912                    content,
913                    at,
914                    owner_authored,
915                } => {
916                    last_user_message = Some((content, *at, *owner_authored));
917                }
918                TraceEvent::ToolCalled {
919                    name,
920                    arguments: Some(arguments),
921                    ..
922                } if name == REMEMBER_FACT_TOOL => {
923                    for fact in remembered_facts(arguments) {
924                        let mut source = "derived";
925                        let mut source_excerpt = None;
926                        let mut first_seen_at = None;
927                        if let Some((message, at, owner_authored)) = last_user_message {
928                            if owner_authored
929                                && fact.evidence.as_deref().is_some_and(|evidence| {
930                                    crate::progressive::quote_occurs_in(evidence, message)
931                                })
932                            {
933                                source = "user_stated";
934                            }
935                            source_excerpt = Some(truncate_chars(message, 200));
936                            first_seen_at = Some(at);
937                        }
938                        let _ = self
939                            .stores
940                            .stamp_fact_provenance(
941                                &fact.category,
942                                &fact.key,
943                                source,
944                                first_seen_at,
945                                source_excerpt.as_deref(),
946                            )
947                            .await;
948                    }
949                }
950                _ => {}
951            }
952        }
953    }
954}
955
956/// One fact of a remember call, with the quote the model gave as the
957/// owner's words, if any.
958struct RememberedFact {
959    category: String,
960    key: String,
961    evidence: Option<String>,
962}
963
964/// The facts of a remember call: its `facts` list when it has one,
965/// otherwise the call's own fields. An entry without its own `evidence`
966/// takes the call's.
967fn remembered_facts(arguments: &Value) -> Vec<RememberedFact> {
968    let text =
969        |value: &Value, name: &str| value.get(name).and_then(Value::as_str).map(str::to_string);
970    let call_evidence = text(arguments, "evidence");
971    let entry = |fact: &Value| {
972        text(fact, "value")?;
973        Some(RememberedFact {
974            category: text(fact, "category")?,
975            key: text(fact, "key")?,
976            evidence: text(fact, "evidence").or_else(|| call_evidence.clone()),
977        })
978    };
979    match arguments.get("facts").and_then(Value::as_array) {
980        Some(facts) => facts.iter().filter_map(entry).collect(),
981        None => entry(arguments).into_iter().collect(),
982    }
983}
984
985/// Rewrites an observed procedure into a reusable one with a model: a
986/// purpose name, a general trigger and clean steps.
987#[derive(Clone)]
988pub struct ProcedureEnhancer {
989    provider: Arc<dyn Provider>,
990    model: String,
991}
992
993impl ProcedureEnhancer {
994    pub fn new(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
995        Self {
996            provider,
997            model: model.into(),
998        }
999    }
1000
1001    /// The enhanced procedure, or `None` when the model fails, declines it
1002    /// as too specific (`skip`), or returns no name or trigger. Steps whose
1003    /// count differs from the original by more than one are not trusted;
1004    /// the original steps are kept.
1005    pub async fn enhance(
1006        &self,
1007        procedure: &Procedure,
1008        task_description: &str,
1009    ) -> Option<Procedure> {
1010        let tool_sequence = procedure
1011            .steps
1012            .iter()
1013            .enumerate()
1014            .map(|(i, step)| format!("{}. {step}", i + 1))
1015            .collect::<Vec<_>>()
1016            .join("\n");
1017        let duration = procedure
1018            .avg_duration_secs
1019            .map(|d| format!("{d:.0}"))
1020            .unwrap_or_else(|| "unknown".to_string());
1021        let step_count = procedure.steps.len();
1022        let user_prompt = format!(
1023            "Given a task that completed successfully, generate a clean procedure definition.\n\n\
1024             Task: {task_description}\n\
1025             Tools used:\n{tool_sequence}\n\
1026             Duration: {duration}s\n\n\
1027             Respond with JSON:\n\
1028             {{\n\
1029               \"name\": \"descriptive-kebab-case-name\",\n\
1030               \"trigger_pattern\": \"general description of when to use this\",\n\
1031               \"steps\": [\"Step 1: ...\", \"Step 2: ...\"],\n\
1032               \"skip\": false\n\
1033             }}\n\n\
1034             Rules:\n\
1035             - name: 2-4 word kebab-case describing PURPOSE (not tools used)\n\
1036             - trigger_pattern: General description, not the exact task\n\
1037             - steps: Actionable instructions including tool names and key parameters\n\
1038             - skip: true if too context-specific to be reusable\n\
1039             - Step count must match original ({step_count} steps)"
1040        );
1041        let request = ModelRequest {
1042            model: self.model.clone(),
1043            messages: vec![
1044                Message::system(
1045                    "You generate clean procedure definitions from successful task sequences.\nRespond with ONLY valid JSON.",
1046                ),
1047                Message::user(user_prompt),
1048            ],
1049            ..Default::default()
1050        };
1051        let response = match self.provider.complete(&request).await {
1052            Ok(response) => response,
1053            Err(e) => {
1054                warn!("LLM enhancement failed for procedure: {e}");
1055                return None;
1056            }
1057        };
1058        let text = response.text.trim();
1059        let json = match (text.find('{'), text.rfind('}')) {
1060            (Some(start), Some(end)) if end >= start => &text[start..=end],
1061            _ => text,
1062        };
1063        let parsed: serde_json::Value = match serde_json::from_str(json) {
1064            Ok(value) => value,
1065            Err(e) => {
1066                warn!("Failed to parse LLM procedure enhancement: {e}");
1067                return None;
1068            }
1069        };
1070        if parsed
1071            .get("skip")
1072            .and_then(serde_json::Value::as_bool)
1073            .unwrap_or(false)
1074        {
1075            return None;
1076        }
1077        let text_field = |key: &str| {
1078            parsed
1079                .get(key)
1080                .and_then(serde_json::Value::as_str)
1081                .unwrap_or_default()
1082                .to_string()
1083        };
1084        let (name, trigger_pattern) = (text_field("name"), text_field("trigger_pattern"));
1085        if name.is_empty() || trigger_pattern.is_empty() {
1086            return None;
1087        }
1088        let steps: Vec<String> = parsed
1089            .get("steps")
1090            .and_then(serde_json::Value::as_array)
1091            .map(|items| {
1092                items
1093                    .iter()
1094                    .filter_map(|s| s.as_str().map(String::from))
1095                    .collect()
1096            })
1097            .unwrap_or_default();
1098        let steps = if steps.is_empty() || steps.len().abs_diff(procedure.steps.len()) > 1 {
1099            procedure.steps.clone()
1100        } else {
1101            steps
1102        };
1103        Some(Procedure {
1104            name,
1105            trigger_pattern,
1106            steps,
1107            ..procedure.clone()
1108        })
1109    }
1110}
1111
1112/// `s` cut to at most `max_len` bytes on a character boundary, ending in
1113/// "..." when cut.
1114fn truncate(s: &str, max_len: usize) -> String {
1115    if s.len() <= max_len {
1116        return s.to_string();
1117    }
1118    let target = max_len.saturating_sub(3);
1119    let end = s
1120        .char_indices()
1121        .map(|(i, _)| i)
1122        .take_while(|&i| i <= target)
1123        .last()
1124        .unwrap_or(0);
1125    format!("{}...", &s[..end])
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130    use aidaemon_core::testing::{ScriptedProvider, text};
1131
1132    use super::*;
1133
1134    fn task(task_id: &str, outcome: TaskEnding, tools: &[&str]) -> Vec<TraceEvent> {
1135        let mut trace = vec![TraceEvent::TaskStarted {
1136            task_id: task_id.into(),
1137            description: format!("Do {task_id}"),
1138        }];
1139        for tool in tools {
1140            trace.push(TraceEvent::ToolCalled {
1141                task_id: Some(task_id.into()),
1142                name: (*tool).into(),
1143                summary: Some("args".into()),
1144                arguments: None,
1145            });
1146        }
1147        trace.push(TraceEvent::TaskEnded {
1148            task_id: task_id.into(),
1149            outcome,
1150            duration_secs: 12.0,
1151        });
1152        trace
1153    }
1154
1155    #[test]
1156    fn only_successful_multi_step_tasks_become_procedures() {
1157        let mut trace = task(
1158            "task-ok-1234",
1159            TaskEnding::Succeeded,
1160            &["terminal", "edit_file"],
1161        );
1162        trace.extend(task(
1163            "task-failed",
1164            TaskEnding::Failed,
1165            &["terminal", "edit_file"],
1166        ));
1167        trace.extend(task("task-short", TaskEnding::Succeeded, &["terminal"]));
1168        let candidates = procedure_candidates(&trace);
1169        assert_eq!(candidates.len(), 1);
1170        assert_eq!(candidates[0].steps, ["terminal: args", "edit_file: args"]);
1171        let procedure = procedure_from_task(&candidates[0]);
1172        assert_eq!(procedure.name, "auto_task-ok-");
1173        assert!(meets_evidence_gate(&procedure));
1174    }
1175
1176    #[test]
1177    fn a_recovered_error_becomes_an_uncredited_solution() {
1178        let trace = vec![
1179            TraceEvent::Failed {
1180                task_id: None,
1181                message: "connection refused at /srv/app/db.rs:10:4".into(),
1182                tool: Some("terminal".into()),
1183            },
1184            TraceEvent::ToolReturned {
1185                task_id: None,
1186                name: "terminal".into(),
1187                succeeded: false,
1188                result: "still down".into(),
1189            },
1190            TraceEvent::ToolReturned {
1191                task_id: None,
1192                name: "run_command".into(),
1193                succeeded: true,
1194                result: "database started".into(),
1195            },
1196        ];
1197        let solutions = error_solutions(&trace);
1198        assert_eq!(solutions.len(), 1);
1199        assert_eq!(solutions[0].solution_summary, "Used run_command to resolve");
1200        assert!(solutions[0].error_pattern.contains("<path>"));
1201        assert_eq!(solutions[0].success_count, 0);
1202    }
1203
1204    #[test]
1205    fn expertise_follows_the_tools_a_task_used() {
1206        let mut trace = task("t1", TaskEnding::Succeeded, &["terminal", "git_commit"]);
1207        trace.extend(task("t2", TaskEnding::Failed, &["web_search"]));
1208        assert_eq!(
1209            expertise_updates(&trace),
1210            [("git".to_string(), true), ("research".to_string(), false)]
1211        );
1212    }
1213
1214    #[test]
1215    fn plans_and_duplicates() {
1216        assert!(procedure_from_plan("plan-1", "deploy", vec!["build".into()]).is_none());
1217        let plan = procedure_from_plan(
1218            "plan-123456789",
1219            "deploy",
1220            vec!["build".into(), "ship".into()],
1221        )
1222        .unwrap();
1223        assert_eq!(plan.name, "plan_plan-123");
1224        assert!(duplicates_existing_trigger(&[1.0, 0.0], &[vec![1.0, 0.01]]));
1225        assert!(!duplicates_existing_trigger(&[1.0, 0.0], &[vec![0.0, 1.0]]));
1226    }
1227
1228    fn decision(code: &str, metadata: Value, ending: Option<TaskEnding>) -> TraceEvent {
1229        TraceEvent::DecisionPoint(DecisionPoint {
1230            task_id: "t1".into(),
1231            code: code.into(),
1232            warning: true,
1233            details: DecisionDetails::from_metadata(&metadata),
1234            task_ending: ending,
1235        })
1236    }
1237
1238    fn returned(task_id: &str, name: &str, succeeded: bool) -> TraceEvent {
1239        TraceEvent::ToolReturned {
1240            task_id: Some(task_id.into()),
1241            name: name.into(),
1242            succeeded,
1243            result: "done".into(),
1244        }
1245    }
1246
1247    #[test]
1248    fn failure_confidence_adds_outcome_and_recovery_and_stays_clamped() {
1249        let trace = vec![
1250            decision(
1251                "repetitive_call_detection",
1252                serde_json::json!({"tool": "terminal", "count": 4, "action": "hard_stop"}),
1253                Some(TaskEnding::Failed),
1254            ),
1255            returned("t1", "terminal", false),
1256            returned("other", "web_fetch", true),
1257            returned("t1", "edit_file", true),
1258        ];
1259        let patterns = failure_patterns(&trace);
1260        assert_eq!(patterns.len(), 1);
1261        assert_eq!(
1262            patterns[0].trigger_context,
1263            "repetitive_call_detection:terminal"
1264        );
1265        assert_eq!(patterns[0].action, "stop_retrying_identical_calls");
1266        assert!(
1267            patterns[0]
1268                .description
1269                .ends_with("Previous successful recoveries switched to edit_file.")
1270        );
1271        assert!((patterns[0].confidence - (0.74 + 0.08 + 0.03)).abs() < 1e-5);
1272        assert!(
1273            (failure_confidence(0.95, Some(TaskEnding::Failed), Some("x")) - 0.96).abs() < 1e-6
1274        );
1275    }
1276
1277    #[test]
1278    fn failure_patterns_drop_unknown_codes_light_severities_and_repeats() {
1279        let mut light = decision("stall", serde_json::json!({}), None);
1280        if let TraceEvent::DecisionPoint(decision) = &mut light {
1281            decision.warning = false;
1282        }
1283        let trace = vec![
1284            light,
1285            decision("not_a_known_code", serde_json::json!({}), None),
1286            decision("stall", serde_json::json!({"stall_mode": "idle"}), None),
1287            decision("stall", serde_json::json!({"stall_mode": "idle"}), None),
1288        ];
1289        let patterns = failure_patterns(&trace);
1290        assert_eq!(patterns.len(), 1);
1291        assert_eq!(patterns[0].trigger_context, "stall:idle");
1292    }
1293
1294    #[test]
1295    fn decision_metadata_reads_mistyped_values_as_defaults() {
1296        let details = DecisionDetails::from_metadata(&serde_json::json!({
1297            "tool": 7, "count": "four", "is_diverse": "yes", "tools": ["a", 1, "b"]
1298        }));
1299        assert_eq!(details.tool, None);
1300        assert_eq!(details.count, 0);
1301        assert!(!details.is_diverse);
1302        assert_eq!(details.tools, ["a", "b"]);
1303    }
1304
1305    /// Decision points and user messages are not work: an error still finds
1306    /// a recovery nine work events away however many sit in between.
1307    #[test]
1308    fn only_work_counts_toward_the_recovery_window() {
1309        let failed = TraceEvent::Failed {
1310            task_id: None,
1311            message: "boom".into(),
1312            tool: None,
1313        };
1314        let mut trace = vec![failed.clone()];
1315        for _ in 0..12 {
1316            trace.push(decision("stall", serde_json::json!({}), None));
1317            trace.push(TraceEvent::UserMessage {
1318                content: "still there?".into(),
1319                at: Utc::now(),
1320                owner_authored: true,
1321            });
1322        }
1323        trace.push(returned("t1", "terminal", true));
1324        assert_eq!(error_solutions(&trace).len(), 1);
1325
1326        let mut too_far = vec![failed];
1327        too_far.extend(std::iter::repeat_n(returned("t1", "terminal", false), 9));
1328        too_far.push(returned("t1", "terminal", true));
1329        assert!(error_solutions(&too_far).is_empty());
1330    }
1331
1332    /// A task's first decision point must not move it ahead of a task that
1333    /// started working earlier.
1334    #[test]
1335    fn decision_points_do_not_reorder_tasks() {
1336        let mut trace = vec![decision("stall", serde_json::json!({}), None)];
1337        trace.extend(task("t2", TaskEnding::Succeeded, &["a", "b"]));
1338        trace.extend(task("t1", TaskEnding::Succeeded, &["a", "b"]));
1339        let order: Vec<String> = procedure_candidates(&trace)
1340            .into_iter()
1341            .map(|candidate| candidate.task_id)
1342            .collect();
1343        assert_eq!(order, ["t2", "t1"]);
1344    }
1345
1346    #[test]
1347    fn truncate_cuts_on_a_character_boundary() {
1348        assert_eq!(truncate("hello", 10), "hello");
1349        assert_eq!(
1350            truncate("hello world, this is a long string", 10),
1351            "hello w..."
1352        );
1353    }
1354
1355    mod learner {
1356        use std::sync::Arc;
1357
1358        use sqlx::SqlitePool;
1359        use sqlx::sqlite::SqlitePoolOptions;
1360
1361        use super::super::*;
1362        use crate::sqlite::SqliteMemory;
1363        use crate::stores::{FactStore, MemoryStores};
1364        use crate::{HashEmbedder, LearningStore};
1365
1366        async fn memory() -> (SqlitePool, SqliteMemory) {
1367            let pool = SqlitePoolOptions::new()
1368                .max_connections(1)
1369                .connect("sqlite::memory:")
1370                .await
1371                .unwrap();
1372            let embedder = Arc::new(HashEmbedder::new(384));
1373            crate::sqlite::migrate(&pool).await.unwrap();
1374            (pool.clone(), SqliteMemory::new(pool, embedder))
1375        }
1376
1377        fn stores(memory: &SqliteMemory) -> Arc<dyn MemoryStores> {
1378            Arc::new(memory.clone())
1379        }
1380
1381        fn remember(arguments: serde_json::Value, name: &str) -> TraceEvent {
1382            TraceEvent::ToolCalled {
1383                task_id: None,
1384                name: name.into(),
1385                summary: None,
1386                arguments: Some(arguments),
1387            }
1388        }
1389
1390        #[tokio::test]
1391        async fn a_known_procedure_gains_a_success_and_keeps_its_definition() {
1392            let (pool, memory) = memory().await;
1393            let trace = super::task(
1394                "task-one",
1395                TaskEnding::Succeeded,
1396                &["terminal", "edit_file"],
1397            );
1398            let learner = TaskLearner::new(stores(&memory));
1399            assert_eq!(learner.learn(&trace, &[]).await.procedures, 1);
1400            let mut changed = super::task("task-one", TaskEnding::Succeeded, &["a", "b", "c"]);
1401            if let TraceEvent::TaskStarted { description, .. } = &mut changed[0] {
1402                *description = "another description".into();
1403            }
1404            assert_eq!(learner.learn(&changed, &[]).await.procedures, 1);
1405            let row: (String, i64, String) =
1406                sqlx::query_as("SELECT trigger_pattern, success_count, steps FROM procedures")
1407                    .fetch_one(&pool)
1408                    .await
1409                    .unwrap();
1410            assert_eq!(row.0, "Do task-one");
1411            assert_eq!(row.1, 2);
1412            assert!(row.2.contains("edit_file"));
1413        }
1414
1415        #[tokio::test]
1416        async fn expertise_counts_and_leaves_the_level_alone() {
1417            let (pool, memory) = memory().await;
1418            let learner = TaskLearner::new(stores(&memory));
1419            let trace = super::task("t1", TaskEnding::Failed, &["web_search"]);
1420            learner.learn(&trace, &[]).await;
1421            learner.learn(&trace, &[]).await;
1422            let row: (i64, i64, i64, String, f64) = sqlx::query_as(
1423                "SELECT tasks_attempted, tasks_succeeded, tasks_failed, current_level, confidence_score
1424                 FROM expertise WHERE domain = 'research'",
1425            )
1426            .fetch_one(&pool)
1427            .await
1428            .unwrap();
1429            assert_eq!((row.0, row.1, row.2), (2, 0, 2));
1430            assert_eq!(row.3, "novice");
1431            assert!((row.4 - 0.1).abs() < 1e-6);
1432        }
1433
1434        #[tokio::test]
1435        async fn duplicates_of_stored_triggers_are_skipped_only_with_an_embedder() {
1436            let (_pool, memory) = memory().await;
1437            let embedder: Arc<dyn Embedder> = Arc::new(HashEmbedder::new(384));
1438            let learner = TaskLearner::new(stores(&memory)).with_embedder(embedder);
1439            let plan = CompletedPlan {
1440                id: "plan-1".into(),
1441                description: "Deploy the Acme Corp site".into(),
1442                completed_steps: vec!["build".into(), "ship".into()],
1443            };
1444            let duplicate = CompletedPlan {
1445                id: "plan-2".into(),
1446                ..plan.clone()
1447            };
1448            let report = learner.learn(&[], &[plan, duplicate]).await;
1449            assert_eq!(report.procedures, 1);
1450            assert_eq!(
1451                memory.procedure_trigger_embeddings().await.unwrap().len(),
1452                1
1453            );
1454        }
1455
1456        #[tokio::test]
1457        async fn remember_calls_stamp_provenance_and_other_tools_do_not() {
1458            let (pool, memory) = memory().await;
1459            for key in ["city", "team", "untouched"] {
1460                memory
1461                    .upsert_fact(
1462                        "profile",
1463                        key,
1464                        "value",
1465                        "agent",
1466                        None,
1467                        crate::records::FactPrivacy::Global,
1468                    )
1469                    .await
1470                    .unwrap();
1471            }
1472            let at = Utc::now();
1473            let trace = vec![
1474                remember(
1475                    serde_json::json!({"category": "profile", "key": "team", "value": "x"}),
1476                    "remember_fact",
1477                ),
1478                TraceEvent::UserMessage {
1479                    content: "Alice Rivera lives in Lisbon".into(),
1480                    at,
1481                    owner_authored: true,
1482                },
1483                remember(
1484                    serde_json::json!({"facts": [
1485                        {"category": "profile", "key": "city", "value": "LISBON",
1486                         "evidence": "lives in Lisbon"}
1487                    ]}),
1488                    "remember_fact",
1489                ),
1490                remember(
1491                    serde_json::json!({"category": "profile", "key": "untouched", "value": "Lisbon"}),
1492                    "another_memory_tool",
1493                ),
1494            ];
1495            TaskLearner::new(stores(&memory)).learn(&trace, &[]).await;
1496            let rows: Vec<(String, String, Option<String>, Option<String>)> = sqlx::query_as(
1497                "SELECT key, source, first_seen_at, source_excerpt FROM facts ORDER BY key",
1498            )
1499            .fetch_all(&pool)
1500            .await
1501            .unwrap();
1502            assert_eq!(rows[0].0, "city");
1503            assert_eq!(rows[0].1, "user_stated");
1504            assert_eq!(rows[0].2.as_deref(), Some(at.to_rfc3339().as_str()));
1505            assert_eq!(rows[0].3.as_deref(), Some("Alice Rivera lives in Lisbon"));
1506            assert_eq!(rows[1].0, "team");
1507            assert_eq!(rows[1].1, "derived");
1508            assert_eq!(rows[1].2, None);
1509            assert_eq!(rows[2].1, "agent");
1510        }
1511
1512        /// A value found in the owner's message is not their statement of
1513        /// it: only a quote of their words, in a message they wrote, is.
1514        #[tokio::test]
1515        async fn only_an_owner_quote_makes_a_remembered_fact_owner_stated() {
1516            let cases = [
1517                // The value occurs in the message, but no quote was given.
1518                ("I don't like blue at all", true, None),
1519                // The quote is not in the message.
1520                (
1521                    "I don't like blue at all",
1522                    true,
1523                    Some("my favorite color is blue"),
1524                ),
1525                // The quote is in the message, which the owner did not write.
1526                (
1527                    "My favorite color is blue",
1528                    false,
1529                    Some("favorite color is blue"),
1530                ),
1531            ];
1532            for (message, owner_authored, evidence) in cases {
1533                let (pool, memory) = memory().await;
1534                let mut call = serde_json::json!(
1535                    {"category": "preference", "key": "favorite_color", "value": "blue"}
1536                );
1537                if let Some(evidence) = evidence {
1538                    call["evidence"] = evidence.into();
1539                }
1540                let trace = vec![
1541                    TraceEvent::UserMessage {
1542                        content: message.into(),
1543                        at: Utc::now(),
1544                        owner_authored,
1545                    },
1546                    remember(call, "remember_fact"),
1547                ];
1548                memory
1549                    .upsert_fact(
1550                        "preference",
1551                        "favorite_color",
1552                        "blue",
1553                        "agent",
1554                        None,
1555                        crate::records::FactPrivacy::Global,
1556                    )
1557                    .await
1558                    .unwrap();
1559                TaskLearner::new(stores(&memory)).learn(&trace, &[]).await;
1560                let source: String =
1561                    sqlx::query_scalar("SELECT source FROM facts WHERE key = 'favorite_color'")
1562                        .fetch_one(&pool)
1563                        .await
1564                        .unwrap();
1565                assert_eq!(source, "derived", "{message} / {evidence:?}");
1566            }
1567        }
1568
1569        #[tokio::test]
1570        async fn the_backfill_embeds_what_has_no_current_embedding() {
1571            let (pool, memory) = memory().await;
1572            sqlx::query(
1573                "INSERT INTO error_solutions (error_pattern, domain, solution_summary, created_at)
1574                 VALUES ('connection refused', '', 'Used terminal to resolve', '2026-01-01')",
1575            )
1576            .execute(&pool)
1577            .await
1578            .unwrap();
1579            let embedder = HashEmbedder::new(384);
1580            assert!(
1581                crate::backfill_learning_embeddings(&memory, &embedder)
1582                    .await
1583                    .unwrap()
1584            );
1585            assert!(
1586                !crate::backfill_learning_embeddings(&memory, &embedder)
1587                    .await
1588                    .unwrap()
1589            );
1590            let embedded: (Option<Vec<u8>>,) =
1591                sqlx::query_as("SELECT error_embedding FROM error_solutions")
1592                    .fetch_one(&pool)
1593                    .await
1594                    .unwrap();
1595            assert!(embedded.0.is_some());
1596        }
1597    }
1598
1599    #[tokio::test]
1600    async fn enhancement_keeps_original_steps_when_the_count_drifts() {
1601        let original = procedure_from_task(
1602            &procedure_candidates(&task(
1603                "t1",
1604                TaskEnding::Succeeded,
1605                &["terminal", "edit_file"],
1606            ))[0],
1607        );
1608        let reply = r#"{"name":"fix-build","trigger_pattern":"when the build breaks",
1609            "steps":["a","b","c","d"],"skip":false}"#;
1610        let enhanced =
1611            ProcedureEnhancer::new(Arc::new(ScriptedProvider::new([text(reply)])), "mock")
1612                .enhance(&original, "Do t1")
1613                .await
1614                .unwrap();
1615        assert_eq!(enhanced.name, "fix-build");
1616        assert_eq!(enhanced.steps, original.steps);
1617        let skipped = ProcedureEnhancer::new(
1618            Arc::new(ScriptedProvider::new([text(r#"{"skip":true}"#)])),
1619            "mock",
1620        )
1621        .enhance(&original, "Do t1")
1622        .await;
1623        assert!(skipped.is_none());
1624    }
1625}