selfware 0.6.2

Your personal AI workshop — software you own, software that lasts
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use super::*;
use crate::agent::progress::ProgressEvent;
use crate::observability::dashboard::TokenUsage;
use serde_json::Value;

// ── headless_mode_block_reason ───────────────────────────────────────

#[test]
fn headless_block_reason_normal_mode_without_tty_is_blocked() {
    let reason = headless_mode_block_reason(ExecutionMode::Normal, false)
        .expect("Normal mode + non-TTY stdin must be blocked");
    assert!(
        reason.contains("-m yolo") && reason.contains("-m auto-edit"),
        "message must name the fix, got: {}",
        reason
    );
    assert!(
        reason.contains("stdin is not a terminal"),
        "message must name the real cause, got: {}",
        reason
    );
}

#[test]
fn headless_block_reason_normal_mode_with_tty_is_allowed() {
    // Interactive terminal: the confirmation prompt can be answered.
    assert!(headless_mode_block_reason(ExecutionMode::Normal, true).is_none());
}

#[test]
fn headless_block_reason_autonomous_modes_allowed_without_tty() {
    assert!(headless_mode_block_reason(ExecutionMode::Yolo, false).is_none());
    assert!(headless_mode_block_reason(ExecutionMode::AutoEdit, false).is_none());
    assert!(headless_mode_block_reason(ExecutionMode::Daemon, false).is_none());
}

// ── SessionResult serialization ──────────────────────────────────────

#[test]
fn test_session_result_round_trip() {
    let result = SessionResult {
        session_id: "test-session-123".to_string(),
        exit_status: 0,
        stop_reason: "completed".to_string(),
        num_turns: 5,
        patch_bytes: 1024,
        patch_lines: 42,
        usage: TokenUsage::new(1000, 500),
        model: "test-model".to_string(),
        duration_ms: 30000,
        failure_mode: None,
        artifact_dir: Some(PathBuf::from("/tmp/artifacts")),
    };
    let json = serde_json::to_string(&result).unwrap();
    let de: SessionResult = serde_json::from_str(&json).unwrap();
    assert_eq!(de.session_id, "test-session-123");
    assert_eq!(de.exit_status, 0);
    assert_eq!(de.stop_reason, "completed");
    assert_eq!(de.num_turns, 5);
    assert_eq!(de.patch_bytes, 1024);
    assert_eq!(de.patch_lines, 42);
    assert_eq!(de.usage.input, 1000);
    assert_eq!(de.usage.output, 500);
    assert_eq!(de.usage.total, 1500);
    assert_eq!(de.model, "test-model");
    assert_eq!(de.duration_ms, 30000);
    assert!(de.failure_mode.is_none());
    assert_eq!(de.artifact_dir, Some(PathBuf::from("/tmp/artifacts")));
}

#[test]
fn test_session_result_with_failure_mode() {
    let result = SessionResult {
        session_id: "fail-session".to_string(),
        exit_status: 1,
        stop_reason: "error".to_string(),
        num_turns: 3,
        patch_bytes: 0,
        patch_lines: 0,
        usage: TokenUsage::default(),
        model: "model-x".to_string(),
        duration_ms: 5000,
        failure_mode: Some("timeout".to_string()),
        artifact_dir: None,
    };
    let json = serde_json::to_string(&result).unwrap();
    let de: SessionResult = serde_json::from_str(&json).unwrap();
    assert_eq!(de.failure_mode, Some("timeout".to_string()));
    assert!(de.artifact_dir.is_none());
    assert_eq!(de.usage.total, 0);
    assert_eq!(de.exit_status, 1);
}

