opencrabs 0.3.37

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Tests for `brain_file_safety` — the chokepoint that protects
//! `~/.opencrabs/*.md` brain files from agent-driven destruction.
//!
//! Background: 2026-04-26 the RSI agent shrank TOOLS.md from 33 KB to a
//! stub by passing the entire file as `old_content` to a
//! `self_improve` action="update". MEMORY.md got the same treatment.
//! The user policy is append-only — removals only when the bytes
//! disappearing are duplicates that survive elsewhere in the result.

use crate::brain::tools::brain_file_safety::{
    ShrinkCheck, backup_before_write, check_no_shrink, is_protected_brain_file, is_protected_path,
};
use std::path::Path;

mod protected_predicate {
    use super::*;

    #[test]
    fn known_brain_files_are_protected() {
        for name in [
            "SOUL.md",
            "USER.md",
            "AGENTS.md",
            "TOOLS.md",
            "CODE.md",
            "SECURITY.md",
            "MEMORY.md",
            "BOOT.md",
        ] {
            assert!(is_protected_brain_file(name), "{name} should be protected");
        }
    }

    #[test]
    fn case_insensitive_match() {
        // The agent sometimes lowercases names — protect either way.
        assert!(is_protected_brain_file("memory.md"));
        assert!(is_protected_brain_file("tools.md"));
    }

    #[test]
    fn unrelated_files_are_not_protected() {
        assert!(!is_protected_brain_file("commands.toml"));
        assert!(!is_protected_brain_file("notes.md"));
        assert!(!is_protected_brain_file("memory/2026-04-26.md"));
    }

    #[test]
    fn path_predicate_uses_basename() {
        assert!(is_protected_path(Path::new("/Users/x/.opencrabs/TOOLS.md")));
        assert!(is_protected_path(Path::new("TOOLS.md")));
        assert!(!is_protected_path(Path::new(
            "/Users/x/.opencrabs/memory/log.md"
        )));
    }
}

mod shrink_check {
    use super::*;

    fn protected() -> &'static Path {
        Path::new("/tmp/fake/TOOLS.md")
    }

    fn unprotected() -> &'static Path {
        Path::new("/tmp/fake/notes.md")
    }

    #[test]
    fn unprotected_file_is_always_allowed() {
        // Non-brain files can shrink freely — that's not what this guard
        // is for.
        let result = check_no_shrink(unprotected(), "lots of content here", "tiny", false, false);
        assert_eq!(result, ShrinkCheck::Allowed);
    }

    #[test]
    fn append_to_protected_is_allowed() {
        // The append-only happy path — content grows.
        let existing = "line one\nline two\n";
        let updated = "line one\nline two\nline three\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, false, false),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn equal_size_rewrite_is_allowed() {
        // Same length update (e.g. typo fix) doesn't shrink, so it's
        // allowed even on a protected file.
        let existing = "abc def ghi";
        let updated = "abc XYZ ghi";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, false, false),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn shrink_without_dedup_intent_is_rejected() {
        // The 2026-04-26 case: agent rewrites the whole file from many
        // KB down to a stub. Hard reject.
        let existing = "rule one\nrule two\nrule three\nrule four\nrule five\n";
        let updated = "rule one\n";
        match check_no_shrink(protected(), existing, updated, false, false) {
            ShrinkCheck::Rejected { message } => {
                assert!(message.contains("Refusing to shrink"));
                assert!(message.contains("TOOLS.md"));
                assert!(message.contains("append-only"));
            }
            other => panic!("expected Rejected, got {:?}", other),
        }
    }

    #[test]
    fn shrink_with_dedup_intent_passes_when_lines_survive() {
        // Legit dedup: existing has the same line twice, updated has it
        // once. Every original line is still present somewhere.
        let existing = "alpha\nbeta\nalpha\ngamma\n";
        let updated = "alpha\nbeta\ngamma\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, true, false),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn shrink_with_dedup_intent_rejected_when_unique_line_disappears() {
        // dedup_intent is set but the agent is sneakily removing
        // unique content. The hint mentions the intent specifically
        // so the agent learns it can't be used as a bypass.
        let existing = "rule one\nrule two\nrule three\n";
        let updated = "rule one\n";
        match check_no_shrink(protected(), existing, updated, true, false) {
            ShrinkCheck::Rejected { message } => {
                assert!(
                    message.contains("dedup_intent"),
                    "rejection should call out the abused dedup_intent flag: {message}"
                );
            }
            other => panic!("expected Rejected with dedup_intent hint, got {:?}", other),
        }
    }

    #[test]
    fn empty_lines_in_original_dont_block_dedup() {
        // Blank-line spacing in the original shouldn't be required to
        // round-trip — only non-blank lines count toward the survival
        // check.
        let existing = "alpha\n\nbeta\n\nalpha\n";
        let updated = "alpha\nbeta\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, true, false),
            ShrinkCheck::Allowed
        );
    }
}

