opencrabs 0.5.3

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/adolfousier/opencrabs/releases
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
// Tests for `write_opencrabs_file` tool.

use crate::brain::tools::write_opencrabs_file::*;
use crate::brain::tools::{Tool, ToolExecutionContext};
use tempfile::TempDir;
use uuid::Uuid;

fn ctx() -> ToolExecutionContext {
    ToolExecutionContext::new(Uuid::new_v4())
}

fn tool() -> WriteOpenCrabsFileTool {
    WriteOpenCrabsFileTool
}

// ── metadata ─────────────────────────────────────────────────────────────────

#[test]
fn test_tool_name_and_requires_approval() {
    let t = tool();
    assert_eq!(t.name(), "write_opencrabs_file");
    assert!(t.requires_approval(), "writes must require approval");
}

#[test]
fn test_input_schema_required_fields() {
    let schema = tool().input_schema();
    let required = schema["required"].as_array().unwrap();
    assert!(required.iter().any(|v| v.as_str() == Some("path")));
    assert!(required.iter().any(|v| v.as_str() == Some("operation")));
}

// ── path validation ───────────────────────────────────────────────────────────

/// A named-profile home shape: `<tmp>/.opencrabs/profiles/<name>`.
fn named_profile_home(dir: &TempDir, name: &str) -> std::path::PathBuf {
    dir.path().join(".opencrabs").join("profiles").join(name)
}

/// The default-profile home shape: `<tmp>/.opencrabs`.
fn default_home(dir: &TempDir) -> std::path::PathBuf {
    dir.path().join(".opencrabs")
}

#[test]
fn test_home_is_named_profile_predicate() {
    let dir = TempDir::new().unwrap();

    assert!(
        home_is_named_profile(&named_profile_home(&dir, "ops")),
        "base/profiles/ops is a named-profile home"
    );
    assert!(
        home_is_named_profile(&named_profile_home(&dir, "family")),
        "base/profiles/family is a named-profile home"
    );
    assert!(
        !home_is_named_profile(&default_home(&dir)),
        "base is NOT a named-profile home"
    );
    assert!(
        !home_is_named_profile(&dir.path().join("profiles")),
        "a directory merely named profiles (no name segment under it) is not a profile home"
    );
}

#[test]
fn test_leading_profiles_segment_predicate() {
    assert!(leading_profiles_segment("profiles/ops/TOOLS.md"));
    assert!(
        leading_profiles_segment("./profiles/ops/TOOLS.md"),
        "a leading CurDir must be skipped, not treated as the first segment"
    );
    assert!(leading_profiles_segment("profiles"));
    assert!(!leading_profiles_segment("MEMORY.md"));
    assert!(!leading_profiles_segment("memory/profiles/note.md"));
    assert!(!leading_profiles_segment(""));
}

#[test]
fn test_empty_path_rejected() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "").is_err());
}

#[test]
fn test_absolute_path_rejected() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "/etc/passwd").is_err());
    assert!(validate_opencrabs_path(&home, "~/MEMORY.md").is_err());
}

#[test]
fn test_path_traversal_rejected() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "../etc/passwd").is_err());
    assert!(validate_opencrabs_path(&home, "../../secrets").is_err());
    assert!(validate_opencrabs_path(&home, "subdir/../../etc/passwd").is_err());
}

#[test]
fn test_valid_brain_files_accepted() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "MEMORY.md").is_ok());
    assert!(validate_opencrabs_path(&home, "USER.md").is_ok());
    assert!(validate_opencrabs_path(&home, "SOUL.md").is_ok());
}

#[test]
fn test_valid_config_files_accepted() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "commands.toml").is_ok());
    assert!(validate_opencrabs_path(&home, "config.toml").is_ok());
}

#[test]
fn test_valid_subdirectory_paths_accepted() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    assert!(validate_opencrabs_path(&home, "memory/2026-03-02.md").is_ok());
    assert!(validate_opencrabs_path(&home, "agents/session/context.json").is_ok());
}

