double-o 0.10.1

Context-efficient command runner for AI coding agents
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
use super::*;
use crate::learn_utils::{strip_fences as strip_fences_impl, truncate_utf8};

// Re-export the functions for testing
fn strip_fences(s: &str) -> String {
    strip_fences_impl(s)
}

// Tests for failure-section validation live in a separate file to keep this
// module under 500 lines.
#[cfg(test)]
#[path = "learn_validate_tests.rs"]
mod validate;

// ---------------------------------------------------------------------------
// strip_fences
// ---------------------------------------------------------------------------

#[test]
fn test_strip_fences_toml() {
    let input = "```toml\ncommand_match = \"test\"\n```";
    assert_eq!(strip_fences(input), "command_match = \"test\"");
}

#[test]
fn test_strip_fences_plain() {
    let input = "```\ncommand_match = \"test\"\n```";
    assert_eq!(strip_fences(input), "command_match = \"test\"");
}

#[test]
fn test_strip_fences_none() {
    let input = "command_match = \"test\"";
    assert_eq!(strip_fences(input), "command_match = \"test\"");
}

#[test]
fn test_strip_fences_whitespace_preserved() {
    let input = "```toml\n\ncommand_match = \"test\"\n\n```";
    let result = strip_fences(input);
    assert!(
        result.contains("command_match"),
        "content must be preserved"
    );
}

// ---------------------------------------------------------------------------
// validate_pattern_toml (now uses validate_pattern_regexes from toml module)
// ---------------------------------------------------------------------------

#[test]
fn test_validate_pattern_toml_regexes_valid() {
    let toml = r#"
command_match = "^mytest"
[success]
pattern = '(?P<n>\d+) passed'
summary = "{n} passed"
"#;
    assert!(validate_pattern_toml_with_limits(toml).is_ok());
}

#[test]
fn test_validate_pattern_toml_regexes_invalid_regex() {
    let toml = r#"
command_match = "[invalid"
"#;
    assert!(validate_pattern_toml_with_limits(toml).is_err());
}

#[test]
fn test_validate_pattern_toml_regexes_no_success() {
    let toml = r#"command_match = "^cargo""#;
    assert!(validate_pattern_toml_with_limits(toml).is_ok());
}

#[test]
fn test_validate_pattern_toml_regexes_invalid_toml_syntax() {
    let toml = "this is not valid = [toml";
    assert!(validate_pattern_toml_with_limits(toml).is_err());
}

#[test]
fn test_validate_pattern_toml_regexes_missing_command_match() {
    let toml = r#"
[success]
pattern = "ok"
summary = "done"
"#;
    assert!(validate_pattern_toml_with_limits(toml).is_err());
}

#[test]
fn test_validate_pattern_toml_regexes_invalid_command_match_regex() {
    let toml = r#"command_match = "[invalid_regex""#;
    assert!(validate_pattern_toml_with_limits(toml).is_err());
}

#[test]
fn test_validate_pattern_toml_regexes_invalid_success_pattern_regex() {
    let toml = r#"
command_match = "^cargo"
[success]
pattern = "[invalid"
summary = "done"
"#;
    assert!(validate_pattern_toml_with_limits(toml).is_err());
}

#[test]
fn test_validate_pattern_toml_regexes_with_valid_success_pattern() {
    let toml = "command_match = \"^pytest\"\n[success]\npattern = '(?P<n>\\d+) passed'\nsummary = \"{n} passed\"";
    assert!(validate_pattern_toml_with_limits(toml).is_ok());
}

