opencrabs 0.5.10

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/opencrabs/opencrabs/releases
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
//! #722 phase 2: the background-task manager runs a command detached and, on
//! completion, enqueues a system QueuedUserMessage into the originating session.

use crate::brain::agent::PushOrigin;
use crate::brain::agent::service::MessageEnqueueCallback;
use crate::brain::agent::service::QueuedUserMessage;
use crate::brain::agent::service::background_tasks::{
    BackgroundTaskManager, ClaudeTurnTasks, CmdResult, claude_completion_message,
    claude_needs_survival_delivery, claude_task_label, clear_claude_mirrors_for_session,
    completion_message, format_elapsed, run_detached, short_label, tail_lines,
};
use crate::brain::agent::service::restart_recovery;
use crate::brain::agent::service::session_routes;
use std::sync::{Arc, Mutex};
use uuid::Uuid;

#[test]
fn tail_keeps_last_n_lines() {
    let text = (1..=100)
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join("\n");
    let tail = tail_lines(&text, 3);
    assert_eq!(tail, "98\n99\n100");
    // Fewer lines than n -> whole text.
    assert_eq!(tail_lines("a\nb", 10), "a\nb");
}

#[test]
fn completion_message_reflects_success_and_failure() {
    let ok = completion_message(
        "cargo test",
        "cargo test --all-features",
        &CmdResult {
            success: true,
            code: 0,
            output: "test result: ok. 5 passed".into(),
        },
        12.0,
    );
    assert!(ok.context_text.contains("exit 0 (success)"));
    assert!(ok.context_text.contains("cargo test --all-features"));
    assert!(ok.context_text.contains("Do not re-run"));
    assert!(ok.display_text.contains("finished"));
    // #15: the typed receipt payload rides along for the echo card.
    let meta = ok.bg_meta.expect("bg completion carries BgTaskMeta");
    assert!(meta.success);
    assert_eq!(meta.label, "cargo test");
    assert_eq!(meta.elapsed_secs, 12.0);
    assert_eq!(meta.tail, "test result: ok. 5 passed");

    let fail = completion_message(
        "build",
        "cargo build",
        &CmdResult {
            success: false,
            code: 101,
            output: "error[E0001]".into(),
        },
        3.0,
    );
    assert!(fail.context_text.contains("exit 101 (failure)"));
    assert!(fail.display_text.contains("failed"));
    let meta = fail.bg_meta.expect("failed completion still carries meta");
    assert!(!meta.success);
    assert_eq!(meta.elapsed_secs, 3.0);
}

#[test]
fn format_elapsed_buckets_match_the_spec() {
    assert_eq!(format_elapsed(0.4), "0s");
    assert_eq!(format_elapsed(42.0), "42s");
    assert_eq!(format_elapsed(59.6), "1m 0s"); // rounds up into the minute bucket
    assert_eq!(format_elapsed(185.0), "3m 5s");
    assert_eq!(format_elapsed(3599.4), "59m 59s");
    assert_eq!(format_elapsed(3720.0), "1h 2m");
}

#[test]
fn short_label_takes_the_command_after_cd() {
    assert_eq!(short_label("cd ~/proj && cargo test"), "cargo test");
    assert_eq!(short_label("cargo build"), "cargo build");
}

#[tokio::test]
// The test_guard serializes suites touching the process-global parked-queue
// state; holding it across the polling `.await`s below is the entire point —
// same shape as the session_notify suite (#22).
#[allow(clippy::await_holding_lock)]
async fn spawn_command_enqueues_on_completion() {
    // register_session_route → claim_session touches the process-global
    // parked-queue state, so serialize against other suites that do too.
    let _guard = restart_recovery::test_guard();
    #[allow(clippy::type_complexity)]
    let recorded: Arc<Mutex<Vec<(Uuid, QueuedUserMessage)>>> = Arc::new(Mutex::new(Vec::new()));
    let rec = recorded.clone();
    let enqueue: MessageEnqueueCallback = Arc::new(move |sid, msg| {
        rec.lock().unwrap().push((sid, msg));
    });

    let mgr = Arc::new(BackgroundTaskManager::new());
    let sid = Uuid::new_v4();
    // The manager no longer carries its own route (fork #19 — delivery goes
    // through the one gated route, which resolves the session's registered
    // route), so claim the session the way a channel would: register the
    // recording callback as its route.
    session_routes::register_session_route(sid, enqueue);
    let cwd = std::env::temp_dir();

    mgr.clone().spawn_command(
        sid,
        cwd,
        "echo probe".to_string(),
        "echo BG_DONE_MARKER".to_string(),
    );

    // Wait (bounded) for the detached command to finish and enqueue.
    let mut waited = 0;
    while recorded.lock().unwrap().is_empty() && waited < 50 {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        waited += 1;
    }

    let r = recorded.lock().unwrap();
    assert_eq!(r.len(), 1, "completion should have enqueued exactly once");
    assert_eq!(r[0].0, sid);
    assert!(r[0].1.context_text.contains("BG_DONE_MARKER"));
    assert!(r[0].1.context_text.contains("exit 0 (success)"));
    // Running count drops back to zero after completion.
    assert_eq!(mgr.running_for(sid), 0);
}