mod cleanup_intent {
    use super::*;

    fn protected() -> &'static Path {
        Path::new("/tmp/fake/TOOLS.md")
    }

    #[test]
    fn cleanup_intent_allows_shrinking_protected_file() {
        // User explicitly wants to clean up a brain file — allow it.
        let existing = "rule one\nrule two\nrule three\nrule four\nrule five\n";
        let updated = "rule one\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, false, true),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn cleanup_intent_bypasses_dedup_requirement() {
        // cleanup_intent doesn't need every original line to survive.
        let existing = "alpha\nbeta\ngamma\ndelta\n";
        let updated = "only one line\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, false, true),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn cleanup_intent_false_still_enforces_append_only() {
        // When cleanup_intent is false, the append-only rule still applies.
        let existing = "rule one\nrule two\nrule three\n";
        let updated = "rule one\n";
        match check_no_shrink(protected(), existing, updated, false, false) {
            ShrinkCheck::Rejected { message } => {
                assert!(message.contains("Refusing to shrink"));
            }
            other => panic!("expected Rejected, got {:?}", other),
        }
    }

    #[test]
    fn cleanup_intent_with_dedup_both_true() {
        // Both flags set — cleanup_intent takes precedence.
        let existing = "alpha\nbeta\nalpha\ngamma\n";
        let updated = "alpha\n";
        assert_eq!(
            check_no_shrink(protected(), existing, updated, true, true),
            ShrinkCheck::Allowed
        );
    }

    #[test]
    fn cleanup_intent_on_unprotected_file() {
        // Unprotected files can shrink regardless — cleanup_intent is irrelevant.
        let unprotected = Path::new("/tmp/fake/notes.md");
        let existing = "lots of content here";
        let updated = "tiny";
        assert_eq!(
            check_no_shrink(unprotected, existing, updated, false, true),
            ShrinkCheck::Allowed
        );
    }
}

mod backup {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn skips_backup_for_nonexistent_file() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("doesnotexist.md");
        let result = backup_before_write(&path).expect("ok");
        assert!(result.is_none());
    }

    #[test]
    fn backs_up_existing_file_to_timestamped_path() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("TOOLS.md");
        std::fs::write(&path, "important content").expect("seed");

        let backup = backup_before_write(&path)
            .expect("ok")
            .expect("backup path returned");

        assert!(backup.exists(), "backup file should exist");
        let backup_name = backup.file_name().unwrap().to_string_lossy().to_string();
        assert!(
            backup_name.starts_with("TOOLS.md."),
            "backup name should start with original: {backup_name}"
        );
        assert!(
            backup_name.ends_with(".bak"),
            "backup name should end with .bak: {backup_name}"
        );
        let backed_up = std::fs::read_to_string(&backup).expect("read backup");
        assert_eq!(backed_up, "important content");

        // Original is untouched
        let original = std::fs::read_to_string(&path).expect("read original");
        assert_eq!(original, "important content");
    }
}

mod dedup_append {
    use crate::brain::tools::brain_file_safety::is_duplicate_append;

    #[test]
    fn empty_content_is_duplicate() {
        assert!(is_duplicate_append("existing content", ""));
        assert!(is_duplicate_append("existing content", "   "));
    }

    #[test]
    fn exact_match_is_duplicate() {
        let existing = "## Server Info\nHost: localhost\nPort: 8080\n";
        assert!(is_duplicate_append(
            existing,
            "## Server Info\nHost: localhost\nPort: 8080\n"
        ));
    }

    #[test]
    fn substring_match_is_duplicate() {
        let existing = "alpha\nbeta\ngamma\ndelta\n";
        assert!(is_duplicate_append(existing, "beta\ngamma\n"));
    }

    #[test]
    fn new_content_is_not_duplicate() {
        let existing = "## Server Info\nHost: localhost\n";
        assert!(!is_duplicate_append(
            existing,
            "## Database\nHost: db.example.com\n"
        ));
    }

    #[test]
    fn same_section_header_is_duplicate() {
        let existing = "## Server Info\nOld content here\n";
        assert!(is_duplicate_append(
            existing,
            "## Server Info\nNew content here\n"
        ));
    }

    #[test]
    fn same_subsection_header_is_duplicate() {
        let existing = "## Servers\n### Web Server\nDetails here\n";
        assert!(is_duplicate_append(
            existing,
            "### Web Server\nUpdated details\n"
        ));
    }

