roboticus-agent 0.11.3

Agent core with ReAct loop, policy engine, injection defense, memory system, and skill loader
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Learning loop — detect successful multi-step tool sequences from completed
//! sessions and synthesize reusable skill documents.
//!
//! # Architecture
//!
//! When a session closes (TTL expiry or rotation), the governor calls
//! [`learn_on_close`].  This function:
//!
//! 1. Loads all tool calls for the session via `get_tool_calls_for_session()`
//! 2. Flattens them chronologically and runs [`detect_candidate_procedures`]
//! 3. For each candidate, either reinforces an existing learned skill or
//!    synthesises a new SKILL.md and persists it
//!
//! No LLM call is involved — learning is pure template synthesis from observed
//! tool-call data, keeping the hot path fast and deterministic.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use roboticus_core::config::LearningConfig;
use roboticus_db::Database;
use roboticus_db::sessions::Session;
use roboticus_db::tools::ToolCallRecord;
use tracing::{debug, info, warn};

// ── Types ──────────────────────────────────────────────────────

/// A candidate procedure detected from a session's tool-call history.
#[derive(Debug, Clone)]
pub struct CandidateProcedure {
    /// Auto-generated name based on the tool chain (e.g. "read-edit-bash").
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Ordered tool names that compose this procedure.
    pub tool_sequence: Vec<String>,
    /// Fraction of tools in the sequence that succeeded (0.0–1.0).
    pub success_ratio: f64,
    /// The individual steps with input/output summaries.
    pub steps: Vec<ProcedureStep>,
}

/// A single step within a candidate procedure.
#[derive(Debug, Clone)]
pub struct ProcedureStep {
    pub tool_name: String,
    pub input_summary: String,
    pub output_summary: Option<String>,
    pub status: String,
}

// ── Detection ──────────────────────────────────────────────────

/// Flatten tool calls from all turns into chronological order, then detect
/// consecutive sequences of ≥ `min_length` tools where the success ratio
/// meets the threshold.
pub fn detect_candidate_procedures(
    tool_calls_by_turn: &HashMap<String, Vec<ToolCallRecord>>,
    min_length: usize,
    min_success_ratio: f64,
) -> Vec<CandidateProcedure> {
    // Flatten all tool calls and sort by created_at.
    let mut all_calls: Vec<&ToolCallRecord> =
        tool_calls_by_turn.values().flat_map(|v| v.iter()).collect();
    all_calls.sort_by(|a, b| a.created_at.cmp(&b.created_at));

    if all_calls.len() < min_length {
        return Vec::new();
    }

    // Sliding-window: find contiguous runs of ≥ min_length tools that meet
    // the success threshold.  We skip trivially repeated single-tool runs
    // (e.g. three consecutive "bash" calls).
    let mut candidates: Vec<CandidateProcedure> = Vec::new();

    // Try windows of min_length up to 2×min_length (cap to avoid noise).
    // Also cap the input to the last 200 tool calls to avoid quadratic blowup
    // on very long sessions.
    let max_input = 200;
    let all_calls = if all_calls.len() > max_input {
        &all_calls[all_calls.len() - max_input..]
    } else {
        &all_calls[..]
    };
    let max_window = (min_length * 2).min(all_calls.len());
    for window_size in min_length..=max_window {
        for window in all_calls.windows(window_size) {
            let success_count = window.iter().filter(|c| c.status == "success").count();
            let ratio = success_count as f64 / window.len() as f64;
            if ratio < min_success_ratio {
                continue;
            }

            let tool_seq: Vec<String> = window.iter().map(|c| c.tool_name.clone()).collect();

            // Skip if all tools are identical (e.g. ["bash","bash","bash"]).
            let distinct: std::collections::HashSet<&str> =
                tool_seq.iter().map(|s| s.as_str()).collect();
            if distinct.len() < 2 {
                continue;
            }

            // Use sanitized name as the dedup key — this matches the DB/filename key
            // so two raw names that sanitize to the same string are correctly deduped.
            let name = sanitize_name(&tool_seq.join("-"));
            if candidates.iter().any(|c| c.name == name) {
                continue;
            }

            let steps: Vec<ProcedureStep> = window
                .iter()
                .map(|c| ProcedureStep {
                    tool_name: c.tool_name.clone(),
                    input_summary: truncate(&c.input, 120),
                    output_summary: c.output.as_deref().map(|o| truncate(o, 120)),
                    status: c.status.clone(),
                })
                .collect();

            let description = format!(
                "{}-step procedure using {}",
                steps.len(),
                distinct_tools_display(&tool_seq),
            );

            candidates.push(CandidateProcedure {
                name,
                description,
                tool_sequence: tool_seq,
                success_ratio: ratio,
                steps,
            });
        }
    }

    candidates
}

