selfware 0.6.3

Your personal AI workshop — software you own, software that lasts
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
use super::*;
use std::time::Duration;

// ── format_file_size tests ──

#[test]
fn format_file_size_bytes() {
    assert_eq!(Agent::format_file_size(0), "0B");
    assert_eq!(Agent::format_file_size(512), "512B");
    assert_eq!(Agent::format_file_size(1023), "1023B");
}

#[test]
fn format_file_size_kilobytes() {
    assert_eq!(Agent::format_file_size(1024), "1.0KB");
    assert_eq!(Agent::format_file_size(2048), "2.0KB");
    assert_eq!(Agent::format_file_size(1536), "1.5KB");
}

#[test]
fn format_file_size_megabytes() {
    assert_eq!(Agent::format_file_size(1024 * 1024), "1.0MB");
    assert_eq!(Agent::format_file_size(2 * 1024 * 1024), "2.0MB");
}

// ── Slash command matching patterns ──
// These tests verify the string-matching logic used in the interactive loop
// to route slash commands, extracted as pure assertions.

#[test]
fn slash_command_routing_exact_matches() {
    let commands = vec![
        "/help",
        "/status",
        "/stats",
        "/compress",
        "/clear",
        "/tools",
        "/mode",
        "/ctx",
        "/context",
        "/diff",
        "/git",
        "/undo",
        "/cost",
        "/model",
        "/last",
        "/debug",
        "/debug-log",
        "/compact",
        "/verbose",
        "/config",
        "/memory",
        "/copy",
        "/restore",
        "/vim",
        "/theme",
        "/queue",
        "/swarm",
        "/chat",
    ];
    for cmd in &commands {
        assert!(
            cmd.starts_with('/'),
            "Command '{}' should start with /",
            cmd
        );
    }

    // Non-slash input should NOT be treated as a command
    let non_commands = ["help", "status", "hello", "fix the bug"];
    for input in &non_commands {
        assert!(
            !input.starts_with('/'),
            "'{}' should not be treated as a slash command",
            input
        );
    }
}

#[test]
fn looks_like_slash_command_matches_unhandled_commands() {
    // Registry-advertised commands with no REPL handler must be caught
    // by the unknown-slash guard instead of burning a paid chat message.
    for input in [
        "/mode yolo",
        "/analyze",
        "/analyze ./src",
        "/garden",
        "/journal",
        "/palette",
        "/totally-made-up",
        "/help extra args",
    ] {
        assert!(
            looks_like_slash_command(input),
            "'{}' should be treated as a slash command",
            input
        );
    }
}

#[test]
fn looks_like_slash_command_passes_paths_and_chat() {
    // Absolute paths and ordinary chat must still reach the LLM.
    for input in [
        "/tmp/foo.rs",
        "/home/rig/selfware/src/main.rs",
        "/",
        "/..",
        "hello",
        "fix the /bug in /src/main.rs",
        "",
    ] {
        assert!(
            !looks_like_slash_command(input),
            "'{}' should NOT be treated as a slash command",
            input
        );
    }
}

#[test]
fn slash_command_with_argument_parsing() {
    // Verify strip_prefix patterns used throughout the interactive loop
    let input = "/review src/main.rs";
    let arg = input.strip_prefix("/review ").map(str::trim);
    assert_eq!(arg, Some("src/main.rs"));

    let input = "/analyze ./src";
    let arg = input.strip_prefix("/analyze ").map(str::trim);
    assert_eq!(arg, Some("./src"));

    let input = "/plan implement auth flow";
    let arg = input.strip_prefix("/plan ").map(str::trim);
    assert_eq!(arg, Some("implement auth flow"));

    let input = "/swarm refactor error handling";
    let arg = input.strip_prefix("/swarm ").map(str::trim);
    assert_eq!(arg, Some("refactor error handling"));

    let input = "/queue fix the tests";
    let arg = input.strip_prefix("/queue ").map(str::trim);
    assert_eq!(arg, Some("fix the tests"));
}

