collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
//! `collet evolve` โ€” run the self-improvement evolution loop.
//!
//! Usage:
//!   collet evolve [OPTIONS]
//!
//! Options:
//!   --workspace <path>         Agent workspace root  [default: .collet/workspace]
//!   --cycles <n>               Max evolution cycles  [default: 10]
//!   --engine <name>            Evolution engine      [default: skillforge]
//!   --batch <n>                Tasks per cycle       [default: 5]
//!   --benchmark <name>         Benchmark adapter     [null|file|swebench]  [default: null]
//!   --tasks <path>             Task JSONL file       (required for file/swebench)
//!   --eval-dir <path>          Scratch dir for evaluation  [default: .collet/eval]
//!   --docker                   Use Docker in SWE-bench harness
//!   --score-cmd <cmd>          External scorer for file benchmark
//!   --evolve-prompts           Mutate system prompt  [default: true]
//!   --evolve-skills            Mutate skills         [default: true]
//!   --no-evolve-memory         Disable memory mutation
//!   --no-evolve-tools          Disable tool mutation (default)
//!   --model <name>             Evolver model override
//!   --dir <path>               Working directory for the agent

use std::path::PathBuf;

use anyhow::Result;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::agent::r#loop::AgentEvent;
use crate::api::provider::OpenAiCompatibleProvider;
use crate::config::Config;
use crate::evolution::{
    EvolutionEvent,
    adapter::ColletEvolvable,
    benchmarks::{FileBenchmark, NullBenchmark, SingleTaskBenchmark, SweBenchAdapter},
    config::EvolveConfig,
    engines::SkillforgeEngine,
    r#loop::EvolutionLoop,
    trial::TrialRunner,
};

pub fn print_evolve_usage() {
    println!("Usage: collet evolve [TASK] [OPTIONS]");
    println!();
    println!("Run the self-improvement evolution loop on an agent workspace.");
    println!();
    println!("  TASK                     Natural-language task (agent solves it, then improves)");
    println!();
    println!("Examples:");
    println!("  collet evolve \"fix the login bug\"                  # solve + 1 improvement");
    println!("  collet evolve \"add input validation\" --cycles 5    # solve + 5 iterations");
    println!("  collet evolve --benchmark file --tasks t.jsonl     # batch benchmark loop");
    println!("  collet evolve --benchmark swebench --tasks s.jsonl # SWE-bench loop");
    println!();
    println!("Options:");
    println!("  --cycles <n>             Max evolution cycles  [default: 1 with TASK, 10 without]");
    println!("  --batch <n>              Tasks per cycle       [default: 5]");
    println!("  --benchmark <name>       Benchmark adapter     [null|file|swebench]");
    println!("  --tasks <path>           Task JSONL file       (required for file/swebench)");
    println!("  --eval-dir <path>        Scratch dir for evaluation  [default: .collet/eval]");
    println!("  --docker                 Use Docker in SWE-bench harness");
    println!("  --score-cmd <cmd>        External scorer command for file benchmark");
    println!("  --model <name>           Evolver model override");
    println!("  --workspace <path>       Agent workspace root  [default: .collet/workspace]");
    println!("  --dir <path>             Working directory for the agent");
    println!("  --no-evolve-prompts      Disable prompt mutation");
    println!("  --no-evolve-skills       Disable skill mutation");
    println!("  --no-evolve-memory       Disable memory mutation");
    println!("  --evolve-tools           Enable tool mutation");
    println!("  -h, --help               Show this help");
}

/// Parse evolve-specific arguments.
struct EvolveArgs {
    /// Free-text task description (positional args joined with spaces).
    task_text: Option<String>,
    workspace: Option<PathBuf>,
    cycles: Option<u32>,
    batch: usize,
    model: Option<String>,
    dir: Option<String>,
    no_evolve_prompts: bool,
    no_evolve_skills: bool,
    no_evolve_memory: bool,
    evolve_tools: bool,
    benchmark: Option<String>,
    tasks: Option<PathBuf>,
    eval_dir: Option<PathBuf>,
    docker: bool,
    score_cmd: Option<String>,
}