#[test]
fn test_session_result_json_fields() {
    let result = SessionResult {
        session_id: "s1".to_string(),
        exit_status: 2,
        stop_reason: "stopped".to_string(),
        num_turns: 10,
        patch_bytes: 2048,
        patch_lines: 88,
        usage: TokenUsage::new(100, 200),
        model: "m1".to_string(),
        duration_ms: 60000,
        failure_mode: Some("loop_guard".to_string()),
        artifact_dir: Some(PathBuf::from("/out")),
    };
    let json = serde_json::to_string(&result).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["session_id"], "s1");
    assert_eq!(v["exit_status"], 2);
    assert_eq!(v["stop_reason"], "stopped");
    assert_eq!(v["num_turns"], 10);
    assert_eq!(v["patch_bytes"], 2048);
    assert_eq!(v["patch_lines"], 88);
    assert_eq!(v["model"], "m1");
    assert_eq!(v["duration_ms"], 60000);
    assert_eq!(v["usage"]["input"], 100);
    assert_eq!(v["usage"]["output"], 200);
    assert_eq!(v["usage"]["total"], 300);
    assert_eq!(v["failure_mode"], "loop_guard");
    assert_eq!(v["artifact_dir"], "/out");
}

// ── HeadlessEvent constructors ───────────────────────────────────────

#[test]
fn test_step_started_constructor() {
    let ev = HeadlessEvent::step_started(3, "gpt-4".to_string());
    assert_eq!(ev.event, "step_started");
    assert_eq!(ev.step, Some(3));
    assert_eq!(ev.model.as_deref(), Some("gpt-4"));
    assert!(ev.tool.is_none());
    assert!(ev.args.is_none());
    assert!(ev.ok.is_none());
    assert!(ev.outcome.is_none());
    assert!(ev.reason.is_none());
}

#[test]
fn test_tool_call_started_constructor() {
    let ev = HeadlessEvent::tool_call_started("file_read".to_string(), "path=foo.rs".to_string());
    assert_eq!(ev.event, "tool_call_started");
    assert_eq!(ev.tool.as_deref(), Some("file_read"));
    assert_eq!(ev.args.as_deref(), Some("path=foo.rs"));
    assert!(ev.step.is_none());
    assert!(ev.model.is_none());
    assert!(ev.ok.is_none());
    assert!(ev.outcome.is_none());
    assert!(ev.reason.is_none());
}

#[test]
fn test_tool_call_completed_constructor_true() {
    let ev = HeadlessEvent::tool_call_completed("file_write".to_string(), true);
    assert_eq!(ev.event, "tool_call_completed");
    assert_eq!(ev.tool.as_deref(), Some("file_write"));
    assert_eq!(ev.ok, Some(true));
    assert!(ev.args.is_none());
    assert!(ev.step.is_none());
    assert!(ev.model.is_none());
    assert!(ev.outcome.is_none());
    assert!(ev.reason.is_none());
}

#[test]
fn test_tool_call_completed_constructor_false() {
    let ev = HeadlessEvent::tool_call_completed("shell_exec".to_string(), false);
    assert_eq!(ev.ok, Some(false));
    assert_eq!(ev.tool.as_deref(), Some("shell_exec"));
}

#[test]
fn jsonl_emits_llm_events_with_tokens_and_finish_reason() {
    // stream-json previously dropped the LLM events entirely.
    let req = JsonlProgressEmitter::event_json_line(ProgressEvent::LlmRequestSent { tokens: 1234 })
        .expect("llm_request_sent must be emitted");
    let req: Value = serde_json::from_str(&req).unwrap();
    assert_eq!(req["event"], "llm_request_sent");
    assert_eq!(req["prompt_tokens"], 1234);

    let resp = JsonlProgressEmitter::event_json_line(ProgressEvent::LlmResponseReceived {
        finish_reason: "stop".to_string(),
        completion_tokens: 56,
    })
    .expect("llm_response_received must be emitted");
    let resp: Value = serde_json::from_str(&resp).unwrap();
    assert_eq!(resp["event"], "llm_response_received");
    assert_eq!(resp["finish_reason"], "stop");
    assert_eq!(resp["completion_tokens"], 56);
}

#[test]
fn test_step_completed_constructor() {
    let ev = HeadlessEvent::step_completed(7);
    assert_eq!(ev.event, "step_completed");
    assert_eq!(ev.step, Some(7));
    assert!(ev.model.is_none());
    assert!(ev.tool.is_none());
    assert!(ev.args.is_none());
    assert!(ev.ok.is_none());
    assert!(ev.outcome.is_none());
    assert!(ev.reason.is_none());
}