/// #1748: `spawn_command_with_hook` hands the outcome to the hook INSTEAD of
/// the generic session delivery; a hook that replaces the process on success
/// would orphan an in-memory enqueue mid-flight. Same lifecycle (timer, status
/// file, DB accounting), different completion route.
#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn spawn_command_with_hook_replaces_generic_delivery() {
    // register_session_route → claim_session touches the process-global
    // parked-queue state, so serialize against other suites that do too.
    let _guard = restart_recovery::test_guard();
    #[allow(clippy::type_complexity)]
    let recorded: Arc<Mutex<Vec<(Uuid, QueuedUserMessage)>>> = Arc::new(Mutex::new(Vec::new()));
    let rec = recorded.clone();
    let enqueue: MessageEnqueueCallback = Arc::new(move |sid, msg| {
        rec.lock().unwrap().push((sid, msg));
    });

    let mgr = Arc::new(BackgroundTaskManager::new());
    let sid = Uuid::new_v4();
    session_routes::register_session_route(sid, enqueue);

    // The hook records what it learned; the session route must stay silent.
    let hooked: Arc<Mutex<Option<(bool, bool)>>> = Arc::new(Mutex::new(None));
    let hk = hooked.clone();
    let hook: crate::brain::agent::service::background_tasks::CompletionHook = Box::new(
        move |ctx: crate::brain::agent::service::background_tasks::HookContext| {
            Box::pin(async move {
                *hk.lock().unwrap() = Some((ctx.result.success, ctx.elapsed_secs >= 0.0));
            })
        },
    );

    mgr.clone().spawn_command_with_hook(
        sid,
        std::env::temp_dir(),
        "hook probe".to_string(),
        "echo HOOK_DONE_MARKER".to_string(),
        hook,
    );

    // Wait (bounded) for the detached command to finish and fire the hook.
    let mut waited = 0;
    while hooked.lock().unwrap().is_none() && waited < 50 {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        waited += 1;
    }

    let h = hooked.lock().unwrap();
    let (success, elapsed_ok) = h.expect("hook must fire on completion");
    assert!(success, "echo must report success to the hook");
    assert!(elapsed_ok, "hook carries the command runtime");

    // The generic delivery did NOT run: the session route got nothing.
    assert!(
        recorded.lock().unwrap().is_empty(),
        "a hook replaces generic session delivery"
    );
    // Running count drops back to zero after completion.
    assert_eq!(mgr.running_for(sid), 0);
}

// --- #1776 seam 2: mirrored claude-cli task lifecycle ---

#[test]
fn claude_task_label_carries_source_tag() {
    assert_eq!(claude_task_label("btglunt18"), "claude-cli btglunt18");
}

#[test]
fn mirror_registers_then_removes() {
    let mgr = Arc::new(BackgroundTaskManager::new());
    let sid = Uuid::new_v4();
    let label = claude_task_label("btglunt18");

    // Before start: nothing running for the session.
    assert_eq!(mgr.running_for(sid), 0);

    mgr.mirror_started(sid, &label);
    assert_eq!(mgr.running_for(sid), 1);
    let rows = mgr.running_tasks(sid);
    assert_eq!(rows.len(), 1);
    assert_eq!(
        rows[0].label, "claude-cli btglunt18",
        "row carries the source tag"
    );

    // The completed notification removes the shadow row.
    mgr.mirror_finished(sid, &label);
    assert_eq!(mgr.running_for(sid), 0);
    assert!(mgr.running_tasks(sid).is_empty());
}

