pawan-core 0.4.9

Pawan (पवन) — Core library: agent, tools, config, healing
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! Skill distillation — convert pawan agent sessions into reusable SKILL.md files
//!
//! Uses thulpoff's GenerationEngine to extract patterns from completed agent sessions
//! and produce skill files that can be loaded back via thulp-skill-files.
//!
//! Flow: PawanSession → TeacherSession → GenerationEngine → GeneratedSkill → SKILL.md

use crate::agent::session::Session;
use crate::agent::{Message, Role, TokenUsage as PawanUsage};
use crate::config::{LlmProvider, PawanConfig};
use crate::{PawanError, Result};

use std::path::{Path, PathBuf};
use std::sync::Arc;

use thulpoff_core::{
    CompletionRequest, CompletionResponse, EvaluationResult, GeneratedSkill,
    LlmProvider as ThulpoffProvider, Message as ToffMessage, MessageRole, TeacherSession,
    TokenUsage as ToffUsage, ToolCall as ToffToolCall,
};
use thulpoff_engine::{EvaluationEngine, GenerationEngine, RefinementEngine};

// ---------------------------------------------------------------------------
// Type conversions: pawan → thulpoff
// ---------------------------------------------------------------------------

fn convert_role(role: &Role) -> MessageRole {
    match role {
        Role::System => MessageRole::System,
        Role::User => MessageRole::User,
        Role::Assistant => MessageRole::Assistant,
        Role::Tool => MessageRole::Tool,
    }
}

fn convert_message(msg: &Message) -> ToffMessage {
    let tool_calls = if msg.tool_calls.is_empty() {
        None
    } else {
        Some(
            msg.tool_calls
                .iter()
                .map(|tc| ToffToolCall {
                    id: tc.id.clone(),
                    name: tc.name.clone(),
                    arguments: tc.arguments.clone(),
                })
                .collect(),
        )
    };

    let tool_call_id = msg.tool_result.as_ref().map(|tr| tr.tool_call_id.clone());

    ToffMessage {
        role: convert_role(&msg.role),
        content: msg.content.clone(),
        tool_calls,
        tool_call_id,
    }
}

fn convert_usage(usage: &PawanUsage) -> ToffUsage {
    ToffUsage {
        input_tokens: usage.prompt_tokens as u32,
        output_tokens: usage.completion_tokens as u32,
    }
}

/// Convert a pawan Session into a thulpoff TeacherSession.
///
/// Extracts the first user message as the task description, collects all messages
/// and tool calls, and maps token usage.
pub fn session_to_teacher(session: &Session, usage: &PawanUsage) -> TeacherSession {
    // Find the first user message as task description
    let task_description = session
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .map(|m| m.content.clone())
        .unwrap_or_else(|| "Unknown task".to_string());

    // Collect all tool calls from assistant messages
    let tool_calls: Vec<ToffToolCall> = session
        .messages
        .iter()
        .flat_map(|m| {
            m.tool_calls.iter().map(|tc| ToffToolCall {
                id: tc.id.clone(),
                name: tc.name.clone(),
                arguments: tc.arguments.clone(),
            })
        })
        .collect();

    TeacherSession {
        task_description,
        messages: session.messages.iter().map(convert_message).collect(),
        tool_calls,
        model: session.model.clone(),
        usage: convert_usage(usage),
    }
}

// ---------------------------------------------------------------------------
// Provider adapter: reuse pawan's NVIDIA/OpenAI config for thulpoff
// ---------------------------------------------------------------------------

/// Adapter that wraps pawan's HTTP config to implement thulpoff's LlmProvider trait.
struct PawanProviderAdapter {
    client: reqwest::Client,
    api_key: String,
    base_url: String,
}