#[test]
fn test_task_completed_constructor() {
    let ev = HeadlessEvent::task_completed("success".to_string());
    assert_eq!(ev.event, "task_completed");
    assert_eq!(ev.outcome.as_deref(), Some("success"));
    assert!(ev.reason.is_none());
    assert!(ev.step.is_none());
    assert!(ev.tool.is_none());
}

#[test]
fn test_task_failed_constructor() {
    let ev = HeadlessEvent::task_failed("compilation error".to_string());
    assert_eq!(ev.event, "task_failed");
    assert_eq!(ev.reason.as_deref(), Some("compilation error"));
    assert!(ev.outcome.is_none());
    assert!(ev.tool.is_none());
    assert!(ev.step.is_none());
}

// ── HeadlessEvent serialization ──────────────────────────────────────

#[test]
fn test_step_started_serialization() {
    let ev = HeadlessEvent::step_started(1, "model-a".to_string());
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "step_started");
    assert_eq!(v["step"], 1);
    assert_eq!(v["model"], "model-a");
}

#[test]
fn test_tool_call_started_serialization() {
    let ev = HeadlessEvent::tool_call_started("cargo_check".to_string(), "".to_string());
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "tool_call_started");
    assert_eq!(v["tool"], "cargo_check");
    assert_eq!(v["args"], "");
}

#[test]
fn test_tool_call_completed_serialization() {
    let ev = HeadlessEvent::tool_call_completed("file_edit".to_string(), false);
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "tool_call_completed");
    assert_eq!(v["tool"], "file_edit");
    assert_eq!(v["ok"], false);
}

#[test]
fn test_step_completed_serialization() {
    let ev = HeadlessEvent::step_completed(42);
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "step_completed");
    assert_eq!(v["step"], 42);
}

#[test]
fn test_task_completed_serialization() {
    let ev = HeadlessEvent::task_completed("all tests passed".to_string());
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "task_completed");
    assert_eq!(v["outcome"], "all tests passed");
}

#[test]
fn test_task_failed_serialization() {
    let ev = HeadlessEvent::task_failed("out of budget".to_string());
    let json = serde_json::to_string(&ev).unwrap();
    let v: Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["event"], "task_failed");
    assert_eq!(v["reason"], "out of budget");
}

#[test]
fn test_skip_serializing_none_fields() {
    // step_completed only has event and step set — all other fields are
    // None and should be omitted from JSON via skip_serializing_if.
    let ev = HeadlessEvent::step_completed(1);
    let json = serde_json::to_string(&ev).unwrap();
    assert!(!json.contains("\"tool\""));
    assert!(!json.contains("\"model\""));
    assert!(!json.contains("\"args\""));
    assert!(!json.contains("\"ok\""));
    assert!(!json.contains("\"outcome\""));
    assert!(!json.contains("\"reason\""));
}

#[test]
fn test_skip_serializing_none_fields_task_failed() {
    // task_failed has event and reason set — step/model/tool/args/ok/outcome
    // should all be skipped.
    let ev = HeadlessEvent::task_failed("err".to_string());
    let json = serde_json::to_string(&ev).unwrap();
    assert!(!json.contains("\"step\""));
    assert!(!json.contains("\"model\""));
    assert!(!json.contains("\"tool\""));
    assert!(!json.contains("\"args\""));
    assert!(!json.contains("\"ok\""));
    assert!(!json.contains("\"outcome\""));
    assert!(json.contains("\"reason\""));
}

// ── emit_event / emit_result (smoke tests — verify no panic) ──────────

#[test]
fn test_emit_event_does_not_panic() {
    let ev = HeadlessEvent::step_started(1, "test".to_string());
    emit_event(&ev);
}