// ── Synthesis ──────────────────────────────────────────────────

/// Generate a SKILL.md document from a candidate procedure.
///
/// Format: YAML frontmatter (`---` delimited, matching `parse_instruction_md`)
/// followed by markdown body (steps, tool chain, when to use).
pub fn synthesize_skill_md(candidate: &CandidateProcedure) -> String {
    let triggers: Vec<&str> = {
        let mut seen = std::collections::HashSet::new();
        candidate
            .tool_sequence
            .iter()
            .filter(|t| seen.insert(t.as_str()))
            .map(|t| t.as_str())
            .collect()
    };

    let mut md = String::new();

    // YAML frontmatter (must use `---` delimiters to match SkillLoader)
    md.push_str("---\n");
    md.push_str(&format!("name: {}\n", sanitize_name(&candidate.name)));
    md.push_str(&format!(
        "description: \"{}\"\n",
        candidate.description.replace('"', "'")
    ));
    // triggers as YAML list — quote values to handle special chars in tool names
    // (e.g. "mcp:read_file", "[bash]", "tool/sub")
    md.push_str("triggers:\n");
    for t in &triggers {
        md.push_str(&format!("  - \"{}\"\n", t.replace('"', "'")));
    }
    md.push_str("priority: 50\n");
    md.push_str("version: \"0.0.1\"\n");
    md.push_str("author: learned\n");
    md.push_str("---\n\n");

    // Markdown body
    md.push_str(&format!("# {}\n\n", candidate.description));
    md.push_str(&format!(
        "Learned from a successful {}-step tool sequence.\n\n",
        candidate.steps.len()
    ));

    md.push_str("## Steps\n\n");
    for (i, step) in candidate.steps.iter().enumerate() {
        md.push_str(&format!(
            "{}. **{}** ({})\n",
            i + 1,
            step.tool_name,
            step.status
        ));
        // Escape backticks in input/output to prevent broken inline code fences
        let safe_input = step.input_summary.replace('`', "'");
        md.push_str(&format!("   - Input: `{safe_input}`\n"));
        if let Some(ref out) = step.output_summary {
            let safe_output = out.replace('`', "'");
            md.push_str(&format!("   - Output: `{safe_output}`\n"));
        }
    }
    md.push('\n');

    md.push_str("## When to Use\n\n");
    md.push_str(&format!(
        "This procedure applies when the agent needs to use {} in sequence.\n",
        distinct_tools_display(&candidate.tool_sequence),
    ));

    md
}

/// Write a learned skill to disk under `{skills_dir}/learned/`.
///
/// Uses atomic write (write to `.tmp` then rename) so that a concurrent
/// `SkillLoader` never observes a partially-written `.md` file.
pub fn write_learned_skill(
    skills_dir: &Path,
    candidate: &CandidateProcedure,
    md_content: &str,
) -> roboticus_core::Result<PathBuf> {
    let learned_dir = skills_dir.join("learned");
    std::fs::create_dir_all(&learned_dir).map_err(|e| {
        roboticus_core::RoboticusError::Config(format!("failed to create learned skills dir: {e}"))
    })?;

    let filename = format!("{}.md", sanitize_name(&candidate.name));
    let path = learned_dir.join(&filename);
    let tmp_path = learned_dir.join(format!("{filename}.tmp"));

    // Write to temporary file first, then atomically rename into place.
    std::fs::write(&tmp_path, md_content).map_err(|e| {
        roboticus_core::RoboticusError::Config(format!("failed to write learned skill tmp: {e}"))
    })?;
    std::fs::rename(&tmp_path, &path).map_err(|e| {
        // Clean up tmp on rename failure
        let _ = std::fs::remove_file(&tmp_path);
        roboticus_core::RoboticusError::Config(format!("failed to rename learned skill: {e}"))
    })?;
    Ok(path)
}

// ── Orchestrator ───────────────────────────────────────────────