#[test]
fn test_validate_pattern_toml_regexes_enforces_length_limit() {
    // MAX_REGEX_LENGTH is 500 chars
    let long_regex = format!(r#"command_match = "{}""#, "a".repeat(501));
    assert!(validate_pattern_toml_with_limits(&long_regex).is_err());
}

// ---------------------------------------------------------------------------
// truncate_for_prompt / truncate_utf8
// ---------------------------------------------------------------------------

#[test]
fn test_truncate_for_prompt() {
    let short = "hello";
    assert_eq!(truncate_for_prompt(short), "hello");

    let long = "x".repeat(5000);
    assert_eq!(truncate_for_prompt(&long).len(), 4000);
}

#[test]
fn test_truncate_for_prompt_boundary() {
    let exact = "a".repeat(4000);
    assert_eq!(truncate_for_prompt(&exact).len(), 4000);

    let over = "a".repeat(4001);
    assert_eq!(truncate_for_prompt(&over).len(), 4000);
}

#[test]
fn test_truncate_utf8_multibyte_boundary() {
    // Each '£' is 2 bytes (0xC2 0xA3). With max_bytes=5 we must not split a char.
    let s = "££££"; // 8 bytes total
    let result = truncate_utf8(s, 5);
    // 5 bytes would split '£' at byte 5; we must step back to byte 4 (2 chars).
    assert_eq!(result.len(), 4);
    assert!(result.is_ascii() || std::str::from_utf8(result.as_bytes()).is_ok());
    assert_eq!(result, "££");
}

#[test]
fn test_truncate_utf8_exact_boundary() {
    let s = "hello"; // 5 bytes
    assert_eq!(truncate_utf8(s, 5), "hello");
    assert_eq!(truncate_utf8(s, 10), "hello");
}

// ---------------------------------------------------------------------------
// label (first word sanitization)
// ---------------------------------------------------------------------------

#[test]
fn test_label_sanitizes_first_word_special_chars() {
    // First word should be sanitized the same way as second word
    // After rsplit('/'), we get the last component, then sanitize it
    assert_eq!(label("../bin/cargo test"), "cargo-test");
    assert_eq!(label("./binary/name test"), "name-test");
    assert_eq!(label("/path/.hidden/bin test"), "bin-test");
    assert_eq!(label("cmd-with-dashes test"), "cmd-with-dashes-test");
}

#[test]
fn test_label_first_word_length_limit() {
    // First word should be limited to MAX_FILENAME_COMPONENT (50 chars)
    let long_first = "a".repeat(100);
    let result = label(&format!("{long_first} test"));
    // Result should be "aaaaaaaaa-test" where first word is truncated to 50 chars
    assert_eq!(
        result.len(),
        55,
        "first word truncated to 50 chars + hyphen + 4 chars for 'test'"
    );
    assert_eq!(
        result
            .chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
            .count(),
        result.len()
    );
}

#[test]
fn test_label_empty_after_sanitization() {
    // If first word has no valid chars after sanitization, return "unknown"
    assert_eq!(label("!!! test"), "unknown");
    assert_eq!(label("../ test"), "unknown");
    assert_eq!(label("@@@ test"), "unknown");
}

#[test]
fn test_label_prevents_dotfile_creation() {
    // Leading dots (dotfiles) should be stripped from first word
    assert_eq!(label(".cargo test"), "cargo-test");
    assert_eq!(label("..cargo test"), "cargo-test");
    // Path with /path/.hidden/test -> first word is "test" (after rsplit)
    assert_eq!(label("/path/.hidden/test"), "test");
    assert_eq!(label("./hidden/bin/test"), "test");
}

// ---------------------------------------------------------------------------
// label (existing tests)
// ---------------------------------------------------------------------------

#[test]
fn test_label_extraction() {
    // Second word is a flag ("-x") — excluded, so single word stays as-is
    assert_eq!(label("pytest -x"), "pytest");
    // Path stripped from first word, second word ("test") included as subcommand
    assert_eq!(label("/usr/bin/cargo test"), "cargo-test");
}

#[test]
fn test_label_path_extraction() {
    // Single-word commands (no subcommand) remain unchanged
    assert_eq!(label("/usr/local/bin/rustc"), "rustc");
    assert_eq!(label("./target/release/oo"), "oo");
}

#[test]
fn test_label_empty_command() {
    assert_eq!(label(""), "unknown");
}

#[test]
fn test_label_subcommand_included() {
    // Two-word commands where second word is a subcommand (not a flag)
    assert_eq!(label("cargo fmt --check"), "cargo-fmt");
    assert_eq!(label("cargo clippy -- -D warnings"), "cargo-clippy");
    assert_eq!(label("npm run build"), "npm-run");
    assert_eq!(label("cargo test"), "cargo-test");
}

#[test]
fn test_label_flag_excluded() {
    // Second word starting with '-' is a flag — not included in label
    assert_eq!(label("pytest -x"), "pytest");
    assert_eq!(label("cargo --verbose test"), "cargo");
}

#[test]
fn test_label_sanitizes_unsafe_chars_in_second_word() {
    // `/` in path argument → slashes stripped
    assert_eq!(label("git some/path/arg"), "git-somepatharg");
    assert_eq!(label("cargo /absolute/path"), "cargo-absolutepath");
    // `=` in subcommand value → stripped
    assert_eq!(label("git subcommand=val"), "git-subcommandval");
    // `..` traversal attempt → dots stripped, remaining chars kept
    assert_eq!(label("cmd ../etc/passwd"), "cmd-etcpasswd");
    // Two-flag-only command → no valid subcommand, returns first word only
    assert_eq!(label("rustc --foo --bar"), "rustc");
}

#[test]
fn test_label_second_word_length_limit() {
    // Second word should also be limited to MAX_FILENAME_COMPONENT (50 chars)
    let long_second = "a".repeat(100);
    let result = label(&format!("cargo {long_second}"));
    // Result should be "cargo-aaaaaaaaa" where second word is truncated to 50 chars
    assert_eq!(
        result.len(),
        56,
        "'cargo-' (6 chars) + second word truncated to 50 chars = 56"
    );
}

// ---------------------------------------------------------------------------
// detect_provider / LearnConfig::default
// ---------------------------------------------------------------------------

#[test]
fn test_default_config_has_valid_fields() {
    // Provider is auto-detected from env; all fields must be non-empty.
    let config = LearnConfig::default();
    assert!(!config.provider.is_empty(), "provider must not be empty");
    assert!(!config.model.is_empty(), "model must not be empty");
    assert!(
        !config.api_key_env.is_empty(),
        "api_key_env must not be empty"
    );
}

#[test]
fn test_detect_provider_no_keys_defaults_to_anthropic() {
    // Uses closure-based injection — no env mutation, no race conditions.
    let config = detect_provider_with(|_| None);
    assert_eq!(config.provider, "anthropic");
    assert_eq!(config.api_key_env, "ANTHROPIC_API_KEY");
    assert_eq!(config.model, "claude-haiku-4-5");
}

#[test]
fn test_detect_provider_anthropic_model_name() {
    // Verify the Anthropic model uses the non-dated alias for forward compatibility.
    let config = detect_provider_with(|key| {
        if key == "ANTHROPIC_API_KEY" {
            Some("test-key".into())
        } else {
            None
        }
    });
    assert_eq!(config.provider, "anthropic");
    assert_eq!(
        config.model, "claude-haiku-4-5",
        "Anthropic model must use the stable alias, not the dated snapshot"
    );
}

// ---------------------------------------------------------------------------
// load_learn_config / patterns_dir
// ---------------------------------------------------------------------------

#[test]
fn test_load_learn_config_no_file_returns_default() {
    // Returns default config (or Err if config.toml is malformed) — must not panic
    match load_learn_config() {
        Ok(c) => {
            assert!(!c.provider.is_empty());
            assert!(!c.model.is_empty());
            assert!(!c.api_key_env.is_empty());
        }
        Err(_) => {} // malformed config.toml in test env is acceptable
    }
}

#[test]
fn test_patterns_dir_is_under_config_dir() {
    let _env = crate::test_env::env_guard(); // reads OO_CONFIG_DIR, set under this guard elsewhere
    let dir = patterns_dir();
    let s = dir.to_string_lossy();
    assert!(s.ends_with("oo/patterns"), "got: {s}");
}

// ---------------------------------------------------------------------------
// run_background
// ---------------------------------------------------------------------------

// Status goes to a temp dir; config and API key still come from the environment.
fn run_bg(path: &Path) -> Result<(), Error> {
    let status = tempfile::TempDir::new().unwrap();
    let log = status.path().join("learn-status.log");
    run_background(path, path.parent().unwrap(), &log)
}

#[test]
fn test_run_background_missing_file_returns_err() {
    // Payload-shaped name in a directory that exists, so the read error path runs.
    let dir = tempfile::TempDir::new().unwrap();
    let missing = dir.path().join(".tmpAbC123");
    assert!(run_bg(&missing).is_err());
}

#[test]
fn test_run_background_invalid_json_returns_err() {
    let tmp = tempfile::NamedTempFile::new().expect("tempfile");
    std::fs::write(tmp.path(), b"not valid json {{{").expect("write");
    assert!(run_bg(tmp.path()).is_err());
}

// ---------------------------------------------------------------------------
// run_background: hint handling
// ---------------------------------------------------------------------------

#[test]
fn test_run_background_with_hint_extracts_hint() {
    let tmp = tempfile::NamedTempFile::new().expect("tempfile");
    let data = serde_json::json!({
        "command": "cargo test",
        "output": "test result: ok. 5 passed\n",
        "exit_code": 0,
        "hint": "capture summary line only"
    });
    std::fs::write(tmp.path(), data.to_string()).expect("write");

    // Verify run_background can parse the hint
    let path = tmp.path();
    let content = std::fs::read_to_string(path).expect("read");
    let parsed: serde_json::Value = serde_json::from_str(&content).expect("valid json");

    let hint = parsed["hint"].as_str();
    assert_eq!(hint, Some("capture summary line only"));
}

// ---------------------------------------------------------------------------
// run_background: exit_code bounds checking
// ---------------------------------------------------------------------------

#[test]
fn test_run_background_invalid_exit_code_truncation() {
    // Test that exit_code outside i32 range is rejected
    let tmp = tempfile::NamedTempFile::new().expect("tempfile");
    // i32::MAX is 2147483647, so use 2147483648 (i64 value that exceeds i32)
    let data = serde_json::json!({
        "command": "echo hello",
        "output": "hello",
        "exit_code": 2147483648i64
    });
    std::fs::write(tmp.path(), data.to_string()).expect("write");

    let err_msg = run_bg(tmp.path()).unwrap_err().to_string();
    assert!(
        err_msg.contains("exit_code out of range for i32"),
        "error should mention i32 range: got {}",
        err_msg
    );
}

#[test]
fn test_run_background_negative_exit_code_out_of_range() {
    // Test that exit_code below i32::MIN is rejected
    let tmp = tempfile::NamedTempFile::new().expect("tempfile");
    // i32::MIN is -2147483648, so use -2147483649 (i64 value that exceeds i32)
    let data = serde_json::json!({
        "command": "echo hello",
        "output": "hello",
        "exit_code": -2147483649i64
    });
    std::fs::write(tmp.path(), data.to_string()).expect("write");

    let err_msg = run_bg(tmp.path()).unwrap_err().to_string();
    assert!(
        err_msg.contains("exit_code out of range for i32"),
        "error should mention i32 range: got {}",
        err_msg
    );
}

// ---------------------------------------------------------------------------
// run_learn_with_config: validation limits
// ---------------------------------------------------------------------------

#[test]
fn test_run_learn_with_config_rejects_hint_too_long() {
    let tmpdir = tempfile::TempDir::new().expect("tempdir");
    let config = LearnConfig {
        provider: "anthropic".into(),
        model: "claude-haiku-4-5".into(),
        api_key_env: "ANTHROPIC_API_KEY".into(),
    };
    let status_path = tmpdir.path().join("status.log");
    let long_hint = "x".repeat(1001);
    let params = LearnParams {
        config: &config,
        api_key: "test-key",
        base_url: "https://api.anthropic.com/v1/messages",
        patterns_dir: tmpdir.path(),
        learn_status_path: &status_path,
        hint: Some(&long_hint), // Exceeds MAX_HINT_LENGTH (1000)
    };

    let result = run_learn_with_config(&params, "echo test", "output", 0);
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("--hint too long"),
        "error should mention hint limit: got {}",
        err_msg
    );
    assert!(
        err_msg.contains("1000"),
        "error should mention limit value: got {}",
        err_msg
    );
}