#[test]
fn context_command_aliases() {
    // Both /context and /ctx should work for all subcommands
    let aliases = [("/context", "/ctx"), ("/context clear", "/ctx clear")];
    for (full, short) in &aliases {
        assert!(full.starts_with("/context") || full.starts_with("/ctx"));
        assert!(short.starts_with("/ctx"));
    }

    let load_input = "/ctx load .rs,.toml";
    let arg = load_input
        .strip_prefix("/context load ")
        .or_else(|| load_input.strip_prefix("/ctx load "))
        .map(str::trim);
    assert_eq!(arg, Some(".rs,.toml"));
}

// ── Shell escape parsing ──

#[test]
fn shell_escape_command_extraction() {
    // The interactive loop uses `!` prefix for shell escapes
    let input = "!ls -la";
    assert!(input.starts_with('!'));
    let cmd = input.strip_prefix('!').map(str::trim);
    assert_eq!(cmd, Some("ls -la"));

    let input = "! git status";
    let cmd = input.strip_prefix('!').map(str::trim);
    assert_eq!(cmd, Some("git status"));

    // Empty shell command
    let input = "!";
    let cmd = input.strip_prefix('!').map(str::trim);
    assert_eq!(cmd, Some(""));
}

// ── Exit/quit detection ──

#[test]
fn exit_commands_recognized() {
    for input in &["exit", "quit", "/exit", "/quit", "/q"] {
        assert!(is_exit_command(input), "'{}' should trigger exit", input);
    }

    for input in &[
        "exiting",
        "quitting",
        "EXIT",
        "exit now",
        "query",
        "/question",
        "q",
    ] {
        assert!(
            !is_exit_command(input),
            "'{}' should NOT trigger exit",
            input
        );
    }
}

// ── Large paste preview logic ──

#[test]
fn large_paste_detection() {
    const LARGE_PASTE_THRESHOLD: usize = 3000;
    const PREVIEW_CHARS: usize = 200;

    let small_input = "Hello world";
    assert!(small_input.len() <= LARGE_PASTE_THRESHOLD);

    let large_input = "x".repeat(5000);
    assert!(large_input.len() > LARGE_PASTE_THRESHOLD);

    // Verify preview extraction logic
    let start_preview: String = large_input.chars().take(PREVIEW_CHARS).collect();
    assert_eq!(start_preview.len(), PREVIEW_CHARS);

    let end_preview: String = large_input
        .chars()
        .rev()
        .take(PREVIEW_CHARS)
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    assert_eq!(end_preview.len(), PREVIEW_CHARS);
}

// ── Queued message preview truncation ──

#[test]
fn queued_message_preview_truncation() {
    let short_msg = "Short message";
    let preview = preview_with_ellipsis(short_msg, QUEUE_DRAIN_PREVIEW_BYTES);
    assert_eq!(preview, "Short message");

    let long_msg = "a".repeat(200);
    let preview = preview_with_ellipsis(&long_msg, QUEUE_DRAIN_PREVIEW_BYTES);
    assert!(preview.len() <= QUEUE_DRAIN_PREVIEW_BYTES + 3);
    assert!(preview.ends_with("..."));
}

#[test]
fn strip_trailing_submission_newlines_preserves_multiline_content() {
    let pasted = "def chart():\n    return 42\n\n";
    assert_eq!(
        strip_trailing_submission_newlines(pasted),
        "def chart():\n    return 42"
    );

    let carriage_return = "line one\r\nline two\r\n";
    assert_eq!(
        strip_trailing_submission_newlines(carriage_return),
        "line one\r\nline two"
    );
}

// ── Queue management subcommand routing ──