/// Main entry point: called by the governor when a session closes.
///
/// Mirrors the pattern of `digest_on_close()` — guard on config, extract data,
/// synthesise artifacts, persist, log.
pub fn learn_on_close(
    db: &Database,
    config: &LearningConfig,
    session: &Session,
    skills_dir: &Path,
) {
    if !config.enabled {
        debug!(session_id = %session.id, "learning disabled");
        return;
    }

    // Cap enforcement — track remaining capacity to avoid TOCTOU race where
    // the loop could exceed max_learned_skills by inserting multiple candidates.
    let remaining_capacity = match roboticus_db::learned_skills::count_learned_skills(db) {
        Ok(count) if count >= config.max_learned_skills => {
            debug!(
                count,
                max = config.max_learned_skills,
                "learned skills cap reached, skipping"
            );
            return;
        }
        Ok(count) => config.max_learned_skills - count,
        Err(e) => {
            warn!(error = %e, "failed to count learned skills");
            return;
        }
    };
    let mut new_skills_inserted = 0usize;

    // Load tool calls for this session
    let tool_calls = match roboticus_db::tools::get_tool_calls_for_session(db, &session.id) {
        Ok(tc) => tc,
        Err(e) => {
            warn!(error = %e, session_id = %session.id, "failed to load tool calls for learning");
            return;
        }
    };

    if tool_calls.is_empty() {
        debug!(session_id = %session.id, "no tool calls to learn from");
        return;
    }

    // Detect candidate procedures
    let candidates = detect_candidate_procedures(
        &tool_calls,
        config.min_tool_sequence,
        config.min_success_ratio,
    );

    if candidates.is_empty() {
        debug!(session_id = %session.id, "no candidate procedures detected");
        return;
    }

    for candidate in &candidates {
        // Check if already known
        match roboticus_db::learned_skills::get_learned_skill_by_name(db, &candidate.name) {
            Ok(Some(existing)) => {
                // Reinforce existing skill (doesn't count against cap)
                if let Err(e) =
                    roboticus_db::learned_skills::record_learned_skill_success(db, &candidate.name)
                {
                    warn!(error = %e, name = %candidate.name, "failed to reinforce learned skill");
                }

                // Self-heal: if a prior run stored the DB row but the .md write
                // or path-set failed, the record has skill_md_path = NULL.
                // Re-synthesize the .md so the skill is fully usable.
                if existing.skill_md_path.is_none() {
                    let md = synthesize_skill_md(candidate);
                    match write_learned_skill(skills_dir, candidate, &md) {
                        Ok(path) => {
                            let path_str = path.to_string_lossy().to_string();
                            if let Err(e) = roboticus_db::learned_skills::set_learned_skill_md_path(
                                db,
                                &candidate.name,
                                &path_str,
                            ) {
                                warn!(error = %e, name = %candidate.name, "failed to set healed skill md path");
                            } else {
                                info!(name = %candidate.name, path = %path_str, "healed learned skill .md");
                            }
                        }
                        Err(e) => {
                            warn!(error = %e, name = %candidate.name, "failed to heal skill .md write");
                        }
                    }
                }

                debug!(name = %candidate.name, "reinforced existing learned skill");
            }
            Ok(None) => {
                // Guard: check remaining capacity before inserting new skill
                if new_skills_inserted >= remaining_capacity {
                    debug!(
                        inserted = new_skills_inserted,
                        remaining = remaining_capacity,
                        "learned skills cap reached during loop, stopping"
                    );
                    break;
                }

                // New skill: store in DB + write .md file
                let trigger_tools_json =
                    serde_json::to_string(&candidate.tool_sequence).unwrap_or_else(|_| "[]".into());
                let steps_json = serde_json::to_string(&steps_to_serializable(&candidate.steps))
                    .unwrap_or_else(|_| "[]".into());

                if let Err(e) = roboticus_db::learned_skills::store_learned_skill(
                    db,
                    &candidate.name,
                    &candidate.description,
                    &trigger_tools_json,
                    &steps_json,
                    Some(&session.id),
                ) {
                    warn!(error = %e, name = %candidate.name, "failed to store learned skill");
                    continue;
                }
                new_skills_inserted += 1;

                // Synthesise and write .md (atomic: write to .tmp then rename)
                let md = synthesize_skill_md(candidate);
                match write_learned_skill(skills_dir, candidate, &md) {
                    Ok(path) => {
                        let path_str = path.to_string_lossy().to_string();
                        if let Err(e) = roboticus_db::learned_skills::set_learned_skill_md_path(
                            db,
                            &candidate.name,
                            &path_str,
                        ) {
                            warn!(error = %e, "failed to record skill md path");
                        }
                        info!(
                            name = %candidate.name,
                            path = %path_str,
                            steps = candidate.steps.len(),
                            "learned new skill"
                        );
                    }
                    Err(e) => {
                        warn!(error = %e, name = %candidate.name, "failed to write skill .md");
                    }
                }
            }
            Err(e) => {
                warn!(error = %e, "failed to check existing learned skill");
            }
        }
    }
}