fn parse_evolve_args(args: &[String]) -> EvolveArgs {
    let mut workspace = None;
    let mut cycles: Option<u32> = None;
    let mut batch = 5usize;
    let mut model = None;
    let mut dir = None;
    let mut no_evolve_prompts = false;
    let mut no_evolve_skills = false;
    let mut no_evolve_memory = false;
    let mut evolve_tools = false;
    let mut benchmark: Option<String> = None;
    let mut tasks: Option<PathBuf> = None;
    let mut eval_dir: Option<PathBuf> = None;
    let mut docker = false;
    let mut score_cmd: Option<String> = None;
    let mut task_words: Vec<String> = Vec::new();

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--workspace" => {
                i += 1;
                workspace = args.get(i).map(PathBuf::from);
            }
            "--cycles" => {
                i += 1;
                cycles = args.get(i).and_then(|s| s.parse().ok());
            }
            "--batch" => {
                i += 1;
                batch = args.get(i).and_then(|s| s.parse().ok()).unwrap_or(5);
            }
            "--model" => {
                i += 1;
                model = args.get(i).cloned();
            }
            "--dir" => {
                i += 1;
                dir = args.get(i).cloned();
            }
            "--benchmark" => {
                i += 1;
                benchmark = args.get(i).cloned();
            }
            "--tasks" => {
                i += 1;
                tasks = args.get(i).map(PathBuf::from);
            }
            "--eval-dir" => {
                i += 1;
                eval_dir = args.get(i).map(PathBuf::from);
            }
            "--score-cmd" => {
                i += 1;
                score_cmd = args.get(i).cloned();
            }
            "--docker" => docker = true,
            "--no-evolve-prompts" => no_evolve_prompts = true,
            "--no-evolve-skills" => no_evolve_skills = true,
            "--no-evolve-memory" => no_evolve_memory = true,
            "--evolve-tools" => evolve_tools = true,
            other if other.starts_with("--") => {} // unknown flag โ€” ignore
            word => task_words.push(word.to_string()), // positional โ†’ task text
        }
        i += 1;
    }

    let task_text = if task_words.is_empty() {
        None
    } else {
        Some(task_words.join(" "))
    };

    EvolveArgs {
        task_text,
        workspace,
        cycles,
        batch,
        model,
        dir,
        no_evolve_prompts,
        no_evolve_skills,
        no_evolve_memory,
        evolve_tools,
        benchmark,
        tasks,
        eval_dir,
        docker,
        score_cmd,
    }
}

/// Run the `collet evolve` subcommand.
pub async fn cmd_evolve(args: &[String]) -> Result<()> {
    let ea = parse_evolve_args(args);

    // Load base config
    let mut config = Config::load().map_err(|e| anyhow::anyhow!("Config error: {e}"))?;

    // Override model if provided
    if let Some(ref m) = ea.model {
        config.model = m.clone();
    }

    // Resolve working directory
    let working_dir = match &ea.dir {
        Some(d) => d.clone(),
        None => std::env::current_dir()
            .unwrap_or_default()
            .display()
            .to_string(),
    };

    // Resolve workspace root
    let workspace_root = ea.workspace.clone().unwrap_or_else(|| {
        PathBuf::from(&working_dir)
            .join(".collet")
            .join("workspace")
    });

    // Build evolve config (max_cycles resolved later after benchmark is known)
    let evolve_config_base = EvolveConfig {
        batch_size: ea.batch,
        max_cycles: ea.cycles.unwrap_or(10), // placeholder, overridden below
        evolve_prompts: !ea.no_evolve_prompts,
        evolve_skills: !ea.no_evolve_skills,
        evolve_memory: !ea.no_evolve_memory,
        evolve_tools: ea.evolve_tools,
        evolver_model: config.model.clone(),
        ..Default::default()
    };

    // Ensure workspace exists
    tokio::fs::create_dir_all(&workspace_root).await?;

    // Build the API client
    let client = OpenAiCompatibleProvider::from_config(&config)
        .map_err(|e| anyhow::anyhow!("Provider error: {e}"))?;

    // Create the Collet evolvable adapter
    let evolvable = ColletEvolvable::new(
        client.clone(),
        config.clone(),
        workspace_root.clone(),
        working_dir.clone(),
    );

    // Create event channel (forwarded to console)
    let (event_tx, mut event_rx) = mpsc::unbounded_channel::<AgentEvent>();
    let cancel = CancellationToken::new();

    // Ctrl+C handler via tokio signal
    let cancel_clone = cancel.clone();
    tokio::spawn(async move {
        if tokio::signal::ctrl_c().await.is_ok() {
            eprintln!("\nโšก Evolution interrupted by user");
            cancel_clone.cancel();
        }
    });

    // Spawn event printer (console output for headless mode)
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            if let AgentEvent::Evolution(evo_event) = event {
                print_evolution_event(&evo_event);
            }
        }
    });

    // Resolve eval scratch dir
    let eval_dir = ea
        .eval_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from(&working_dir).join(".collet").join("eval"));

    // Determine benchmark and cycle count.
    // Priority: explicit --benchmark > task_text > null
    let (benchmark, benchmark_label, cycles_default): (
        Box<dyn crate::evolution::trial::BenchmarkAdapter>,
        String,
        u32,
    ) = if let Some(ref text) = ea.task_text {
        // Natural-language mode: inline single task, default 1 cycle
        (
            Box::new(SingleTaskBenchmark::from_text(text.clone())),
            format!("inline: \"{text}\""),
            1,
        )
    } else {
        match ea.benchmark.as_deref().unwrap_or("null") {
            "file" => {
                let path = ea.tasks.clone().ok_or_else(|| {
                    anyhow::anyhow!("--tasks <path> is required for --benchmark file")
                })?;
                let mut fb = FileBenchmark::new(path.clone());
                if let Some(cmd) = ea.score_cmd.clone() {
                    fb = fb.with_score_cmd(cmd);
                }
                (Box::new(fb), format!("file({})", path.display()), 10)
            }
            "swebench" | "swe-bench" => {
                let path = ea.tasks.clone().ok_or_else(|| {
                    anyhow::anyhow!("--tasks <path> is required for --benchmark swebench")
                })?;
                tokio::fs::create_dir_all(&eval_dir).await?;
                (
                    Box::new(
                        SweBenchAdapter::new(path.clone(), eval_dir.clone()).with_docker(ea.docker),
                    ),
                    format!("swebench({})", path.display()),
                    10,
                )
            }
            _ => (Box::new(NullBenchmark), "null".to_string(), 10),
        }
    };

    let max_cycles = ea.cycles.unwrap_or(cycles_default);

    println!("๐Ÿงฌ Starting evolution loop");
    println!("   Workspace:   {}", workspace_root.display());
    println!("   Working dir: {working_dir}");
    println!("   Cycles:      {max_cycles}");
    println!("   Engine:      skillforge");
    println!("   Benchmark:   {benchmark_label}");
    println!("   Model:       {}", evolve_config_base.evolver_model);
    println!();

    let trial = TrialRunner::new(Box::new(evolvable), benchmark);

    // Build evolution loop
    let evo_event_tx = wrap_evo_tx(event_tx);
    let evolve_config = EvolveConfig {
        max_cycles,
        ..evolve_config_base
    };

    let mut evo_loop =
        EvolutionLoop::new(workspace_root, trial, evolve_config.clone(), evo_event_tx)?;

    let mut engine = SkillforgeEngine::new(evolve_config, client);
    let result = evo_loop.run(&mut engine, cancel).await?;

    println!();
    println!("โœ… Evolution complete");
    println!("   Cycles: {}", result.cycles_completed);
    println!("   Final score: {:.3}", result.final_score);
    println!(
        "   Converged: {}",
        if result.converged { "yes" } else { "no" }
    );

    if !result.score_history.is_empty() {
        let curve: Vec<String> = result
            .score_history
            .iter()
            .enumerate()
            .map(|(i, s)| format!("{}: {:.3}", i + 1, s))
            .collect();
        println!("   Score curve: {}", curve.join(" โ†’ "));
    }

    Ok(())
}