#[test]
fn mirror_finish_is_noop_for_unknown_task() {
    let mgr = Arc::new(BackgroundTaskManager::new());
    let sid = Uuid::new_v4();

    // A notification for a task we never saw started (mid-session attach):
    // must not panic and must not conjure a row.
    mgr.mirror_finished(sid, &claude_task_label("ghost01"));
    assert_eq!(mgr.running_for(sid), 0);
}

#[test]
fn mirror_finish_removes_oldest_on_duplicate_labels() {
    let mgr = Arc::new(BackgroundTaskManager::new());
    let sid = Uuid::new_v4();
    let label = claude_task_label("btglunt18");

    // Two tasks with the same id-shaped label: the manager cannot tell them
    // apart (same rule as spawned commands with identical labels), so the
    // first finish drops the OLDEST row and the survivor stays visible.
    mgr.mirror_started(sid, &label);
    std::thread::sleep(std::time::Duration::from_millis(5));
    mgr.mirror_started(sid, &label);
    assert_eq!(mgr.running_for(sid), 2);

    mgr.mirror_finished(sid, &label);
    assert_eq!(mgr.running_for(sid), 1, "oldest row removed, survivor kept");

    mgr.mirror_finished(sid, &label);
    assert_eq!(mgr.running_for(sid), 0, "second finish clears the survivor");
}

#[test]
fn survivor_delivery_fires_only_for_tasks_not_started_this_turn() {
    let sid = Uuid::new_v4();
    let other = Uuid::new_v4();
    let mut turn_started = ClaudeTurnTasks::default();

    // Empty marker set: every notification is a post-exit survivor.
    assert!(claude_needs_survival_delivery(
        &turn_started,
        sid,
        "bAAA1111"
    ));

    // Started THIS turn: silent, claude sees the notification natively.
    turn_started.insert((sid, "bAAA1111".to_string()));
    assert!(!claude_needs_survival_delivery(
        &turn_started,
        sid,
        "bAAA1111"
    ));

    // Session isolation: the same task id under another session, or another
    // task under this session, is still a survivor.
    turn_started.insert((other, "bAAA1111".to_string()));
    turn_started.insert((sid, "bBBB2222".to_string()));
    assert!(claude_needs_survival_delivery(
        &turn_started,
        other,
        "bCCC3333"
    ));
    assert!(claude_needs_survival_delivery(
        &turn_started,
        sid,
        "bDDD4444"
    ));
}

#[test]
fn claude_completion_message_carries_status_and_summary_mechanically() {
    let msg = claude_completion_message("bAAA1111", "completed", Some("tests passed"));
    assert!(
        msg.context_text.contains("claude-cli bAAA1111"),
        "label in context"
    );
    assert!(msg.context_text.contains("Status: completed"));
    assert!(msg.context_text.contains("Summary: tests passed"));
    assert!(msg.context_text.contains("Do not re-run the task"));
    assert_eq!(
        msg.display_text,
        "🔧 background task finished: claude-cli bAAA1111"
    );
    assert_eq!(msg.origin, PushOrigin::BackgroundTask, "#1221 echo tag");
    assert!(msg.bg_meta.is_none(), "no CmdResult, no fabricated receipt");
}

#[test]
fn claude_completion_message_failed_wording_and_summary_fallback() {
    let msg = claude_completion_message("bBBB2222", "failed", None);
    assert!(msg.context_text.contains("Status: failed"));
    assert!(msg.context_text.contains("Summary: (no summary provided)"));
    assert_eq!(
        msg.display_text,
        "🔧 background task failed: claude-cli bBBB2222"
    );
}

// --- #1984: mirror rows must not outlive their notification or their ----
// --- process, and the detached wait must never be open-ended --------------