#[test]
fn queue_subcommand_routing() {
    // /queue list and /queue clear must match before /queue <msg>
    let input = "/queue list";
    assert!(input == "/queue list");
    assert!(input.starts_with("/queue ")); // would also match generic handler

    let input = "/queue clear";
    assert!(input == "/queue clear");
    assert!(input.starts_with("/queue ")); // would also match generic handler

    // /queue drop <n> uses strip_prefix
    let input = "/queue drop 3";
    let idx_str = input.strip_prefix("/queue drop ");
    assert_eq!(idx_str, Some("3"));
    let idx: usize = idx_str.unwrap().trim().parse().unwrap();
    assert_eq!(idx, 3);

    // /queue drop with extra whitespace
    let input = "/queue drop  5 ";
    let idx_str = input.strip_prefix("/queue drop ");
    assert_eq!(idx_str.unwrap().trim().parse::<usize>().unwrap(), 5);

    // /queue drop with invalid index
    let input = "/queue drop abc";
    let idx_str = input.strip_prefix("/queue drop ").unwrap();
    assert!(idx_str.trim().parse::<usize>().is_err());
}

#[test]
fn queue_subcommands_do_not_match_bare_queue() {
    // /queue (bare) should not match subcommands
    let input = "/queue";
    assert!(input == "/queue");
    assert!(!input.starts_with("/queue ")); // no trailing space
}

#[test]
fn queue_drop_index_conversion() {
    // 1-based to 0-based conversion via saturating_sub
    assert_eq!(1_usize.saturating_sub(1), 0);
    assert_eq!(5_usize.saturating_sub(1), 4);
    // Edge case: 0 stays at 0 (saturating)
    assert_eq!(0_usize.saturating_sub(1), 0);
}

#[test]
fn queue_list_preview_truncation() {
    let short = "Short message";
    let preview = preview_with_ellipsis(short, QUEUE_LIST_PREVIEW_BYTES);
    assert_eq!(preview, "Short message");

    let long = "x".repeat(200);
    let preview = preview_with_ellipsis(&long, QUEUE_LIST_PREVIEW_BYTES);
    assert!(preview.len() <= QUEUE_LIST_PREVIEW_BYTES + 3);
    assert!(preview.ends_with("..."));

    let emoji_str = "Hello 🦊 world! This is a test with emoji 🌸 and more text here...";
    let preview = preview_with_ellipsis(emoji_str, QUEUE_LIST_PREVIEW_BYTES);
    assert!(preview.len() <= QUEUE_LIST_PREVIEW_BYTES + 3);
}

#[test]
fn queue_drop_preview_truncation() {
    let short = "Short task";
    let preview = preview_with_ellipsis(short, QUEUE_DROP_PREVIEW_BYTES);
    assert_eq!(preview, "Short task");

    let long = "y".repeat(120);
    let preview = preview_with_ellipsis(&long, QUEUE_DROP_PREVIEW_BYTES);
    assert!(preview.len() <= QUEUE_DROP_PREVIEW_BYTES + 3);
    assert!(preview.ends_with("..."));

    let emoji_str = "🦊🌸🌿❄️🥀 abcdefghij 🦊🌸🌿❄️🥀";
    let preview = preview_with_ellipsis(emoji_str, QUEUE_DROP_PREVIEW_BYTES);
    assert!(preview.len() <= QUEUE_DROP_PREVIEW_BYTES + 3);
}

#[test]
fn coalesces_interactive_queue_bursts_into_one_message() {
    let start = Instant::now();
    let messages = vec![
        PendingMessage::new("line one", PendingMessageOrigin::InteractiveQueue, start),
        PendingMessage::new(
            "line two",
            PendingMessageOrigin::InteractiveQueue,
            start + Duration::from_millis(25),
        ),
        PendingMessage::new(
            "manual follow-up",
            PendingMessageOrigin::ManualQueue,
            start + Duration::from_millis(30),
        ),
    ];

    let coalesced = coalesce_pending_messages(messages);
    assert_eq!(coalesced.len(), 2);
    assert_eq!(coalesced[0].content, "line one\nline two");
    assert_eq!(coalesced[1].content, "manual follow-up");
}