    #[test]
    fn different_subsection_is_not_duplicate() {
        let existing = "## Servers\n### Web Server\nDetails here\n";
        assert!(!is_duplicate_append(
            existing,
            "### DB Server\nNew details\n"
        ));
    }

    #[test]
    fn high_line_overlap_is_duplicate() {
        let existing = "line one\nline two\nline three\nline four\nline five\n";
        let new_content = "line one\nline two\nline three\nline six\n";
        // 3 out of 4 non-empty lines overlap = 75% > 60%
        assert!(is_duplicate_append(existing, new_content));
    }

    #[test]
    fn low_line_overlap_is_not_duplicate() {
        let existing = "line one\nline two\nline three\n";
        let new_content = "line one\nnew alpha\nnew beta\nnew gamma\n";
        // 1 out of 4 = 25% < 60%
        assert!(!is_duplicate_append(existing, new_content));
    }

    #[test]
    fn empty_existing_file_is_not_duplicate() {
        assert!(!is_duplicate_append("", "## New Section\nFresh content\n"));
    }

    #[test]
    fn whitespace_trimmed_for_comparison() {
        let existing = "## Server\nHost: localhost\n";
        assert!(is_duplicate_append(
            existing,
            "  ## Server\nHost: localhost\n  "
        ));
    }
}

mod filter_duplicate_append {
    use crate::brain::tools::brain_file_safety::{AppendDedup, filter_duplicate_append};

    #[test]
    fn all_new_content_passes_through() {
        let existing = "## Servers\nWeb: localhost\n";
        let result = filter_duplicate_append(existing, "## Database\nHost: db.local\nPort: 5432\n");
        assert!(matches!(result, AppendDedup::AllNew));
    }

    #[test]
    fn fully_duplicate_content_is_blocked() {
        let existing = "## Servers\nWeb: localhost\n";
        let result = filter_duplicate_append(existing, "## Servers\nWeb: localhost\n");
        assert!(matches!(result, AppendDedup::AllDuplicate));
    }

    #[test]
    fn partially_new_filters_correctly() {
        let existing = "## Servers\nWeb: localhost\n\n## Ports\nHTTP: 80\n";
        // First paragraph already exists, second is new
        let new_content = "## Servers\nWeb: localhost\n\n## Database\nHost: db.local\n";
        match filter_duplicate_append(existing, new_content) {
            AppendDedup::Filtered {
                filtered_content,
                skipped_paragraphs,
            } => {
                assert_eq!(skipped_paragraphs, 1);
                assert!(filtered_content.contains("## Database"));
                assert!(!filtered_content.contains("## Servers"));
            }
            other => panic!("expected Filtered, got {:?}", other),
        }
    }

    #[test]
    fn three_paragraphs_two_existing() {
        let existing = "## Alpha\nalpha content\n\n## Bravo\nbravo content\n";
        // Alpha and Bravo exist, Charlie is new
        let new_content =
            "## Alpha\nalpha content\n\n## Bravo\nbravo content\n\n## Charlie\ncharlie content\n";
        match filter_duplicate_append(existing, new_content) {
            AppendDedup::Filtered {
                filtered_content,
                skipped_paragraphs,
            } => {
                assert_eq!(skipped_paragraphs, 2);
                assert!(filtered_content.contains("## Charlie"));
                assert!(!filtered_content.contains("## Alpha"));
                assert!(!filtered_content.contains("## Bravo"));
            }
            other => panic!("expected Filtered, got {:?}", other),
        }
    }

    #[test]
    fn empty_existing_file_allows_everything() {
        let result = filter_duplicate_append(
            "",
            "## New Section\nFresh content\n\n## Another\nMore content\n",
        );
        assert!(matches!(result, AppendDedup::AllNew));
    }

    #[test]
    fn empty_new_content_is_all_duplicate() {
        let result = filter_duplicate_append("existing", "");
        assert!(matches!(result, AppendDedup::AllDuplicate));
    }

    #[test]
    fn same_header_different_body_is_filtered() {
        let existing = "## Config\nold value\n";
        let new_content = "## Config\nnew value\n";
        // Same header → paragraph_exists returns true
        let result = filter_duplicate_append(existing, new_content);
        assert!(matches!(result, AppendDedup::AllDuplicate));
    }

    #[test]
    fn single_paragraph_all_new() {
        let existing = "## Alpha\nalpha\n";
        let result = filter_duplicate_append(existing, "## Beta\nbeta\n");
        assert!(matches!(result, AppendDedup::AllNew));
    }
}