// ── Helpers ────────────────────────────────────────────────────

fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        // Use floor_char_boundary to avoid panicking on multi-byte UTF-8.
        let boundary = s.floor_char_boundary(max_len);
        format!("{}", &s[..boundary])
    }
}

fn sanitize_name(name: &str) -> String {
    let raw: String = name
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect::<String>()
        .to_lowercase();

    // Collapse runs of hyphens, trim leading/trailing hyphens, and provide
    // a fallback so we never produce an empty or hidden filename.
    let collapsed: String = raw
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");

    if collapsed.is_empty() {
        "unknown-skill".to_string()
    } else {
        collapsed
    }
}

fn distinct_tools_display(seq: &[String]) -> String {
    let mut seen = std::collections::HashSet::new();
    let unique: Vec<&str> = seq
        .iter()
        .filter(|t| seen.insert(t.as_str()))
        .map(|t| t.as_str())
        .collect();
    unique.join("")
}

/// Convert steps to a JSON-serializable form.
fn steps_to_serializable(steps: &[ProcedureStep]) -> Vec<HashMap<String, String>> {
    steps
        .iter()
        .map(|s| {
            let mut m = HashMap::new();
            m.insert("tool".into(), s.tool_name.clone());
            m.insert("input".into(), s.input_summary.clone());
            m.insert("status".into(), s.status.clone());
            if let Some(ref out) = s.output_summary {
                m.insert("output".into(), out.clone());
            }
            m
        })
        .collect()
}