/// A leading `profiles/` segment duplicates a NAMED profile's home path, so it
/// is refused in BOTH spellings — the plain one and the `./`-prefixed one that
/// used to slip past the string test (issue #350).
#[test]
fn test_profiles_prefix_duplication_rejected() {
    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");

    let result = validate_opencrabs_path(&home, "profiles/ops/TOOLS.md");
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.contains("duplicates it"),
        "Error message should name the real rule: {err}"
    );
    assert!(
        err.contains("profiles/ops/TOOLS.md"),
        "Error should echo the bad path: {err}"
    );

    // A second duplicating path, to show the refusal is not specific to one file.
    // The bare `profiles` segment is covered in the predicate test above.
    assert!(validate_opencrabs_path(&home, "profiles/ops/MEMORY.md").is_err());

    // The bypass spelling must get the SAME verdict, not be accepted.
    assert!(
        validate_opencrabs_path(&home, "./profiles/ops/TOOLS.md").is_err(),
        "the leading './' spelling must not bypass the gate"
    );
}

/// Issue #350: for the DEFAULT profile (`<base>`), `profiles/<name>/...` is a
/// sibling profile's real home, not a duplicated prefix — it must be accepted,
/// in both spellings.
#[test]
fn test_profiles_sibling_path_accepted_for_default_home() {
    let dir = TempDir::new().unwrap();
    let home = default_home(&dir);

    assert!(
        validate_opencrabs_path(&home, "profiles/family/USER.md").is_ok(),
        "profiles/family/USER.md is the sibling profile's real home"
    );
    assert!(
        validate_opencrabs_path(&home, "profiles/ops/TOOLS.md").is_ok(),
        "profiles/ops/TOOLS.md is the sibling profile's real home"
    );
    assert!(
        validate_opencrabs_path(&home, "./profiles/family/USER.md").is_ok(),
        "identical target, identical verdict — the ./ spelling is accepted too"
    );
}

/// The default home keeps every traversal refusal it had before #350.
#[test]
fn test_default_home_still_rejects_traversal() {
    let dir = TempDir::new().unwrap();
    let home = default_home(&dir);

    assert!(validate_opencrabs_path(&home, "../etc/passwd").is_err());
    assert!(validate_opencrabs_path(&home, "/etc/passwd").is_err());
    assert!(validate_opencrabs_path(&home, "~/MEMORY.md").is_err());
    assert!(validate_opencrabs_path(&home, "").is_err());
}

// ── operation validation ──────────────────────────────────────────────────────

#[tokio::test]
async fn test_unknown_operation_returns_error() {
    let result = tool()
        .execute(
            serde_json::json!({"path": "MEMORY.md", "operation": "delete"}),
            &ctx(),
        )
        .await
        .unwrap();
    assert!(!result.success);
    assert!(result.error.unwrap().contains("Unknown operation"));
}

#[tokio::test]
async fn test_overwrite_missing_content_returns_error() {
    let result = tool()
        .execute(
            serde_json::json!({"path": "MEMORY.md", "operation": "overwrite"}),
            &ctx(),
        )
        .await
        .unwrap();
    assert!(!result.success);
    assert!(result.error.unwrap().contains("content is required"));
}

#[tokio::test]
async fn test_append_missing_content_returns_error() {
    let result = tool()
        .execute(
            serde_json::json!({"path": "MEMORY.md", "operation": "append"}),
            &ctx(),
        )
        .await
        .unwrap();
    assert!(!result.success);
    assert!(result.error.unwrap().contains("content is required"));
}

#[tokio::test]
async fn test_replace_missing_old_text_returns_error() {
    let result = tool()
        .execute(
            serde_json::json!({"path": "MEMORY.md", "operation": "replace", "new_text": "x"}),
            &ctx(),
        )
        .await
        .unwrap();
    assert!(!result.success);
    assert!(result.error.unwrap().contains("old_text is required"));
}

