opencrabs 0.3.72

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Dedicated coverage for the plan-mode tool gate
//! (`brain::tools::plan_gate`), driven by MCP-style [`ToolHints`].
//! Verifies, per state:
//!
//! - pre-init Editing allows read-only tools, sends mutators to
//!   RequireApproval
//! - post-init Editing sends mutators to RequireApproval, allows
//!   writes ONLY to the session `.md`
//! - Active freezes the `.md` against generic write tools; the seed
//!   window hard-denies mutators
//! - NoPlan gates nothing
//!
//! The gate is pure: `hints.read_only` is the sole signal. No name
//! lists, no capability branching.

use crate::brain::tools::plan_gate::check_plan_gate;
use crate::brain::tools::r#trait::ToolHints;
use crate::config::profile::{home_for_profile, with_profile_home_async};
use crate::tui::plan::{PlanDocument, PlanStatus, PlanTask, TaskType};
use crate::utils::plan_files::{create_design_md, plan_md_path, save_plan, set_pre_init_editing};
use serde_json::json;
use uuid::Uuid;

/// Read-only hint (read_file, grep, web_search, plan, etc.).
fn ro() -> ToolHints {
    ToolHints {
        read_only: true,
        destructive: false,
        idempotent: true,
        open_world: false,
    }
}

/// Mutator hint (bash, edit_file, telegram_send, spawn_agent, etc.).
fn mut_tool() -> ToolHints {
    ToolHints {
        read_only: false,
        destructive: true,
        idempotent: false,
        open_world: true,
    }
}

async fn in_temp_home<F, T>(f: F) -> T
where
    F: std::future::Future<Output = T>,
{
    let profile = format!("plan-gate-test-{}", Uuid::new_v4());
    let out = with_profile_home_async(Some(&profile), f).await;
    let home = home_for_profile(Some(&profile));
    let _ = std::fs::remove_dir_all(&home);
    out
}

async fn make_post_init_editing(sid: Uuid) {
    let plan = PlanDocument::new(sid, "Design".to_string());
    save_plan(&plan).await.unwrap();
    create_design_md(sid, "Design").await.unwrap();
}

async fn make_active(sid: Uuid, with_md: bool) {
    let mut plan = PlanDocument::new(sid, "Exec".to_string());
    let mut task = PlanTask::new(1, "t1".to_string(), "d".to_string(), TaskType::Edit);
    // A started checklist: the seed window (all tasks Pending) has its own
    // stricter policy, covered separately below.
    task.start();
    plan.add_task(task);
    plan.status = PlanStatus::Active;
    save_plan(&plan).await.unwrap();
    if with_md {
        create_design_md(sid, "Exec").await.unwrap();
    }
}

#[tokio::test]
async fn no_plan_gates_nothing() {
    in_temp_home(async {
        let sid = Uuid::new_v4();
        for (name, hints) in [
            ("edit_file", &mut_tool()),
            ("bash", &mut_tool()),
            ("telegram_send", &mut_tool()),
            ("spawn_agent", &mut_tool()),
        ] {
            assert!(
                check_plan_gate(sid, name, hints, &json!({}))
                    .await
                    .is_allowed(),
                "{name} must pass with no plan"
            );
        }
    })
    .await;
}

#[tokio::test]
async fn pre_init_gates_mutators_allows_reads_and_plan() {
    in_temp_home(async {
        let sid = Uuid::new_v4();
        set_pre_init_editing(sid).await.unwrap();

        // Mutators go to RequireApproval in pre-init Editing.
        for (name, hints) in [
            ("edit_file", &mut_tool()),
            ("bash", &mut_tool()),
            ("execute_code", &mut_tool()),
            ("telegram_send", &mut_tool()),
            ("browser_click", &mut_tool()),
            ("spawn_agent", &mut_tool()),
            ("evolve", &mut_tool()),
        ] {
            assert!(
                check_plan_gate(sid, name, hints, &json!({}))
                    .await
                    .needs_approval(),
                "{name} must require approval pre-init"
            );
        }

        // Brain-file writes are mutators too.
        let deny = check_plan_gate(
            sid,
            "write_opencrabs_file",
            &mut_tool(),
            &json!({"path": "MEMORY.md"}),
        )
        .await;
        assert!(
            deny.needs_approval(),
            "opencrabs write must require approval pre-init"
        );

        // Read-only tools flow through.
        for (name, hints) in [("read_file", &ro()), ("web_search", &ro()), ("plan", &ro())] {
            assert!(
                check_plan_gate(sid, name, hints, &json!({}))
                    .await
                    .is_allowed(),
                "{name} must be allowed pre-init"
            );
        }
    })
    .await;
}