#[test]
fn test_emit_result_does_not_panic() {
    let result = SessionResult {
        session_id: "emit-test".to_string(),
        exit_status: 0,
        stop_reason: "done".to_string(),
        num_turns: 1,
        patch_bytes: 0,
        patch_lines: 0,
        usage: TokenUsage::default(),
        model: "test".to_string(),
        duration_ms: 0,
        failure_mode: None,
        artifact_dir: None,
    };
    emit_result(&result);
}

// ── JsonlProgressEmitter ─────────────────────────────────────────────

#[test]
fn test_jsonl_emitter_new_and_default() {
    let _emitter = JsonlProgressEmitter::new();
    let _default = JsonlProgressEmitter::default();
}

#[test]
fn test_jsonl_emitter_step_started() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::StepStarted {
        step: 1,
        model: "test-model".to_string(),
        tools_available: 5,
    });
}

#[test]
fn test_jsonl_emitter_tool_call_started() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::ToolCallStarted {
        tool: "file_read".to_string(),
        args_short: "path=test.rs".to_string(),
    });
}

#[test]
fn test_jsonl_emitter_tool_call_completed() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::ToolCallCompleted {
        tool: "file_read".to_string(),
        ok: true,
        elapsed_ms: 42,
    });
}

#[test]
fn test_jsonl_emitter_step_completed() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::StepCompleted {
        step: 3,
        mutating_tools_so_far: 2,
    });
}

#[test]
fn test_jsonl_emitter_task_completed() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::TaskCompleted {
        outcome: "success".to_string(),
    });
}

#[test]
fn test_jsonl_emitter_task_failed() {
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::TaskFailed {
        reason: "something went wrong".to_string(),
    });
}

#[test]
fn test_jsonl_emitter_ignores_unmapped_events() {
    // Events that don't map to a HeadlessEvent variant should be silently
    // dropped (the `_ => None` arm).
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::LlmRequestSent { tokens: 100 });
    emitter.emit(ProgressEvent::LlmResponseReceived {
        finish_reason: "stop".to_string(),
        completion_tokens: 50,
    });
    emitter.emit(ProgressEvent::GuardFired {
        kind: "progress".to_string(),
        count: 1,
    });
    emitter.emit(ProgressEvent::SubprocessStarted {
        name: "cargo".to_string(),
    });
    emitter.emit(ProgressEvent::SubprocessCompleted {
        name: "cargo".to_string(),
        exit: 0,
        elapsed_ms: 100,
    });
}

#[test]
fn test_jsonl_emitter_simulated_agent_loop() {
    // Emit a realistic sequence of events as a real agent loop would.
    let emitter = JsonlProgressEmitter::new();
    emitter.emit(ProgressEvent::StepStarted {
        step: 1,
        model: "m".to_string(),
        tools_available: 3,
    });
    emitter.emit(ProgressEvent::ToolCallStarted {
        tool: "file_read".to_string(),
        args_short: "path=foo".to_string(),
    });
    emitter.emit(ProgressEvent::ToolCallCompleted {
        tool: "file_read".to_string(),
        ok: true,
        elapsed_ms: 10,
    });
    emitter.emit(ProgressEvent::StepCompleted {
        step: 1,
        mutating_tools_so_far: 0,
    });
    emitter.emit(ProgressEvent::TaskCompleted {
        outcome: "done".to_string(),
    });
}

// ── capture_patch ────────────────────────────────────────────────────

fn git_available() -> bool {
    std::process::Command::new("git")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok()
}