#[tokio::test]
async fn test_replace_missing_new_text_returns_error() {
    let result = tool()
        .execute(
            serde_json::json!({"path": "MEMORY.md", "operation": "replace", "old_text": "x"}),
            &ctx(),
        )
        .await
        .unwrap();
    assert!(!result.success);
    assert!(result.error.unwrap().contains("new_text is required"));
}

// ── roundtrip write + read ────────────────────────────────────────────────────

#[test]
fn test_overwrite_roundtrip_via_fs() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("MEMORY.md");
    std::fs::write(&path, "initial content").unwrap();
    std::fs::write(&path, "updated content").unwrap();
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "updated content");
}

#[test]
fn test_append_roundtrip_via_fs() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("MEMORY.md");
    std::fs::write(&path, "## Section\n").unwrap();
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .append(true)
        .open(&path)
        .unwrap();
    f.write_all(b"\nnew note").unwrap();
    let result = std::fs::read_to_string(&path).unwrap();
    assert!(result.contains("## Section"));
    assert!(result.contains("new note"));
}

#[test]
fn test_replace_roundtrip_via_fs() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("MEMORY.md");
    std::fs::write(&path, "old value here").unwrap();
    let content = std::fs::read_to_string(&path).unwrap();
    let updated = content.replacen("old value", "new value", 1);
    std::fs::write(&path, &updated).unwrap();
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "new value here");
}

#[test]
fn test_subdirectory_created_on_write() {
    let dir = TempDir::new().unwrap();
    let subdir = dir.path().join("memory");
    let path = subdir.join("note.md");
    // Simulate create_dir_all + write
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(&path, "content").unwrap();
    assert!(path.exists());
}

// ── NFC normalization for replace ────────────────────────────────────────────

/// Verify that NFC normalization makes replace work when the file has NFD
/// bytes but the search string uses NFC (the common macOS copy-paste case).
/// Regression test for issue #256.
#[test]
fn test_replace_nfc_normalizes_both_sides() {
    use unicode_normalization::UnicodeNormalization;

    let dir = TempDir::new().unwrap();
    let path = dir.path().join("MEMORY.md");

    // Em-dash: U+2014. In NFC it's 3 bytes (E2 80 94). In NFD it's the same
    // (em-dash has no decomposition). Multiplication sign: U+00D7.
    // In NFC: C3 97. In NFD: same (no decomposition).
    // The real-world issue is with accented characters, e.g. é:
    // NFC: C3 A9 (single codepoint U+00E9)
    // NFD: 65 CC 81 (e + combining acute accent U+0301)

    // Write file with NFD-normalized content (as macOS might produce)
    let nfd_content: String = "café résumé".nfd().collect();
    std::fs::write(&path, &nfd_content).unwrap();

    // Search with NFC-normalized text (as most users would type)
    let search_nfc: String = "café".nfc().collect();
    let replace_nfc: String = "coffee".nfc().collect();

    // Verify they're different byte sequences
    let search_nfd: String = search_nfc.nfd().collect();
    assert_ne!(
        search_nfc.as_bytes(),
        search_nfd.as_bytes(),
        "NFC and NFD should differ for accented chars"
    );

    // Raw contains() would FAIL because NFC search won't match NFD file
    let raw_file = std::fs::read_to_string(&path).unwrap();
    assert!(
        !raw_file.contains(search_nfc.as_str()),
        "raw contains should fail with mixed normalization"
    );

    // NFC-normalize both sides (what write_opencrabs_file now does)
    let file_nfc: String = raw_file.nfc().collect();
    let search_nfc_norm: String = search_nfc.nfc().collect();
    assert!(
        file_nfc.contains(search_nfc_norm.as_str()),
        "NFC-normalized contains should match"
    );

    // Do the replacement
    let updated = file_nfc.replacen(search_nfc_norm.as_str(), replace_nfc.as_str(), 1);
    std::fs::write(&path, &updated).unwrap();

    let result = std::fs::read_to_string(&path).unwrap();
    assert!(
        result.contains("coffee"),
        "replacement should have succeeded: got {:?}",
        result
    );
    assert!(
        result.contains("résumé"),
        "unrelated text should be preserved: got {:?}",
        result
    );
}