#[test]
fn queue_vecdeque_operations() {
    use std::collections::VecDeque;

    let now = Instant::now();
    let mut queue: VecDeque<PendingMessage> = VecDeque::new();

    queue.push_back(PendingMessage::new(
        "task one",
        PendingMessageOrigin::ManualQueue,
        now,
    ));
    queue.push_back(PendingMessage::new(
        "task two",
        PendingMessageOrigin::ManualQueue,
        now,
    ));
    queue.push_back(PendingMessage::new(
        "task three",
        PendingMessageOrigin::ManualQueue,
        now,
    ));
    assert_eq!(queue.len(), 3);

    let items: Vec<(usize, &PendingMessage)> = queue.iter().enumerate().collect();
    assert_eq!(items.len(), 3);
    assert_eq!(items[0].0, 0);
    assert_eq!(items[0].1.content, "task one");

    let removed = queue.remove(1).unwrap();
    assert_eq!(removed.content, "task two");
    assert_eq!(queue.len(), 2);
    assert_eq!(queue[0].content, "task one");
    assert_eq!(queue[1].content, "task three");

    // Clear
    let count = queue.len();
    queue.clear();
    assert_eq!(count, 2);
    assert!(queue.is_empty());
}

// ── ESC listener pause/unpause tests ──

#[tokio::test]
async fn esc_listener_stops_cleanly() {
    let cancel = Arc::new(AtomicBool::new(false));
    let paused = Arc::new(AtomicBool::new(false));
    let ack = Arc::new(AtomicBool::new(false));
    let guard = spawn_esc_listener(cancel, paused, ack);
    // Should stop without hanging
    guard.stop().await;
}

#[tokio::test]
async fn esc_listener_stops_when_cancelled() {
    let cancel = Arc::new(AtomicBool::new(false));
    let paused = Arc::new(AtomicBool::new(false));
    let ack = Arc::new(AtomicBool::new(false));
    let guard = spawn_esc_listener(Arc::clone(&cancel), paused, ack);
    cancel.store(true, std::sync::atomic::Ordering::Relaxed);
    guard.stop().await;
}

#[tokio::test]
async fn esc_listener_pauses_and_resumes() {
    use std::sync::atomic::Ordering;
    let cancel = Arc::new(AtomicBool::new(false));
    let paused = Arc::new(AtomicBool::new(false));
    let ack = Arc::new(AtomicBool::new(false));
    let guard = spawn_esc_listener(Arc::clone(&cancel), Arc::clone(&paused), Arc::clone(&ack));

    // Pause — the listener should yield raw mode
    paused.store(true, Ordering::Release);
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;
    assert!(ack.load(Ordering::Acquire));

    // Unpause — the listener should re-enter raw mode
    paused.store(false, Ordering::Release);
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;
    assert!(!ack.load(Ordering::Acquire));

    // Clean stop
    guard.stop().await;
}

#[tokio::test]
async fn esc_listener_stops_while_paused() {
    use std::sync::atomic::Ordering;
    let cancel = Arc::new(AtomicBool::new(false));
    let paused = Arc::new(AtomicBool::new(false));
    let ack = Arc::new(AtomicBool::new(false));
    let guard = spawn_esc_listener(Arc::clone(&cancel), Arc::clone(&paused), Arc::clone(&ack));

    // Pause then immediately stop — must not hang
    paused.store(true, Ordering::Release);
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    assert!(ack.load(Ordering::Acquire));
    guard.stop().await;
}

#[tokio::test]
async fn esc_listener_cancel_while_paused() {
    use std::sync::atomic::Ordering;
    let cancel = Arc::new(AtomicBool::new(false));
    let paused = Arc::new(AtomicBool::new(false));
    let ack = Arc::new(AtomicBool::new(false));
    let guard = spawn_esc_listener(Arc::clone(&cancel), Arc::clone(&paused), Arc::clone(&ack));

    paused.store(true, Ordering::Release);
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    assert!(ack.load(Ordering::Acquire));
    cancel.store(true, Ordering::Relaxed);
    guard.stop().await;
}