/// Helper: create a temp git repo with an initial commit and return its path.
fn make_temp_git_repo(prefix: &str) -> Option<std::path::PathBuf> {
    if !git_available() {
        return None;
    }

    let tmp_dir = std::env::temp_dir().join(format!(
        "{}_{}_{}",
        prefix,
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&tmp_dir).unwrap();

    // Init
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&tmp_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();

    // Configure user (required for commit)
    for (key, val) in &[("user.email", "t@t.com"), ("user.name", "T")] {
        std::process::Command::new("git")
            .args(["config", key, val])
            .current_dir(&tmp_dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();
    }

    // Initial file + commit
    std::fs::write(tmp_dir.join("file.txt"), "line1\nline2\n").unwrap();
    std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(&tmp_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
    std::process::Command::new("git")
        .args(["commit", "-m", "initial"])
        .current_dir(&tmp_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();

    Some(tmp_dir)
}

struct TempDirCleanup(std::path::PathBuf);
impl Drop for TempDirCleanup {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

#[test]
fn test_capture_patch_detects_modified_and_new_files() {
    let tmp_dir = match make_temp_git_repo("selfware_cp_mod") {
        Some(d) => d,
        None => {
            eprintln!("Skipping: git not available");
            return;
        }
    };
    let _cleanup = TempDirCleanup(tmp_dir.clone());
    let _guard = crate::test_support::CwdGuard::hold();
    let original_dir = std::env::current_dir().unwrap();

    // Modify existing file
    std::fs::write(tmp_dir.join("file.txt"), "line1\nline2\nline3\n").unwrap();
    // Add new file
    std::fs::write(tmp_dir.join("new.txt"), "new content\n").unwrap();

    std::env::set_current_dir(&tmp_dir).unwrap();
    let result = capture_patch();
    std::env::set_current_dir(&original_dir).unwrap();

    assert!(result.is_ok(), "capture_patch failed: {:?}", result.err());
    let patch = result.unwrap();
    assert!(
        patch.contains("line3"),
        "patch should contain new line3, got: {}",
        patch
    );
    assert!(
        patch.contains("new content"),
        "patch should contain new file, got: {}",
        patch
    );
}

#[test]
fn test_capture_patch_no_phantom_deletion_for_tracked_ignored_files() {
    // Regression: a file that is tracked in HEAD but matches .gitignore must
    // NOT be reported as deleted when it is unchanged. Before seeding the
    // temp index from HEAD, `git add -A` skipped it (ignored) and the diff
    // showed a spurious deletion — a huge phantom patch with zero real edits.
    let tmp_dir = match make_temp_git_repo("selfware_cp_phantom") {
        Some(d) => d,
        None => {
            eprintln!("Skipping: git not available");
            return;
        }
    };
    let _cleanup = TempDirCleanup(tmp_dir.clone());
    let _guard = crate::test_support::CwdGuard::hold();
    let original_dir = std::env::current_dir().unwrap();

    // Two commits, in order, so the file ends up tracked-BUT-ignored:
    //   1) commit data.gen while it is still un-ignored (so it is tracked),
    //   2) THEN add a .gitignore that ignores it.
    // (Writing both at once and committing would let `git add -A` skip the
    // already-ignored file, so it would never be tracked — not the case we
    // want to exercise.)
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .args(args)
            .current_dir(&tmp_dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();
    };
    std::fs::write(tmp_dir.join("data.gen"), "generated payload\n").unwrap();
    git(&["add", "-A"]);
    git(&["commit", "-m", "add data.gen (tracked)"]);
    std::fs::write(tmp_dir.join(".gitignore"), "data.gen\n").unwrap();
    git(&["add", "-A"]);
    git(&["commit", "-m", "ignore data.gen (now tracked-but-ignored)"]);

    // No working-tree changes at all → the patch must be empty, and in
    // particular must not mention data.gen (as a deletion or otherwise).
    std::env::set_current_dir(&tmp_dir).unwrap();
    let result = capture_patch();
    std::env::set_current_dir(&original_dir).unwrap();

    assert!(result.is_ok(), "capture_patch failed: {:?}", result.err());
    let patch = result.unwrap();
    assert!(
        !patch.contains("data.gen"),
        "tracked-but-ignored file reported as a phantom change:\n{}",
        patch
    );
    assert!(
        patch.trim().is_empty(),
        "no real edits, so the patch must be empty; got:\n{}",
        patch
    );
}

#[test]
fn test_capture_patch_empty_when_no_changes() {
    let tmp_dir = match make_temp_git_repo("selfware_cp_empty") {
        Some(d) => d,
        None => {
            eprintln!("Skipping: git not available");
            return;
        }
    };
    let _cleanup = TempDirCleanup(tmp_dir.clone());
    let _guard = crate::test_support::CwdGuard::hold();
    let original_dir = std::env::current_dir().unwrap();

    std::env::set_current_dir(&tmp_dir).unwrap();
    let result = capture_patch();
    std::env::set_current_dir(&original_dir).unwrap();

    assert!(result.is_ok(), "capture_patch failed: {:?}", result.err());
    let patch = result.unwrap();
    assert!(
        patch.trim().is_empty(),
        "patch should be empty with no changes, got: {:?}",
        patch
    );
}

#[test]
fn test_capture_patch_excludes_internal_dirs() {
    let tmp_dir = match make_temp_git_repo("selfware_cp_excl") {
        Some(d) => d,
        None => {
            eprintln!("Skipping: git not available");
            return;
        }
    };
    let _cleanup = TempDirCleanup(tmp_dir.clone());
    let _guard = crate::test_support::CwdGuard::hold();
    let original_dir = std::env::current_dir().unwrap();

    // Modify main file (should appear)
    std::fs::write(tmp_dir.join("file.txt"), "line1\nline2\nCHANGED\n").unwrap();

    // Create files in excluded directories
    std::fs::create_dir_all(tmp_dir.join(".selfware")).unwrap();
    std::fs::write(tmp_dir.join(".selfware/cache.txt"), "secret cache\n").unwrap();

    std::env::set_current_dir(&tmp_dir).unwrap();
    let result = capture_patch();
    std::env::set_current_dir(&original_dir).unwrap();

    assert!(result.is_ok(), "capture_patch failed: {:?}", result.err());
    let patch = result.unwrap();
    assert!(
        patch.contains("CHANGED"),
        "patch should contain real change, got: {}",
        patch
    );
    assert!(
        !patch.contains("secret cache"),
        "patch should exclude .selfware/, got: {}",
        patch
    );
}

#[test]
fn test_capture_patch_does_not_stage_user_files() {
    let tmp_dir = match make_temp_git_repo("selfware_cp_nostage") {
        Some(d) => d,
        None => {
            eprintln!("Skipping: git not available");
            return;
        }
    };
    let _cleanup = TempDirCleanup(tmp_dir.clone());
    let _guard = crate::test_support::CwdGuard::hold();
    let original_dir = std::env::current_dir().unwrap();

    // Make an unstaged modification to the tracked file.
    std::fs::write(tmp_dir.join("file.txt"), "line1\nline2\nUNSTAGED\n").unwrap();

    // Snapshot the real index state BEFORE capture_patch (git diff --cached
    // against the real index should be empty since nothing is staged yet).
    std::env::set_current_dir(&tmp_dir).unwrap();
    let staged_before = std::process::Command::new("git")
        .args(["diff", "--cached", "HEAD"])
        .output()
        .unwrap();
    std::env::set_current_dir(&original_dir).unwrap();
    let staged_before = String::from_utf8_lossy(&staged_before.stdout).to_string();

    // Run capture_patch (should NOT touch the real index).
    std::env::set_current_dir(&tmp_dir).unwrap();
    let result = capture_patch();
    std::env::set_current_dir(&original_dir).unwrap();

    assert!(result.is_ok(), "capture_patch failed: {:?}", result.err());
    let patch = result.unwrap();
    assert!(
        patch.contains("UNSTAGED"),
        "patch should contain the unstaged change, got: {}",
        patch
    );

    // Snapshot the real index state AFTER capture_patch and compare. The
    // real `.git/index` must be untouched, so `git diff --cached` must be
    // identical to the before snapshot.
    std::env::set_current_dir(&tmp_dir).unwrap();
    let staged_after = std::process::Command::new("git")
        .args(["diff", "--cached", "HEAD"])
        .output()
        .unwrap();
    std::env::set_current_dir(&original_dir).unwrap();
    let staged_after = String::from_utf8_lossy(&staged_after.stdout).to_string();

    assert_eq!(
        staged_before, staged_after,
        "capture_patch must not mutate the user's real git index (staged state changed)"
    );
}