#[tokio::test]
async fn post_init_gates_mutators_to_md_only() {
    in_temp_home(async {
        let sid = Uuid::new_v4();
        make_post_init_editing(sid).await;
        let md = plan_md_path(sid).await;

        // Mutators go to approval (RequireApproval), not hard deny.
        for (name, hints) in [
            ("bash", &mut_tool()),
            ("execute_code", &mut_tool()),
            ("slack_send", &mut_tool()),
            ("browser_eval", &mut_tool()),
            ("resume_agent", &mut_tool()),
            ("cron_manage", &mut_tool()),
        ] {
            assert!(
                check_plan_gate(sid, name, hints, &json!({}))
                    .await
                    .needs_approval(),
                "{name} must require approval post-init"
            );
        }

        // The session .md is the only writable file for a mutator.
        let ok = check_plan_gate(
            sid,
            "write_file",
            &mut_tool(),
            &json!({"path": md.to_string_lossy()}),
        )
        .await;
        assert!(ok.is_allowed(), "session .md write must pass, got: {ok:?}");

        // edit_file on the .md passes too (path key is shared).
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": md.to_string_lossy()})
            )
            .await
            .is_allowed()
        );

        // Project writes go to approval.
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": "/tmp/project/main.rs"})
            )
            .await
            .needs_approval()
        );

        // Other ~/.opencrabs writes go to approval too.
        assert!(
            check_plan_gate(
                sid,
                "write_opencrabs_file",
                &mut_tool(),
                &json!({"path": "MEMORY.md"})
            )
            .await
            .needs_approval()
        );

        // A mutator with no recognizable target goes to approval.
        assert!(
            check_plan_gate(sid, "generate_document", &mut_tool(), &json!({}))
                .await
                .needs_approval()
        );

        // Read-only tools flow through.
        for (name, hints) in [
            ("read_file", &ro()),
            ("grep", &ro()),
            ("plan", &ro()),
            ("follow_up_question", &ro()),
        ] {
            assert!(
                check_plan_gate(sid, name, hints, &json!({}))
                    .await
                    .is_allowed(),
                "{name} must be allowed post-init"
            );
        }
    })
    .await;
}

#[tokio::test]
async fn active_freezes_md_only() {
    in_temp_home(async {
        let sid = Uuid::new_v4();
        make_active(sid, true).await;
        let md = plan_md_path(sid).await;

        // The design .md is frozen against generic write tools.
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": md.to_string_lossy()})
            )
            .await
            .is_denied(),
            "Active .md write must be frozen"
        );

        // Everything else follows the normal approval policy.
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": "/tmp/project/main.rs"})
            )
            .await
            .is_allowed()
        );
        assert!(
            check_plan_gate(sid, "bash", &mut_tool(), &json!({"command": "ls"}))
                .await
                .is_allowed()
        );
        assert!(
            check_plan_gate(sid, "telegram_send", &mut_tool(), &json!({}))
                .await
                .is_allowed()
        );
        assert!(
            check_plan_gate(sid, "spawn_agent", &mut_tool(), &json!({}))
                .await
                .is_allowed()
        );
    })
    .await;
}

#[tokio::test]
async fn active_checklist_without_md_gates_nothing_on_writes() {
    in_temp_home(async {
        // Checklist-track plans have no design .md; nothing to freeze.
        let sid = Uuid::new_v4();
        make_active(sid, false).await;
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": "/tmp/project/main.rs"})
            )
            .await
            .is_allowed()
        );
        assert!(
            check_plan_gate(sid, "bash", &mut_tool(), &json!({"command": "ls"}))
                .await
                .is_allowed()
        );
    })
    .await;
}