// ── Tests ──────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn make_call(name: &str, status: &str, time: &str) -> ToolCallRecord {
        ToolCallRecord {
            id: uuid::Uuid::new_v4().to_string(),
            turn_id: "t1".into(),
            tool_name: name.into(),
            input: format!(r#"{{"action":"{name}"}}"#),
            output: Some(format!("{name} output")),
            skill_id: None,
            skill_name: None,
            skill_hash: None,
            status: status.into(),
            duration_ms: Some(50),
            created_at: time.into(),
        }
    }

    fn sample_calls() -> HashMap<String, Vec<ToolCallRecord>> {
        let mut map = HashMap::new();
        map.insert(
            "t1".into(),
            vec![
                make_call("read", "success", "2025-01-01T00:00:01Z"),
                make_call("edit", "success", "2025-01-01T00:00:02Z"),
                make_call("bash", "success", "2025-01-01T00:00:03Z"),
            ],
        );
        map
    }

    #[test]
    fn detect_three_step_procedure() {
        let calls = sample_calls();
        let candidates = detect_candidate_procedures(&calls, 3, 0.7);
        assert!(!candidates.is_empty());
        let c = &candidates[0];
        assert_eq!(c.tool_sequence, vec!["read", "edit", "bash"]);
        assert!((c.success_ratio - 1.0).abs() < f64::EPSILON);
        assert_eq!(c.steps.len(), 3);
    }

    #[test]
    fn no_detection_below_min_length() {
        let mut map = HashMap::new();
        map.insert(
            "t1".into(),
            vec![
                make_call("read", "success", "2025-01-01T00:00:01Z"),
                make_call("edit", "success", "2025-01-01T00:00:02Z"),
            ],
        );
        let candidates = detect_candidate_procedures(&map, 3, 0.7);
        assert!(candidates.is_empty());
    }

    #[test]
    fn no_detection_below_success_ratio() {
        let mut map = HashMap::new();
        map.insert(
            "t1".into(),
            vec![
                make_call("read", "error", "2025-01-01T00:00:01Z"),
                make_call("edit", "error", "2025-01-01T00:00:02Z"),
                make_call("bash", "success", "2025-01-01T00:00:03Z"),
            ],
        );
        // ratio = 1/3 = 0.33 < 0.7
        let candidates = detect_candidate_procedures(&map, 3, 0.7);
        assert!(candidates.is_empty());
    }

    #[test]
    fn skip_identical_tools() {
        let mut map = HashMap::new();
        map.insert(
            "t1".into(),
            vec![
                make_call("bash", "success", "2025-01-01T00:00:01Z"),
                make_call("bash", "success", "2025-01-01T00:00:02Z"),
                make_call("bash", "success", "2025-01-01T00:00:03Z"),
            ],
        );
        let candidates = detect_candidate_procedures(&map, 3, 0.7);
        assert!(
            candidates.is_empty(),
            "all-same-tool sequences should be skipped"
        );
    }

    #[test]
    fn synthesize_skill_md_format() {
        let candidate = CandidateProcedure {
            name: "read-edit-bash".into(),
            description: "3-step procedure using read → edit → bash".into(),
            tool_sequence: vec!["read".into(), "edit".into(), "bash".into()],
            success_ratio: 1.0,
            steps: vec![
                ProcedureStep {
                    tool_name: "read".into(),
                    input_summary: "file.rs".into(),
                    output_summary: Some("contents".into()),
                    status: "success".into(),
                },
                ProcedureStep {
                    tool_name: "edit".into(),
                    input_summary: "change line 5".into(),
                    output_summary: None,
                    status: "success".into(),
                },
                ProcedureStep {
                    tool_name: "bash".into(),
                    input_summary: "cargo test".into(),
                    output_summary: Some("ok".into()),
                    status: "success".into(),
                },
            ],
        };
        let md = synthesize_skill_md(&candidate);
        // YAML frontmatter delimiters
        assert!(md.contains("---"), "expected YAML frontmatter delimiter");
        assert!(md.contains("name: read-edit-bash"));
        assert!(
            md.contains("triggers:") && md.contains("  - \"read\""),
            "expected YAML triggers list"
        );
        assert!(md.contains("## Steps"));
        assert!(md.contains("1. **read**"));
        assert!(md.contains("2. **edit**"));
        assert!(md.contains("3. **bash**"));
        assert!(md.contains("## When to Use"));
    }

    #[test]
    fn write_learned_skill_creates_file() {
        let dir = tempfile::tempdir().unwrap();
        let candidate = CandidateProcedure {
            name: "test-skill".into(),
            description: "test".into(),
            tool_sequence: vec!["a".into(), "b".into()],
            success_ratio: 1.0,
            steps: vec![],
        };
        let md = "# Test\n";
        let path = write_learned_skill(dir.path(), &candidate, md).unwrap();
        assert!(path.exists());
        assert!(path.starts_with(dir.path().join("learned")));
        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, md);
    }

    #[test]
    fn sanitize_name_handles_special_chars() {
        assert_eq!(sanitize_name("read/edit.bash"), "read-edit-bash");
        assert_eq!(sanitize_name("Read-EDIT_Bash"), "read-edit_bash");
    }

    #[test]
    fn learn_on_close_disabled_is_noop() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let sid = roboticus_db::sessions::find_or_create(&db, "learn-agent", None).unwrap();
        let session = roboticus_db::sessions::get_session(&db, &sid)
            .unwrap()
            .unwrap();
        let dir = tempfile::tempdir().unwrap();

        let config = LearningConfig {
            enabled: false,
            ..LearningConfig::default()
        };
        learn_on_close(&db, &config, &session, dir.path());

        assert_eq!(
            roboticus_db::learned_skills::count_learned_skills(&db).unwrap(),
            0
        );
    }

    #[test]
    fn learn_on_close_with_tool_calls_creates_skill() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let sid = roboticus_db::sessions::find_or_create(&db, "learn-agent", None).unwrap();
        let session = roboticus_db::sessions::get_session(&db, &sid)
            .unwrap()
            .unwrap();

        // Create a turn and tool calls
        {
            let conn = db.conn();
            conn.execute(
                "INSERT INTO turns (id, session_id) VALUES ('lt1', ?1)",
                [&sid],
            )
            .unwrap();
        }
        roboticus_db::tools::record_tool_call(
            &db,
            "lt1",
            "read",
            r#"{"file":"a.rs"}"#,
            Some("contents"),
            "success",
            Some(10),
        )
        .unwrap();
        roboticus_db::tools::record_tool_call(
            &db,
            "lt1",
            "edit",
            r#"{"file":"a.rs"}"#,
            Some("ok"),
            "success",
            Some(20),
        )
        .unwrap();
        roboticus_db::tools::record_tool_call(
            &db,
            "lt1",
            "bash",
            r#"{"cmd":"cargo test"}"#,
            Some("passed"),
            "success",
            Some(30),
        )
        .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let config = LearningConfig::default();
        learn_on_close(&db, &config, &session, dir.path());

        // A learned skill should now exist
        let count = roboticus_db::learned_skills::count_learned_skills(&db).unwrap();
        assert!(count > 0, "should have learned at least one skill");

        // A .md file should have been written
        let learned_dir = dir.path().join("learned");
        assert!(learned_dir.exists());
        let files: Vec<_> = std::fs::read_dir(&learned_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert!(!files.is_empty(), "should have written at least one .md");
    }

    #[test]
    fn learn_on_close_respects_cap() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let sid = roboticus_db::sessions::find_or_create(&db, "cap-agent", None).unwrap();
        let session = roboticus_db::sessions::get_session(&db, &sid)
            .unwrap()
            .unwrap();

        // Pre-fill to max
        let config = LearningConfig {
            max_learned_skills: 2,
            ..LearningConfig::default()
        };
        roboticus_db::learned_skills::store_learned_skill(&db, "existing-a", "A", "[]", "[]", None)
            .unwrap();
        roboticus_db::learned_skills::store_learned_skill(&db, "existing-b", "B", "[]", "[]", None)
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        learn_on_close(&db, &config, &session, dir.path());

        // Should still be 2 — cap prevented new skills
        assert_eq!(
            roboticus_db::learned_skills::count_learned_skills(&db).unwrap(),
            2
        );
    }

    #[test]
    fn learn_on_close_heals_null_skill_md_path() {
        let db = roboticus_db::Database::new(":memory:").unwrap();
        let sid = roboticus_db::sessions::find_or_create(&db, "heal-agent", None).unwrap();
        let session = roboticus_db::sessions::get_session(&db, &sid)
            .unwrap()
            .unwrap();

        // Pre-create a learned skill with NULL skill_md_path (simulates prior
        // partial write where DB store succeeded but .md write failed).
        roboticus_db::learned_skills::store_learned_skill(
            &db,
            "read-edit-bash",
            "3-step procedure",
            r#"["read","edit","bash"]"#,
            "[]",
            None,
        )
        .unwrap();

        // Verify it starts with NULL path
        let before = roboticus_db::learned_skills::get_learned_skill_by_name(&db, "read-edit-bash")
            .unwrap()
            .unwrap();
        assert!(
            before.skill_md_path.is_none(),
            "precondition: path should be NULL"
        );

        // Create tool calls that will produce a candidate with the same name
        {
            let conn = db.conn();
            conn.execute(
                "INSERT INTO turns (id, session_id) VALUES ('ht1', ?1)",
                [&sid],
            )
            .unwrap();
        }
        roboticus_db::tools::record_tool_call(
            &db,
            "ht1",
            "read",
            r#"{"file":"a.rs"}"#,
            Some("contents"),
            "success",
            Some(10),
        )
        .unwrap();
        roboticus_db::tools::record_tool_call(
            &db,
            "ht1",
            "edit",
            r#"{"file":"a.rs"}"#,
            Some("ok"),
            "success",
            Some(20),
        )
        .unwrap();
        roboticus_db::tools::record_tool_call(
            &db,
            "ht1",
            "bash",
            r#"{"cmd":"cargo test"}"#,
            Some("passed"),
            "success",
            Some(30),
        )
        .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let config = LearningConfig::default();
        learn_on_close(&db, &config, &session, dir.path());

        // After heal: skill_md_path should now be populated
        let after = roboticus_db::learned_skills::get_learned_skill_by_name(&db, "read-edit-bash")
            .unwrap()
            .unwrap();
        assert!(
            after.skill_md_path.is_some(),
            "skill_md_path should be healed to a real path"
        );

        // The .md file should actually exist on disk
        let md_path = std::path::Path::new(after.skill_md_path.as_ref().unwrap());
        assert!(md_path.exists(), "healed .md file should exist on disk");

        // Success count should have been bumped (reinforced)
        assert!(
            after.success_count > before.success_count,
            "success_count should have been incremented"
        );
    }
}