/// Verify that replace with Unicode symbols (em-dash, multiplication sign,
/// less-than-or-equal) works through NFC normalization.
#[test]
fn test_replace_unicode_symbols_via_nfc() {
    use unicode_normalization::UnicodeNormalization;

    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.md");

    // Content with various Unicode symbols
    let content = "price: 10×2 ≤ 25 — final";
    std::fs::write(&path, content).unwrap();

    let search = "10×2";
    let replacement = "10x2";

    // NFC normalize both sides
    let raw = std::fs::read_to_string(&path).unwrap();
    let file_nfc: String = raw.nfc().collect();
    let search_nfc: String = search.nfc().collect();

    assert!(
        file_nfc.contains(search_nfc.as_str()),
        "multiplication sign should match after NFC normalization"
    );

    let updated = file_nfc.replacen(search_nfc.as_str(), replacement, 1);
    std::fs::write(&path, &updated).unwrap();

    let result = std::fs::read_to_string(&path).unwrap();
    assert!(
        result.contains("10x2"),
        "replacement succeeded: {:?}",
        result
    );
    assert!(
        result.contains("≤"),
        "other Unicode preserved: {:?}",
        result
    );
    assert!(result.contains("—"), "em-dash preserved: {:?}", result);
}

// ── cross-boundary: the tool's real execute() path ───────────────────────────
//
// The predicate tests above call the validator directly. These two drive the
// ACTUAL tool boundary — `WriteOpenCrabsFileTool::execute` under a temp home
// override — so the call-site wiring (home hoisted above validation, the
// two-argument invocation) is exercised, not merely the function it delegates
// to. Nothing is asserted against a helper's own delegate: the file either
// exists on disk afterwards or it does not.

#[tokio::test]
async fn test_execute_writes_real_file_under_temp_home() {
    use crate::config::profile::with_home_override_async;

    let dir = TempDir::new().unwrap();
    let home = default_home(&dir);
    std::fs::create_dir_all(&home).unwrap();

    let ctx = ctx();
    let t = tool();
    let result = with_home_override_async(home.clone(), async {
        t.execute(
            serde_json::json!({
                "path": "memory/2026-03-02.md",
                "operation": "overwrite",
                "content": "hello from the boundary test",
            }),
            &ctx,
        )
        .await
    })
    .await
    .unwrap();

    assert!(result.success, "write should succeed: {:?}", result.error);

    // Read back through the filesystem — the real cross-boundary assertion.
    let landed = std::fs::read_to_string(home.join("memory/2026-03-02.md")).unwrap();
    assert_eq!(landed, "hello from the boundary test");
}

#[tokio::test]
async fn test_execute_rejects_profiles_prefix_and_writes_nothing() {
    use crate::config::profile::with_home_override_async;

    let dir = TempDir::new().unwrap();
    let home = named_profile_home(&dir, "ops");
    std::fs::create_dir_all(&home).unwrap();

    let ctx = ctx();
    let t = tool();
    for spelling in ["profiles/ops/TOOLS.md", "./profiles/ops/TOOLS.md"] {
        let result = with_home_override_async(home.clone(), async {
            t.execute(
                serde_json::json!({
                    "path": spelling,
                    "operation": "overwrite",
                    "content": "must never land",
                }),
                &ctx,
            )
            .await
        })
        .await
        .unwrap();

        assert!(!result.success, "{spelling} must be rejected");
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("duplicates it"),
            "{spelling}: error should explain the duplication, got {:?}",
            result.error
        );
        // The real boundary check: nothing was created one level too deep.
        assert!(
            !home.join(spelling).exists(),
            "{spelling} must not exist on disk"
        );
    }
}