#[test]
fn test_run_learn_with_config_truncates_command() {
    // Command truncation is applied silently within run_learn_with_config
    // We verify by checking that a very long command doesn't cause validation errors
    let tmpdir = tempfile::TempDir::new().expect("tempdir");
    let config = LearnConfig {
        provider: "anthropic".into(),
        model: "claude-haiku-4-5".into(),
        api_key_env: "ANTHROPIC_API_KEY".into(),
    };
    let long_command = "a".repeat(200); // Exceeds MAX_COMMAND_LENGTH (100)
    let status_path = tmpdir.path().join("status.log");
    let params = LearnParams {
        config: &config,
        api_key: "test-key",
        base_url: "https://api.anthropic.com/v1/messages",
        patterns_dir: tmpdir.path(),
        learn_status_path: &status_path,
        hint: None,
    };

    // This will fail due to API, not command length validation
    let result = run_learn_with_config(&params, &long_command, "output", 0);
    // The error should be API-related, not "command too long"
    if let Err(e) = result {
        let err_msg = e.to_string();
        assert!(
            !err_msg.contains("too long"),
            "command should be truncated, not rejected: got {}",
            err_msg
        );
    }
}

#[test]
fn test_truncate_utf8_multibyte_command_crosses_limit() {
    // Test that truncating a multi-byte UTF-8 command that crosses the byte limit
    // doesn't panic and produces valid UTF-8.
    // Each Chinese character is 3 bytes: 你好世界 = 4 chars × 3 bytes = 12 bytes
    let multibyte_command = "测试".repeat(50); // 50 chars × 3 bytes = 150 bytes, exceeds MAX_COMMAND_LENGTH (100)
    let truncated = crate::learn_utils::truncate_utf8(&multibyte_command, 100);

    // Should truncate to valid UTF-8 boundary (33 chars = 99 bytes)
    assert_eq!(truncated.len(), 99);
    assert!(std::str::from_utf8(truncated.as_bytes()).is_ok());
    // Verify it's a valid prefix of the original string (valid UTF-8)
    assert!(multibyte_command.starts_with(truncated));

    // Test with emoji (4 bytes each): 🎉🎊 = 2 chars × 4 bytes = 8 bytes
    let emoji_command = "🎉".repeat(30); // 30 chars × 4 bytes = 120 bytes
    let truncated_emoji = crate::learn_utils::truncate_utf8(&emoji_command, 100);
    // Should truncate to 25 chars = 100 bytes exactly
    assert_eq!(truncated_emoji.len(), 100);
    assert!(std::str::from_utf8(truncated_emoji.as_bytes()).is_ok());
    assert!(emoji_command.starts_with(truncated_emoji));
}