#[test]
fn task_notification_clears_the_row_for_any_status() {
    // The old match arm removed the mirror row only for completed|failed, so
    // a task claude reports with any OTHER terminal status (stopped,
    // cancelled, killed) left the row alive forever, and that stuck row is
    // what kept the typing tick pinging. The arm now keys the clear on the
    // SUBTYPE; only the synthetic result wake stays status-limited. The arm
    // lives inside the 1200-line stream loop (no provider harness exists to
    // drive it), so this is a source pin, the same shape the WhatsApp parity
    // test (#1989) uses, and the clearing itself is behavioral in
    // `process_exit_clears_the_sessions_mirrors_and_markers_only` below.
    let src = include_str!("../brain/agent/service/helpers.rs");
    assert!(
        src.contains("(\"task_notification\", st)"),
        "any task_notification must clear the mirror row, not only the two \
         statuses the old arm enumerated"
    );
    assert!(
        !src.contains("(\"task_notification\", Some(s @ (\"completed\" | \"failed\")))"),
        "the status-filtered clear is the #1984 stuck-row bug, restored"
    );
    assert!(
        src.contains("matches!(st, Some(\"completed\") | Some(\"failed\"))"),
        "the synthetic survival wake must stay limited to result statuses"
    );
}

#[test]
fn process_exit_clears_the_sessions_mirrors_and_markers_only() {
    // The other stuck-row source: a notification that never arrives (task
    // stopped, CLI died). The exit guard drains the marker set, and every
    // marker IS a row this process mirrored in, so rows and markers leave
    // together. Another session's mid-turn rows must survive untouched.
    let mgr = BackgroundTaskManager::new();
    let sid_a = Uuid::new_v4();
    let sid_b = Uuid::new_v4();
    let mut tasks: ClaudeTurnTasks = ClaudeTurnTasks::new();
    for (sid, id) in [(sid_a, "a1"), (sid_a, "a2"), (sid_b, "b1")] {
        tasks.insert((sid, id.to_string()));
        mgr.mirror_started(sid, &claude_task_label(id));
    }
    assert_eq!(mgr.running_for(sid_a), 2);
    clear_claude_mirrors_for_session(&mut tasks, &mgr, sid_a);
    assert_eq!(
        mgr.running_for(sid_a),
        0,
        "a session's mirrors must not outlive its process"
    );
    assert_eq!(mgr.running_for(sid_b), 1, "other sessions are untouched");
    assert!(
        !tasks.iter().any(|(s, _)| *s == sid_a),
        "A's markers go with its rows"
    );
    assert_eq!(tasks.len(), 1, "B's marker stays");
}

/// The wait-what-the-shell-owns behavior of #1984. These are shell job
/// semantics (`&`), so unix.
#[cfg(unix)]
#[tokio::test]
async fn detached_run_does_not_wait_on_survivor_output() {
    // `sleep 10 &` leaves a child holding the write end of the output. The
    // old `.output()` waited for EOF on that pipe, so it waited on a shell
    // that had ALREADY exited, and a long-lived server held the tracker row
    // (and every typing tick counting it) open forever. Waiting the shell
    // only returns the moment `echo done` has run.
    let sid = Uuid::new_v4();
    let started = std::time::Instant::now();
    let result = run_detached(
        "sleep 10 & echo done",
        &std::env::temp_dir(),
        sid,
        std::time::Duration::from_secs(30),
    )
    .await;
    let elapsed = started.elapsed();
    assert!(result.success, "the shell exited 0: {}", result.output);
    assert!(
        result.output.contains("done"),
        "output must be captured: {:?}",
        result.output
    );
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "the shell exited at once; waiting {elapsed:?} means the wait is on \
         the survivor's inherited output, not on the shell (#1984)"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn detached_run_stops_waiting_at_its_ceiling() {
    // The other half: a foreground command that never exits (a dev server
    // without `&`) used to hold its row open forever. The ceiling cuts the
    // wait, marks the task failed, and still reports what printed before.
    let sid = Uuid::new_v4();
    let started = std::time::Instant::now();
    let result = run_detached(
        "echo starting; sleep 30",
        &std::env::temp_dir(),
        sid,
        std::time::Duration::from_millis(300),
    )
    .await;
    let elapsed = started.elapsed();
    assert!(!result.success, "a ceiling cut is not a success");
    assert!(
        result.output.contains("ceiling"),
        "the receipt must say why: {:?}",
        result.output
    );
    assert!(
        result.output.contains("starting"),
        "what ran before the cut is still reported"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "the ceiling must end the wait, not sleep 30 ({elapsed:?})"
    );
}