/// Create a wrapped sender that converts `EvolutionEvent` โ†’ `AgentEvent::Evolution`.
fn wrap_evo_tx(
    agent_tx: mpsc::UnboundedSender<AgentEvent>,
) -> mpsc::UnboundedSender<EvolutionEvent> {
    let (evo_tx, mut evo_rx) = mpsc::unbounded_channel::<EvolutionEvent>();
    tokio::spawn(async move {
        while let Some(evt) = evo_rx.recv().await {
            let _ = agent_tx.send(AgentEvent::Evolution(evt));
        }
    });
    evo_tx
}

/// Print evolution events to console (used in headless mode).
fn print_evolution_event(event: &EvolutionEvent) {
    use crate::evolution::EvolutionEvent::*;
    match event {
        CycleStarted { cycle, max_cycles } => {
            println!("โ”€โ”€ Cycle {cycle}/{max_cycles} โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€");
        }
        SolveStarted { task_count } => {
            println!("  ๐Ÿ”ง Solving {task_count} tasks...");
        }
        SolveCompleted { score } => {
            println!("  ๐Ÿ“Š Batch score: {score:.3}");
        }
        EngineStepStarted { engine_name } => {
            println!("  ๐Ÿง  [{engine_name}] Analyzing observations...");
        }
        EngineStepCompleted { mutated, summary } => {
            if *mutated {
                println!("  โœ… Mutated: {summary}");
            } else {
                println!("  โญ  No mutation: {summary}");
            }
        }
        CycleCompleted {
            cycle,
            score,
            mutated,
        } => {
            let m = if *mutated { "โœŽ" } else { "ยท" };
            println!("  {m} Cycle {cycle} done โ€” score: {score:.3}");
        }
        Converged { cycle, final_score } => {
            println!();
            println!("๐ŸŽฏ Converged at cycle {cycle} โ€” final score: {final_score:.3}");
        }
        Error(msg) => {
            eprintln!("  โŒ Error: {msg}");
        }
        Done(_) => {}
    }
}