impl PawanProviderAdapter {
    fn from_config(config: &PawanConfig) -> Result<Self> {
        let (base_url, api_key) = match config.provider {
            LlmProvider::Nvidia => {
                let url = config
                    .base_url
                    .clone()
                    .or_else(|| std::env::var("NVIDIA_API_URL").ok())
                    .unwrap_or_else(|| crate::DEFAULT_NVIDIA_API_URL.to_string());
                let key = std::env::var("NVIDIA_API_KEY").ok();
                (url, key)
            }
            LlmProvider::Ollama => {
                let url = config
                    .base_url
                    .clone()
                    .unwrap_or_else(|| "http://localhost:11434/v1".to_string());
                (url, None)
            }
            LlmProvider::OpenAI => {
                let url = config
                    .base_url
                    .clone()
                    .or_else(|| std::env::var("OPENAI_API_URL").ok())
                    .unwrap_or_else(|| "https://api.openai.com/v1".to_string());
                let key = std::env::var("OPENAI_API_KEY").ok();
                (url, key)
            }
            LlmProvider::Mlx => {
                let url = config
                    .base_url
                    .clone()
                    .unwrap_or_else(|| "http://localhost:8080/v1".to_string());
                (url, None)
            }
        };

        let api_key = api_key.unwrap_or_default();
        if api_key.is_empty() && config.provider == LlmProvider::Nvidia {
            return Err(PawanError::Config(
                "NVIDIA_API_KEY not set — needed for skill distillation".into(),
            ));
        }

        Ok(Self {
            client: reqwest::Client::new(),
            api_key,
            base_url,
        })
    }
}

#[async_trait::async_trait]
impl ThulpoffProvider for PawanProviderAdapter {
    async fn complete(
        &self,
        request: CompletionRequest,
    ) -> thulpoff_core::Result<CompletionResponse> {
        let url = format!("{}/chat/completions", self.base_url);

        let messages: Vec<serde_json::Value> = request
            .messages
            .iter()
            .map(|m| {
                serde_json::json!({
                    "role": m.role,
                    "content": m.content,
                })
            })
            .collect();

        let mut body = serde_json::json!({
            "model": request.model,
            "messages": messages,
        });

        if let Some(max_tokens) = request.max_tokens {
            body["max_tokens"] = serde_json::json!(max_tokens);
        }
        if let Some(temperature) = request.temperature {
            body["temperature"] = serde_json::json!(temperature);
        }

        let resp = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| thulpoff_core::ThulpoffError::Provider(e.to_string()))?;

        let status = resp.status();
        let text = resp
            .text()
            .await
            .map_err(|e| thulpoff_core::ThulpoffError::Provider(e.to_string()))?;

        if !status.is_success() {
            return Err(thulpoff_core::ThulpoffError::Provider(format!(
                "API error {}: {}",
                status, text
            )));
        }

        let json: serde_json::Value = serde_json::from_str(&text)?;

        let content = json["choices"][0]["message"]["content"]
            .as_str()
            .unwrap_or("")
            .to_string();

        let usage = ToffUsage {
            input_tokens: json["usage"]["prompt_tokens"].as_u64().unwrap_or(0) as u32,
            output_tokens: json["usage"]["completion_tokens"].as_u64().unwrap_or(0) as u32,
        };

        let finish_reason = json["choices"][0]["finish_reason"]
            .as_str()
            .unwrap_or("stop");
        let fr = match finish_reason {
            "tool_calls" => thulpoff_core::FinishReason::ToolUse,
            "length" => thulpoff_core::FinishReason::MaxTokens,
            _ => thulpoff_core::FinishReason::Stop,
        };