#[tokio::test]
async fn seed_window_blocks_mutators_allows_plan_and_reads() {
    in_temp_home(async {
        // Approved design plan whose checklist has not started yet (empty
        // tasks): only read-only tools and the plan tool flow through.
        let sid = Uuid::new_v4();
        let mut plan = PlanDocument::new(sid, "Seeding".to_string());
        plan.status = PlanStatus::Active;
        save_plan(&plan).await.unwrap();
        create_design_md(sid, "Seeding").await.unwrap();

        assert!(
            check_plan_gate(sid, "plan", &ro(), &json!({"operation": "add_tasks"}))
                .await
                .is_allowed()
        );
        assert!(
            check_plan_gate(sid, "read_file", &ro(), &json!({}))
                .await
                .is_allowed()
        );
        // Mutators are hard-denied in the seed window.
        assert!(
            check_plan_gate(sid, "bash", &mut_tool(), &json!({"command": "ls"}))
                .await
                .is_denied()
        );
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": "/tmp/p/main.rs"})
            )
            .await
            .is_denied()
        );
        assert!(
            check_plan_gate(sid, "spawn_agent", &mut_tool(), &json!({}))
                .await
                .is_denied(),
            "spawn must be blocked in seed window (mutator)"
        );

        // Partial seed (tasks added, none started) stays blocked too.
        let mut plan = crate::utils::plan_files::load_plan(sid).await.unwrap();
        plan.add_task(PlanTask::new(
            1,
            "t1".to_string(),
            "d".to_string(),
            TaskType::Edit,
        ));
        save_plan(&plan).await.unwrap();
        assert!(
            check_plan_gate(sid, "bash", &mut_tool(), &json!({"command": "ls"}))
                .await
                .is_denied()
        );

        // Once a task starts, the seed window closes and normal Active
        // policy applies (only the .md stays frozen).
        let mut plan = crate::utils::plan_files::load_plan(sid).await.unwrap();
        plan.tasks[0].start();
        save_plan(&plan).await.unwrap();
        assert!(
            check_plan_gate(sid, "bash", &mut_tool(), &json!({"command": "ls"}))
                .await
                .is_allowed()
        );
        assert!(
            check_plan_gate(
                sid,
                "edit_file",
                &mut_tool(),
                &json!({"path": "/tmp/p/main.rs"})
            )
            .await
            .is_allowed()
        );
    })
    .await;
}

// ── restrict_registry_to_read_only (#649) ───────────────────────────────
// A subagent spawned while the parent is Editing must be read-only. The
// filter strips non-read-only tools from the child registry via the MCP
// `read_only` hint (child runs under a fresh NoPlan session the per-call
// gate would not catch), keeping only read/search/network tools.

struct CapTool {
    name: &'static str,
    caps: Vec<crate::brain::tools::r#trait::ToolCapability>,
}

#[async_trait::async_trait]
impl crate::brain::tools::Tool for CapTool {
    fn name(&self) -> &str {
        self.name
    }
    fn description(&self) -> &str {
        "cap test tool"
    }
    fn input_schema(&self) -> serde_json::Value {
        json!({ "type": "object" })
    }
    fn capabilities(&self) -> Vec<crate::brain::tools::r#trait::ToolCapability> {
        self.caps.clone()
    }
    async fn execute(
        &self,
        _input: serde_json::Value,
        _ctx: &crate::brain::tools::ToolExecutionContext,
    ) -> crate::brain::tools::error::Result<crate::brain::tools::ToolResult> {
        Ok(crate::brain::tools::ToolResult::success("ok".to_string()))
    }
}

#[test]
fn read_only_filter_strips_mutators_keeps_reads() {
    use crate::brain::tools::ToolRegistry;
    use crate::brain::tools::plan_gate::restrict_registry_to_read_only;
    use crate::brain::tools::r#trait::ToolCapability;
    use std::sync::Arc;

    let registry = ToolRegistry::new();
    // Read-only surface (no destructive caps) must survive.
    registry.register(Arc::new(CapTool {
        name: "read_file",
        caps: vec![ToolCapability::ReadFiles],
    }));
    registry.register(Arc::new(CapTool {
        name: "grep",
        caps: vec![ToolCapability::ReadFiles],
    }));
    registry.register(Arc::new(CapTool {
        name: "http_request",
        caps: vec![ToolCapability::Network],
    }));
    registry.register(Arc::new(CapTool {
        name: "follow_up_question",
        caps: vec![],
    }));
    // Mutators (destructive trio) must be stripped by the read_only hint.
    registry.register(Arc::new(CapTool {
        name: "edit_file",
        caps: vec![ToolCapability::WriteFiles],
    }));
    registry.register(Arc::new(CapTool {
        name: "bash",
        caps: vec![ToolCapability::ExecuteShell],
    }));
    registry.register(Arc::new(CapTool {
        name: "spawn_agent",
        caps: vec![ToolCapability::SystemModification],
    }));

    restrict_registry_to_read_only(&registry);

    assert!(registry.has_tool("read_file"), "reads must survive");
    assert!(registry.has_tool("grep"), "search must survive");
    assert!(
        registry.has_tool("http_request"),
        "network read must survive"
    );
    assert!(
        registry.has_tool("follow_up_question"),
        "the question tool must survive"
    );
    assert!(!registry.has_tool("edit_file"), "writes must be stripped");
    assert!(!registry.has_tool("bash"), "bash must be stripped");
    assert!(
        !registry.has_tool("spawn_agent"),
        "spawn must be stripped so no non-restricted grandchild can be minted"
    );
}