        Ok(CompletionResponse {
            content,
            tool_calls: vec![],
            usage,
            finish_reason: fr,
        })
    }

    fn name(&self) -> &str {
        "pawan-adapter"
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Distill a pawan session into a GeneratedSkill using the configured LLM.
///
/// This calls thulpoff's GenerationEngine to analyze the session trace and
/// extract a reusable skill definition.
pub async fn distill_session(
    session: &Session,
    usage: &PawanUsage,
    config: &PawanConfig,
) -> Result<GeneratedSkill> {
    let teacher = session_to_teacher(session, usage);

    let adapter = PawanProviderAdapter::from_config(config)?;
    let engine = GenerationEngine::new(Arc::new(adapter));

    engine
        .generate(&teacher)
        .await
        .map_err(|e| PawanError::Agent(format!("Skill distillation failed: {}", e)))
}

/// Distill and save a session as a SKILL.md file.
///
/// Returns the path where the skill was written.
pub async fn distill_and_save(
    session: &Session,
    usage: &PawanUsage,
    config: &PawanConfig,
    output_dir: &Path,
) -> Result<PathBuf> {
    let skill = distill_session(session, usage, config).await?;
    save_skill(&skill, output_dir)
}

/// Evaluate a distilled skill against a student model using thulpoff's
/// EvaluationEngine. Runs each test case through the student model with
/// the skill in context and scores how well the skill's pass_criteria
/// are met.
///
/// Returns an `EvaluationResult` with per-test scores and an `overall_score`
/// between 0.0 and 1.0. A perfect score means every pass_criterion was met
/// in every test case.
pub async fn evaluate_skill(
    skill: &GeneratedSkill,
    student_model: &str,
    config: &PawanConfig,
) -> Result<EvaluationResult> {
    let adapter = PawanProviderAdapter::from_config(config)?;
    let engine = EvaluationEngine::new(Arc::new(adapter));

    engine
        .evaluate(skill, student_model)
        .await
        .map_err(|e| PawanError::Agent(format!("Skill evaluation failed: {}", e)))
}

/// Refine a skill based on its evaluation results using thulpoff's
/// RefinementEngine. If the skill scored less than 1.0, the refinement
/// engine calls the teacher model with the skill + failing test details
/// and generates an improved version of the skill content.
///
/// The refined skill keeps the original name, frontmatter, and test_cases
/// — only description and content are updated based on failure analysis.
pub async fn refine_skill(
    skill: &GeneratedSkill,
    eval_result: &EvaluationResult,
    config: &PawanConfig,
) -> Result<GeneratedSkill> {
    let adapter = PawanProviderAdapter::from_config(config)?;
    let engine = RefinementEngine::new(Arc::new(adapter));

    engine
        .refine(skill, eval_result, &config.model)
        .await
        .map_err(|e| PawanError::Agent(format!("Skill refinement failed: {}", e)))
}

/// Full distill → evaluate → refine → save loop.
///
/// 1. Distills the session into a skill
/// 2. Evaluates against the student model (or primary model if None)
/// 3. If score < 1.0, refines once using the teacher model
/// 4. Saves the final skill to disk
///
/// Returns a tuple of `(saved_path, initial_score, final_score)`.
pub async fn distill_eval_refine_save(
    session: &Session,
    usage: &PawanUsage,
    config: &PawanConfig,
    output_dir: &Path,
    student_model: Option<&str>,
) -> Result<(PathBuf, f64, f64)> {
    let skill = distill_session(session, usage, config).await?;
    let student = student_model.unwrap_or(&config.model);

    let eval = evaluate_skill(&skill, student, config).await?;
    let initial_score = eval.overall_score;

    let final_skill = if initial_score < 1.0 {
        refine_skill(&skill, &eval, config).await?
    } else {
        skill
    };

    // Re-evaluate the refined skill to get the final score
    let final_score = if initial_score < 1.0 {
        let eval2 = evaluate_skill(&final_skill, student, config).await?;
        eval2.overall_score
    } else {
        initial_score
    };

    let path = save_skill(&final_skill, output_dir)?;
    Ok((path, initial_score, final_score))
}

/// Save a GeneratedSkill as a SKILL.md file in a named subdirectory.
pub fn save_skill(skill: &GeneratedSkill, output_dir: &Path) -> Result<PathBuf> {
    let skill_dir = output_dir.join(&skill.name);
    std::fs::create_dir_all(&skill_dir)
        .map_err(PawanError::Io)?;

    let content = format_skill_md(skill);
    let path = skill_dir.join("SKILL.md");
    std::fs::write(&path, content)?;

    Ok(path)
}

/// Format a GeneratedSkill into the SKILL.md format that thulp-skill-files can parse.
fn format_skill_md(skill: &GeneratedSkill) -> String {
    let frontmatter = if skill.frontmatter.is_null() {
        serde_json::json!({
            "name": skill.name,
            "description": skill.description,
        })
    } else {
        skill.frontmatter.clone()
    };

    let frontmatter_yaml = format!(
        "name: {}\ndescription: {}",
        skill.name, skill.description
    );

    let mut md = String::new();
    md.push_str("---\n");
    md.push_str(&frontmatter_yaml);

    // Add any extra frontmatter fields from the generation
    if let Some(obj) = frontmatter.as_object() {
        for (key, val) in obj {
            if key != "name" && key != "description" {
                md.push_str(&format!("\n{}: {}", key, val));
            }
        }
    }

    md.push_str("\n---\n\n");
    md.push_str(&skill.content);

    if !skill.test_cases.is_empty() {
        md.push_str("\n\n## Test Cases\n\n```json\n");
        if let Ok(json) = serde_json::to_string_pretty(&skill.test_cases) {
            md.push_str(&json);
        }
        md.push_str("\n```\n");
    }

    md
}

/// Get the default skills output directory (~/.pawan/skills/).
pub fn skills_dir() -> Result<PathBuf> {
    let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
    let dir = PathBuf::from(home).join(".pawan").join("skills");
    if !dir.exists() {
        std::fs::create_dir_all(&dir)?;
    }
    Ok(dir)
}

/// Check if a session is worth distilling (has enough substance).
///
/// A session needs at least 1 user message and 1 tool call to be useful.
pub fn is_distillable(session: &Session) -> bool {
    let has_user_msg = session.messages.iter().any(|m| m.role == Role::User);
    let has_tool_calls = session
        .messages
        .iter()
        .any(|m| !m.tool_calls.is_empty());
    let min_messages = session.messages.len() >= 4; // system + user + assistant + tool result

    has_user_msg && has_tool_calls && min_messages
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::{ToolCallRequest, ToolResultMessage};

    fn make_test_session() -> Session {
        Session {
            notes: String::new(),
            id: "test-123".to_string(),
            model: "test-model".to_string(),
            created_at: "2025-01-01T00:00:00Z".to_string(),
            updated_at: "2025-01-01T00:01:00Z".to_string(),
            messages: vec![
                Message {
                    role: Role::System,
                    content: "You are a coding agent.".to_string(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::User,
                    content: "Fix the bug in main.rs".to_string(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "I'll read the file first.".to_string(),
                    tool_calls: vec![ToolCallRequest {
                        id: "tc-1".to_string(),
                        name: "read_file".to_string(),
                        arguments: serde_json::json!({"path": "main.rs"}),
                    }],
                    tool_result: None,
                },
                Message {
                    role: Role::Tool,
                    content: "fn main() { panic!() }".to_string(),
                    tool_calls: vec![],
                    tool_result: Some(ToolResultMessage {
                        tool_call_id: "tc-1".to_string(),
                        content: serde_json::json!("fn main() { panic!() }"),
                        success: true,
                    }),
                },
                Message {
                    role: Role::Assistant,
                    content: "Found the issue. Fixing...".to_string(),
                    tool_calls: vec![ToolCallRequest {
                        id: "tc-2".to_string(),
                        name: "write_file".to_string(),
                        arguments: serde_json::json!({"path": "main.rs", "content": "fn main() { println!(\"hello\"); }"}),
                    }],
                    tool_result: None,
                },
                Message {
                    role: Role::Tool,
                    content: "File written.".to_string(),
                    tool_calls: vec![],
                    tool_result: Some(ToolResultMessage {
                        tool_call_id: "tc-2".to_string(),
                        content: serde_json::json!("File written successfully"),
                        success: true,
                    }),
                },
            ],
        total_tokens: 1500,
        iteration_count: 2,
        tags: Vec::new(),
        }
    }

    fn make_usage() -> PawanUsage {
        PawanUsage {
            prompt_tokens: 1000,
            completion_tokens: 500,
            total_tokens: 1500,
            reasoning_tokens: 100,
            action_tokens: 400,
        }
    }

    #[test]
    fn test_convert_role() {
        assert_eq!(convert_role(&Role::System), MessageRole::System);
        assert_eq!(convert_role(&Role::User), MessageRole::User);
        assert_eq!(convert_role(&Role::Assistant), MessageRole::Assistant);
        assert_eq!(convert_role(&Role::Tool), MessageRole::Tool);
    }

    #[test]
    fn test_convert_message_simple() {
        let msg = Message {
            role: Role::User,
            content: "hello".to_string(),
            tool_calls: vec![],
            tool_result: None,
        };
        let converted = convert_message(&msg);
        assert_eq!(converted.role, MessageRole::User);
        assert_eq!(converted.content, "hello");
        assert!(converted.tool_calls.is_none());
        assert!(converted.tool_call_id.is_none());
    }

    #[test]
    fn test_convert_message_with_tool_calls() {
        let msg = Message {
            role: Role::Assistant,
            content: "Reading file".to_string(),
            tool_calls: vec![ToolCallRequest {
                id: "tc-1".to_string(),
                name: "read_file".to_string(),
                arguments: serde_json::json!({"path": "foo.rs"}),
            }],
            tool_result: None,
        };
        let converted = convert_message(&msg);
        let calls = converted.tool_calls.unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "read_file");
        assert_eq!(calls[0].id, "tc-1");
    }

    #[test]
    fn test_convert_message_tool_result() {
        let msg = Message {
            role: Role::Tool,
            content: "result".to_string(),
            tool_calls: vec![],
            tool_result: Some(ToolResultMessage {
                tool_call_id: "tc-1".to_string(),
                content: serde_json::json!("ok"),
                success: true,
            }),
        };
        let converted = convert_message(&msg);
        assert_eq!(converted.tool_call_id, Some("tc-1".to_string()));
    }

    #[test]
    fn test_convert_usage() {
        let usage = make_usage();
        let converted = convert_usage(&usage);
        assert_eq!(converted.input_tokens, 1000);
        assert_eq!(converted.output_tokens, 500);
    }

    #[test]
    fn test_session_to_teacher() {
        let session = make_test_session();
        let usage = make_usage();
        let teacher = session_to_teacher(&session, &usage);

        assert_eq!(teacher.task_description, "Fix the bug in main.rs");
        assert_eq!(teacher.model, "test-model");
        assert_eq!(teacher.messages.len(), 6);
        assert_eq!(teacher.tool_calls.len(), 2);
        assert_eq!(teacher.tool_calls[0].name, "read_file");
        assert_eq!(teacher.tool_calls[1].name, "write_file");
        assert_eq!(teacher.usage.input_tokens, 1000);
    }

    #[test]
    fn test_is_distillable() {
        let session = make_test_session();
        assert!(is_distillable(&session));
    }

    #[test]
    fn test_not_distillable_no_tools() {
        let session = Session {
            notes: String::new(),
            id: "empty".to_string(),
            model: "m".to_string(),
            created_at: "now".to_string(),
            updated_at: "now".to_string(),
            messages: vec![
                Message {
                    role: Role::User,
                    content: "hi".to_string(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "hello".to_string(),
                    tool_calls: vec![],
                    tool_result: None,
                },
            ],
        total_tokens: 100,
        iteration_count: 1,
        tags: Vec::new(),
    };
        assert!(!is_distillable(&session));
    }

    #[test]
    fn test_format_skill_md() {
        let skill = GeneratedSkill {
            name: "fix-bug".to_string(),
            description: "Fix common bugs in Rust code".to_string(),
            frontmatter: serde_json::json!({"name": "fix-bug", "description": "Fix common bugs"}),
            content: "## Steps\n\n1. Read the file\n2. Identify the bug\n3. Fix it".to_string(),
            test_cases: vec![thulpoff_core::TestCase {
                name: "basic-fix".to_string(),
                input: serde_json::json!({"file": "main.rs"}),
                expected_behavior: "Bug is fixed".to_string(),
                pass_criteria: vec!["compiles".to_string(), "no panic".to_string()],
            }],
            source_session: Some("test-123".to_string()),
        };

        let md = format_skill_md(&skill);
        assert!(md.starts_with("---\n"));
        assert!(md.contains("name: fix-bug"));
        assert!(md.contains("## Steps"));
        assert!(md.contains("## Test Cases"));
        assert!(md.contains("basic-fix"));
    }

    #[test]
    fn test_save_skill_creates_dir() {
        let skill = GeneratedSkill {
            name: "test-skill".to_string(),
            description: "A test".to_string(),
            frontmatter: serde_json::json!({}),
            content: "Do the thing.".to_string(),
            test_cases: vec![],
            source_session: None,
        };

        let dir = tempfile::tempdir().unwrap();
        let path = save_skill(&skill, dir.path()).unwrap();

        assert!(path.exists());
        assert_eq!(path.file_name().unwrap(), "SKILL.md");
        assert!(path.parent().unwrap().ends_with("test-skill"));

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("name: test-skill"));
        assert!(content.contains("Do the thing."));
    }

    #[test]
    fn test_skills_dir_creates_directory() {
        let dir = skills_dir().unwrap();
        assert!(dir.exists());
        assert!(dir.ends_with("skills"));
    }

    #[test]
    fn test_is_distillable_too_few_messages() {
        // Even with a tool call, a session with <4 messages is not worth
        // distilling — you can't learn a pattern from one round trip.
        let session = Session {
            notes: String::new(),
            id: "short".into(),
            model: "m".into(),
            created_at: "now".into(),
            updated_at: "now".into(),
            messages: vec![
                Message {
                    role: Role::User,
                    content: "do stuff".into(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "running tool".into(),
                    tool_calls: vec![ToolCallRequest {
                        id: "tc-1".into(),
                        name: "ls".into(),
                        arguments: serde_json::json!({}),
                    }],
                    tool_result: None,
                },
                Message {
                    role: Role::Tool,
                    content: "output".into(),
                    tool_calls: vec![],
                    tool_result: Some(ToolResultMessage {
                        tool_call_id: "tc-1".into(),
                        content: serde_json::json!("ok"),
                        success: true,
                    }),
                },
            ],
        total_tokens: 100,
        iteration_count: 1,
        tags: Vec::new(),
    };
        // Has user + tools but only 3 messages < min_messages (4)
        assert!(!is_distillable(&session), "sessions with <4 messages must not be distillable");
    }

    #[test]
    fn test_session_to_teacher_without_user_falls_back_to_unknown() {
        // A session that somehow has no user message (system-only prompt)
        // must still produce a TeacherSession — just with a placeholder task.
        let session = Session {
            notes: String::new(),
            id: "no-user".into(),
            model: "m".into(),
            created_at: "now".into(),
            updated_at: "now".into(),
            messages: vec![Message {
                role: Role::System,
                content: "you are a bot".into(),
                tool_calls: vec![],
                tool_result: None,
            }],
            total_tokens: 0,
            iteration_count: 0,
        tags: Vec::new(),
        };
        let teacher = session_to_teacher(&session, &make_usage());
        assert_eq!(teacher.task_description, "Unknown task");
        assert_eq!(teacher.messages.len(), 1);
        assert_eq!(teacher.tool_calls.len(), 0);
    }

    #[test]
    fn test_format_skill_md_without_test_cases_omits_test_section() {
        // When test_cases is empty, the "## Test Cases" section must be
        // omitted entirely — not left dangling with empty code fences.
        let skill = GeneratedSkill {
            name: "just-steps".into(),
            description: "No tests attached".into(),
            frontmatter: serde_json::json!({}),
            content: "## Do this\nThen do that".into(),
            test_cases: vec![],
            source_session: None,
        };
        let md = format_skill_md(&skill);
        assert!(md.contains("## Do this"), "content must be present");
        assert!(!md.contains("## Test Cases"), "no test cases ⇒ no test section");
        assert!(!md.contains("```json"), "no test cases ⇒ no json fence");
    }

    #[test]
    fn test_format_skill_md_preserves_extra_frontmatter_fields() {
        // Frontmatter fields beyond name/description must be emitted after
        // the standard two — regression test for the object iteration
        // branch in format_skill_md.
        let skill = GeneratedSkill {
            name: "skill-with-meta".into(),
            description: "Has extra metadata".into(),
            frontmatter: serde_json::json!({
                "name": "skill-with-meta",
                "description": "Has extra metadata",
                "version": "1.2.3",
                "tags": ["rust", "test"]
            }),
            content: "body".into(),
            test_cases: vec![],
            source_session: None,
        };
        let md = format_skill_md(&skill);
        assert!(md.contains("name: skill-with-meta"));
        assert!(md.contains("description: Has extra metadata"));
        assert!(md.contains("version:"), "extra 'version' field must be emitted");
        assert!(md.contains("tags:"), "extra 'tags' field must be emitted");
    }

    #[test]
    fn test_save_skill_on_existing_dir_overwrites() {
        // Calling save_skill twice with the same name must succeed —
        // create_dir_all + write overwrites, and we don't want the second
        // call to fail because the first already ran.
        let skill_v1 = GeneratedSkill {
            name: "iter-skill".into(),
            description: "v1 description".into(),
            frontmatter: serde_json::json!({}),
            content: "v1 body".into(),
            test_cases: vec![],
            source_session: None,
        };
        let skill_v2 = GeneratedSkill {
            name: "iter-skill".into(),
            description: "v2 description".into(),
            frontmatter: serde_json::json!({}),
            content: "v2 body".into(),
            test_cases: vec![],
            source_session: None,
        };

        let dir = tempfile::tempdir().unwrap();
        let p1 = save_skill(&skill_v1, dir.path()).unwrap();
        let p2 = save_skill(&skill_v2, dir.path()).unwrap();
        assert_eq!(p1, p2, "second save should write to the same path");

        let content = std::fs::read_to_string(&p2).unwrap();
        assert!(content.contains("v2 body"), "file should contain v2 content");
        assert!(!content.contains("v1 body"), "v1 content should be overwritten");
    }

    // ─── Edge cases for skill distillation helpers ──────────────────────

    #[test]
    fn test_is_distillable_empty_session() {
        // An empty session (0 messages) must fail all 3 checks: no user,
        // no tool calls, not enough messages
        let session = Session {
            notes: String::new(),
            id: "empty".into(),
            model: "m".into(),
            created_at: "t".into(),
            updated_at: "t".into(),
            messages: vec![],
            total_tokens: 0,
            iteration_count: 0,
        tags: Vec::new(),
        };
        assert!(
            !is_distillable(&session),
            "empty session must not be distillable"
        );
    }

    #[test]
    fn test_is_distillable_with_tool_calls_but_no_user_message() {
        // Regression: is_distillable must check ALL three conditions, not
        // just the tool_calls + message count. Missing user intent means
        // there's nothing meaningful to distill even if tools ran.
        let session = Session {
            notes: String::new(),
            id: "no-user".into(),
            model: "m".into(),
            created_at: "t".into(),
            updated_at: "t".into(),
            messages: vec![
                Message {
                    role: Role::System,
                    content: "sys".into(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "running".into(),
                    tool_calls: vec![ToolCallRequest {
                        id: "tc-1".into(),
                        name: "read_file".into(),
                        arguments: serde_json::json!({}),
                    }],
                    tool_result: None,
                },
                Message {
                    role: Role::Tool,
                    content: "result".into(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "done".into(),
                    tool_calls: vec![],
                    tool_result: None,
                },
            ],
            total_tokens: 0,
            iteration_count: 0,
        tags: Vec::new(),
        };
        assert!(
            !is_distillable(&session),
            "session without user message must not be distillable"
        );
    }

    #[test]
    fn test_session_to_teacher_collects_all_tool_calls_across_messages() {
        // Multiple assistant messages with tool calls — session_to_teacher
        // must flatten them all into a single Vec<ToffToolCall>.
        let session = Session {
            notes: String::new(),
            id: "multi".into(),
            model: "test-model".into(),
            created_at: "t".into(),
            updated_at: "t".into(),
            messages: vec![
                Message {
                    role: Role::User,
                    content: "do stuff".into(),
                    tool_calls: vec![],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "step 1".into(),
                    tool_calls: vec![ToolCallRequest {
                        id: "a".into(),
                        name: "read_file".into(),
                        arguments: serde_json::json!({}),
                    }],
                    tool_result: None,
                },
                Message {
                    role: Role::Assistant,
                    content: "step 2".into(),
                    tool_calls: vec![
                        ToolCallRequest {
                            id: "b".into(),
                            name: "write_file".into(),
                            arguments: serde_json::json!({}),
                        },
                        ToolCallRequest {
                            id: "c".into(),
                            name: "bash".into(),
                            arguments: serde_json::json!({}),
                        },
                    ],
                    tool_result: None,
                },
            ],
            total_tokens: 100,
            iteration_count: 2,
        tags: Vec::new(),
        };
        let usage = PawanUsage {
            prompt_tokens: 50,
            completion_tokens: 50,
            total_tokens: 100,
            reasoning_tokens: 0,
            action_tokens: 50,
        };
        let teacher = session_to_teacher(&session, &usage);
        assert_eq!(
            teacher.tool_calls.len(),
            3,
            "session_to_teacher must collect all 3 tool calls across 2 assistant messages"
        );
        let names: Vec<&str> = teacher.tool_calls.iter().map(|tc| tc.name.as_str()).collect();
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"write_file"));
        assert!(names.contains(&"bash"));
    }

    #[test]
    fn test_session_to_teacher_preserves_model_name() {
        // The teacher session must carry the source model forward so the
        // distiller can log which model produced the trajectory.
        let session = Session {
            notes: String::new(),
            id: "m".into(),
            model: "qwen3.5-122b-exotic-variant".into(),
            created_at: "t".into(),
            updated_at: "t".into(),
            messages: vec![Message {
                role: Role::User,
                content: "q".into(),
                tool_calls: vec![],
                tool_result: None,
            }],
            total_tokens: 0,
            iteration_count: 0,
        tags: Vec::new(),
        };
        let usage = PawanUsage::default();
        let teacher = session_to_teacher(&session, &usage);
        assert_eq!(teacher.model, "qwen3.5-122b-exotic-variant");
    }
}