cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! Git commit operations.
//!
//! This module provides functions for creating, managing, and querying Git commits.

use super::basic::run_git;
use super::status_policy::{
    read_only_status_argv, CHANGE_MONITOR_STATUS_ARGS, PORCELAIN_STATUS_ARGS,
};
use crate::events::CommitOutputStream;
use crate::vcs::commands::{run_vcs_command_captured, run_vcs_command_streamed, VcsCommandOutput};
use crate::vcs::{CommitRejection, VcsBackend, VcsError, VcsResult, VerifiedCommitOutcome};
use std::path::Path;
use tracing::debug;

/// Presentation sink for streamed verified-commit output.
///
/// The sink observes lines only. Everything classification depends on — command
/// line, exit code, complete raw stdout and stderr — travels in the returned
/// [`VcsCommandOutput`], so a sink can never influence whether a commit is
/// treated as rejected, retryable, or fatal.
pub type CommitOutputSink<'a> = &'a (dyn Fn(CommitOutputStream, &str) + Send + Sync);

/// Exit status `git commit` reports when the repository itself rejects the
/// commit, most importantly a non-zero `pre-commit` or `commit-msg` hook.
///
/// Fatal Git failures (bad repository, unreadable objects, usage errors) exit
/// with 128, and a signal-killed process reports no code at all, so matching
/// this exact status keeps recovery eligibility structural instead of relying
/// on the rendered error text.
pub const GIT_REPOSITORY_REJECTION_EXIT_CODE: i32 = 1;

/// Which finalization path a verified commit takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifiedCommitMode {
    /// The worktree had changes, so they were staged and committed normally.
    AddAndCommit,
    /// A WIP snapshot already left the worktree clean, so HEAD is amended.
    Amend,
}

/// Build the argument list for the verified (hook-enabled) commit.
///
/// Kept separate from execution so the "final commits never bypass hooks" rule
/// is checkable without spawning Git.
///
/// The amend path adds `--allow-empty` because the WIP snapshot it rewrites may
/// itself be empty (snapshots are created with `--allow-empty`), and the final
/// commit's job is to name the completed apply rather than to introduce
/// content. Without it Git exits 1 for "would make it empty", which is
/// indistinguishable from a hook rejection by exit code and would spend the
/// whole repair budget on a failure no agent can fix.
pub fn verified_commit_args(mode: VerifiedCommitMode, message: &str) -> Vec<String> {
    let mut args = vec!["commit".to_string()];
    if mode == VerifiedCommitMode::Amend {
        args.push("--amend".to_string());
        args.push("--allow-empty".to_string());
    }
    args.push("-m".to_string());
    args.push(message.to_string());
    args
}

/// Classify the result of a verified commit process that actually ran.
///
/// Only an exact [`GIT_REPOSITORY_REJECTION_EXIT_CODE`] becomes
/// [`VerifiedCommitOutcome::RepositoryRejected`]. Every other failure — fatal
/// Git status, signal death — stays a terminal [`VcsError`]. Classification
/// reads the preserved exit code only; it never inspects rendered error text.
pub fn classify_verified_commit_output(
    output: VcsCommandOutput,
    working_dir: &Path,
) -> VcsResult<VerifiedCommitOutcome> {
    if output.success {
        return Ok(VerifiedCommitOutcome::Committed);
    }

    if output.exit_code == Some(GIT_REPOSITORY_REJECTION_EXIT_CODE) {
        debug!(
            "Verified commit rejected by repository verification: {}",
            output.command
        );
        return Ok(VerifiedCommitOutcome::RepositoryRejected(CommitRejection {
            command: output.command,
            exit_code: output.exit_code,
            stdout: output.stdout,
            stderr: output.stderr,
        }));
    }

    Err(VcsError::Command {
        backend: VcsBackend::Git,
        message: format!("{} failed: {}", output.command, output.stderr),
        command: Some(output.command),
        working_dir: Some(working_dir.to_path_buf()),
        stderr: Some(output.stderr),
        stdout: Some(output.stdout),
    })
}

/// Run a verified commit and classify its result structurally.
///
/// A spawn failure propagates as a terminal [`VcsError`] before any
/// classification happens.
async fn run_verified_commit<P: AsRef<Path>>(
    cwd: P,
    args: &[String],
    sink: Option<CommitOutputSink<'_>>,
) -> VcsResult<VerifiedCommitOutcome> {
    debug_assert!(
        !args.iter().any(|arg| arg == "--no-verify"),
        "verified commits must run repository hooks"
    );

    let arg_refs = args.iter().map(String::as_str).collect::<Vec<_>>();
    // Both paths produce the same `VcsCommandOutput` contract, so the
    // classification below is identical whether or not an operator is watching.
    let output = match sink {
        Some(sink) => {
            run_vcs_command_streamed(
                "git",
                &arg_refs,
                cwd.as_ref(),
                VcsBackend::Git,
                |stream, line| sink(stream, line),
            )
            .await?
        }
        None => run_vcs_command_captured("git", &arg_refs, cwd.as_ref(), VcsBackend::Git).await?,
    };

    classify_verified_commit_output(output, cwd.as_ref())
}

/// Create the verified (hook-enabled) commit for a workspace.
///
/// Setup steps (`status`, `add`, staged-snapshot validation) propagate as
/// terminal errors; only the commit itself can produce a repository rejection.
pub async fn create_verified_commit<P: AsRef<Path>>(
    cwd: P,
    message: &str,
) -> VcsResult<VerifiedCommitOutcome> {
    create_verified_commit_streamed(cwd, message, None).await
}

/// `create_verified_commit` with an optional presentation sink.
///
/// A long pre-commit hook is otherwise invisible until the process exits, which
/// is exactly the window an operator most needs to see. Streaming changes when
/// the output is observed, never what it is: the returned outcome is classified
/// from the same preserved command, exit status, and raw streams either way.
pub async fn create_verified_commit_streamed<P: AsRef<Path>>(
    cwd: P,
    message: &str,
    sink: Option<CommitOutputSink<'_>>,
) -> VcsResult<VerifiedCommitOutcome> {
    let mode = if has_changes_to_commit(&cwd).await? {
        run_git(&["add", "-A"], &cwd).await?;
        validate_staged_snapshot(&cwd).await?;
        VerifiedCommitMode::AddAndCommit
    } else {
        VerifiedCommitMode::Amend
    };

    run_verified_commit(&cwd, &verified_commit_args(mode, message), sink).await
}

fn staged_snapshot_anomaly<'a>(paths: impl Iterator<Item = &'a str>) -> Option<String> {
    const MAX_STAGED_FILES: usize = 5_000;

    let mut by_top_level = std::collections::BTreeMap::<&str, usize>::new();
    let mut total = 0;
    for path in paths {
        total += 1;
        *by_top_level
            .entry(path.split('/').next().unwrap_or(path))
            .or_default() += 1;
    }
    if let Some((directory, count)) = by_top_level
        .iter()
        .find(|(directory, _)| directory.starts_with(".agent-target"))
    {
        return Some(format!("forbidden temporary path {directory}: {count}"));
    }
    if total <= MAX_STAGED_FILES {
        return None;
    }

    let summary = by_top_level
        .iter()
        .take(20)
        .map(|(directory, count)| format!("{directory}: {count}"))
        .collect::<Vec<_>>()
        .join(", ");
    Some(format!("{total} staged files ({summary})"))
}

pub async fn validate_staged_snapshot<P: AsRef<Path>>(cwd: P) -> VcsResult<()> {
    let cwd = cwd.as_ref();
    let output = run_git(
        &[
            "diff",
            "--cached",
            "--name-only",
            "--diff-filter=ACMR",
            "-z",
        ],
        cwd,
    )
    .await?;
    let paths = output
        .split('\0')
        .filter(|path| !path.is_empty())
        .collect::<Vec<_>>();
    let Some(summary) = staged_snapshot_anomaly(paths.iter().copied()) else {
        return Ok(());
    };

    let _ = run_git(&["reset"], cwd).await;
    Err(VcsError::git_command(format!(
        "Refusing suspicious snapshot ({summary}); staged changes were reset"
    )))
}

/// Create a WIP archive commit for a retry attempt.
pub async fn create_archive_wip_commit<P: AsRef<Path>>(
    cwd: P,
    change_id: &str,
    attempt: u32,
) -> VcsResult<()> {
    let message = format!("WIP(archive): {} (attempt#{})", change_id, attempt);
    run_git(&["add", "-A"], &cwd).await?;
    validate_staged_snapshot(&cwd).await?;
    run_git(&["commit", "--allow-empty", "-m", &message], cwd).await?;
    Ok(())
}

/// Squash all archive WIP commits into a final Archive commit.
pub async fn squash_archive_wip_commits<P: AsRef<Path>>(cwd: P, change_id: &str) -> VcsResult<()> {
    let wip_pattern = format!("WIP(archive): {}", change_id);
    let wip_commits = run_git(
        &[
            "rev-list",
            "--reverse",
            "--grep",
            &wip_pattern,
            "--fixed-strings",
            "HEAD",
        ],
        &cwd,
    )
    .await?;
    let first_wip = wip_commits
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .ok_or_else(|| {
            VcsError::git_command(format!("No archive WIP commits found for {}", change_id))
        })?;

    let parent_revision = run_git(&["rev-parse", &format!("{}^", first_wip)], &cwd).await?;
    let parent_revision = parent_revision.trim();

    run_git(&["reset", "--soft", parent_revision], &cwd).await?;
    validate_staged_snapshot(&cwd).await?;
    let archive_message = format!("Archive: {}", change_id);
    run_git(&["commit", "--allow-empty", "-m", &archive_message], cwd).await?;
    Ok(())
}

/// List change IDs from the HEAD commit tree.
///
/// Reads directories under `openspec/changes` in the HEAD tree and filters out
/// archive, hidden entries, and changes without proposal.md.
pub async fn list_changes_in_head<P: AsRef<Path>>(cwd: P) -> VcsResult<Vec<String>> {
    let cwd_ref = cwd.as_ref();

    let output = run_git(
        &["ls-tree", "-d", "--name-only", "HEAD:openspec/changes"],
        cwd_ref,
    )
    .await?;

    let mut change_ids: Vec<String> = Vec::new();

    for name in output.lines().map(str::trim) {
        if name.is_empty() || name == "archive" || name.starts_with('.') {
            continue;
        }

        // Check if proposal.md exists in HEAD for this change
        let proposal_path = format!("HEAD:openspec/changes/{}/proposal.md", name);
        match run_git(&["cat-file", "-e", &proposal_path], cwd_ref).await {
            Ok(_) => {
                // proposal.md exists, include this change
                change_ids.push(name.to_string());
            }
            Err(_) => {
                // proposal.md doesn't exist, skip this change
                debug!("Skipping change '{}' in HEAD - no proposal.md found", name);
            }
        }
    }

    change_ids.sort();
    Ok(change_ids)
}

/// Check if there are staged or unstaged changes to commit.
///
/// Read-only, so it runs under the shared optional-lock policy: see
/// [`crate::vcs::git::commands::status_policy`].
#[allow(dead_code)]
pub async fn has_changes_to_commit<P: AsRef<Path>>(cwd: P) -> VcsResult<bool> {
    let output = run_git(&read_only_status_argv(PORCELAIN_STATUS_ARGS), cwd).await?;
    Ok(!output.is_empty())
}

/// Argv of the read-oriented repository monitoring query.
///
/// Built from the shared read-only status policy, so the global
/// `--no-optional-locks` option always precedes the `status` subcommand and the
/// suppression stays child-command-local. See
/// [`crate::vcs::git::commands::status_policy`] for why both properties matter.
fn uncommitted_monitor_argv() -> Vec<&'static str> {
    read_only_status_argv(CHANGE_MONITOR_STATUS_ARGS)
}

/// List change IDs that have uncommitted or untracked files under `openspec/changes/<change_id>/`.
///
/// This function detects changes with:
/// - Staged changes (added, modified, deleted)
/// - Unstaged changes (modified, deleted)
/// - Untracked files
///
/// The query is read-oriented monitoring (TUI refresh, parallel startup, queue
/// filtering), so it reports a point-in-time observation and never persists an
/// optional index refresh. See [`uncommitted_monitor_argv`].
///
/// Returns a sorted vector of change IDs that have uncommitted modifications.
pub async fn list_changes_with_uncommitted_files<P: AsRef<Path>>(cwd: P) -> VcsResult<Vec<String>> {
    let cwd_ref = cwd.as_ref();

    // Get all files with uncommitted changes or untracked status
    // Use -u to show individual untracked files instead of just directories
    let output = run_git(&uncommitted_monitor_argv(), cwd_ref).await?;

    let mut change_ids: std::collections::HashSet<String> = std::collections::HashSet::new();

    for line in output.lines() {
        if line.trim().is_empty() {
            continue;
        }

        // Parse porcelain format path field.
        // Normal: "XY <path>" (2 status columns + separator)
        // Fallback: "Y <path>" for first line when run_git() trimmed a leading space.
        let bytes = line.as_bytes();
        let path_field = if bytes.len() >= 3 && bytes[2] == b' ' {
            &line[3..]
        } else if bytes.len() >= 2 && bytes[1] == b' ' {
            &line[2..]
        } else {
            continue;
        };

        // Handle rename format: "old/path -> new/path". Use destination path.
        let path = path_field
            .split_once(" -> ")
            .map(|(_, new_path)| new_path)
            .unwrap_or(path_field)
            .trim();

        // Check if path is under openspec/changes/<change_id>/
        if let Some(change_id) = extract_change_id_from_path(path) {
            change_ids.insert(change_id);
        }
    }

    let mut result: Vec<String> = change_ids.into_iter().collect();
    result.sort();
    Ok(result)
}

/// Extract change_id from a file path if it matches `openspec/changes/<change_id>/...`
///
/// Returns None if the path doesn't match the expected pattern or refers to the archive directory.
fn extract_change_id_from_path(path: &str) -> Option<String> {
    // Normalize path separators for cross-platform compatibility
    let normalized_path = path.replace('\\', "/");

    // Expected pattern: openspec/changes/<change_id>/...
    let prefix = "openspec/changes/";
    if !normalized_path.starts_with(prefix) {
        return None;
    }

    // Extract the part after "openspec/changes/"
    let remainder = &normalized_path[prefix.len()..];

    // Find the first path separator to get the change_id
    let change_id = if let Some(pos) = remainder.find('/') {
        &remainder[..pos]
    } else {
        // Path is exactly "openspec/changes/<change_id>" (no trailing slash)
        remainder
    };

    // Filter out special directories
    if change_id.is_empty() || change_id == "archive" || change_id.starts_with('.') {
        return None;
    }

    Some(change_id.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use tokio::process::Command;

    #[tokio::test]
    async fn test_list_changes_in_head_filters_special_dirs() {
        let temp_dir = TempDir::new().unwrap();

        debug!(
            module = module_path!(),
            "Executing git command: git init (cwd: {:?})",
            temp_dir.path()
        );
        let init_result = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        if init_result.is_err() {
            return;
        }

        debug!(
            module = module_path!(),
            "Executing git command: git config user.email test@example.com (cwd: {:?})",
            temp_dir.path()
        );
        let _ = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        debug!(
            module = module_path!(),
            "Executing git command: git config user.name Test User (cwd: {:?})",
            temp_dir.path()
        );
        let _ = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let base_dir = temp_dir.path().join("openspec/changes");
        std::fs::create_dir_all(base_dir.join("change-b")).unwrap();
        std::fs::create_dir_all(base_dir.join("change-a")).unwrap();
        std::fs::create_dir_all(base_dir.join("archive")).unwrap();
        std::fs::create_dir_all(base_dir.join(".hidden")).expect("create hidden dir");
        std::fs::write(base_dir.join("change-a").join("proposal.md"), "test").unwrap();
        std::fs::write(base_dir.join("change-b").join("proposal.md"), "test").unwrap();
        std::fs::write(base_dir.join("archive").join("proposal.md"), "test").unwrap();

        debug!(
            module = module_path!(),
            "Executing git command: git add . (cwd: {:?})",
            temp_dir.path()
        );
        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await;
        debug!(
            module = module_path!(),
            "Executing git command: git commit -m add changes (cwd: {:?})",
            temp_dir.path()
        );
        let _ = Command::new("git")
            .args(["commit", "-m", "add changes"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let changes = list_changes_in_head(temp_dir.path()).await.unwrap();
        assert_eq!(
            changes,
            vec!["change-a".to_string(), "change-b".to_string()]
        );
    }

    #[tokio::test]
    async fn test_list_changes_in_head_excludes_without_proposal() {
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repo
        let init_result = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        if init_result.is_err() {
            return; // Skip if git not available
        }

        let _ = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let base_dir = temp_dir.path().join("openspec/changes");

        // Create change-a WITH proposal.md
        std::fs::create_dir_all(base_dir.join("change-a")).unwrap();
        std::fs::write(base_dir.join("change-a").join("proposal.md"), "test").unwrap();
        std::fs::write(base_dir.join("change-a").join("tasks.md"), "- [ ] Task 1").unwrap();

        // Create change-b WITHOUT proposal.md (only tasks.md)
        std::fs::create_dir_all(base_dir.join("change-b")).unwrap();
        std::fs::write(base_dir.join("change-b").join("tasks.md"), "- [ ] Task 1").unwrap();

        // Create change-c WITH proposal.md
        std::fs::create_dir_all(base_dir.join("change-c")).unwrap();
        std::fs::write(base_dir.join("change-c").join("proposal.md"), "test").unwrap();

        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["commit", "-m", "add changes"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let changes = list_changes_in_head(temp_dir.path()).await.unwrap();

        // Should only include change-a and change-c (have proposal.md)
        // change-b should be excluded (no proposal.md)
        assert_eq!(
            changes,
            vec!["change-a".to_string(), "change-c".to_string()]
        );
    }

    #[tokio::test]
    async fn test_list_changes_with_uncommitted_files() {
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repo
        let init_result = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        if init_result.is_err() {
            return; // Skip if git not available
        }

        let _ = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let base_dir = temp_dir.path().join("openspec/changes");

        // Create change-a and commit it
        std::fs::create_dir_all(base_dir.join("change-a")).unwrap();
        std::fs::write(base_dir.join("change-a").join("proposal.md"), "test").unwrap();

        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["commit", "-m", "add change-a"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        // Create change-b with uncommitted files
        std::fs::create_dir_all(base_dir.join("change-b")).unwrap();
        std::fs::write(base_dir.join("change-b").join("proposal.md"), "uncommitted").unwrap();

        // Modify change-a after commit (staged change)
        std::fs::write(base_dir.join("change-a").join("tasks.md"), "new task").unwrap();
        let _ = Command::new("git")
            .args(["add", "openspec/changes/change-a/tasks.md"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let uncommitted_changes = list_changes_with_uncommitted_files(temp_dir.path())
            .await
            .unwrap();

        // Should include both change-a (staged) and change-b (untracked)
        assert_eq!(
            uncommitted_changes,
            vec!["change-a".to_string(), "change-b".to_string()]
        );
    }

    #[tokio::test]
    async fn test_list_changes_with_uncommitted_files_filters_archive() {
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repo
        let init_result = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        if init_result.is_err() {
            return; // Skip if git not available
        }

        let _ = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let base_dir = temp_dir.path().join("openspec/changes");

        // Create initial commit to establish git repository
        std::fs::create_dir_all(&base_dir).unwrap();
        std::fs::write(temp_dir.path().join("README.md"), "test").unwrap();
        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["commit", "-m", "initial commit"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        // Create archive directory with uncommitted files (should be ignored)
        std::fs::create_dir_all(base_dir.join("archive")).unwrap();
        std::fs::write(base_dir.join("archive").join("old.md"), "archived").unwrap();

        // Create regular change with uncommitted files
        std::fs::create_dir_all(base_dir.join("change-c")).unwrap();
        std::fs::write(base_dir.join("change-c").join("proposal.md"), "test").unwrap();

        let uncommitted_changes = list_changes_with_uncommitted_files(temp_dir.path())
            .await
            .unwrap();

        // Should only include change-c, not archive
        assert_eq!(uncommitted_changes, vec!["change-c".to_string()]);
    }

    #[tokio::test]
    async fn test_list_changes_with_uncommitted_files_detects_unstaged_modified_first_line() {
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repo
        let init_result = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        if init_result.is_err() {
            return; // Skip if git not available
        }

        let _ = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        let change_dir = temp_dir.path().join("openspec/changes/change-a");
        std::fs::create_dir_all(&change_dir).unwrap();
        std::fs::write(change_dir.join("proposal.md"), "test").unwrap();
        std::fs::write(change_dir.join("tasks.md"), "- [ ] task").unwrap();

        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await;
        let _ = Command::new("git")
            .args(["commit", "-m", "add change-a"])
            .current_dir(temp_dir.path())
            .output()
            .await;

        // Create unstaged modification. Status line is typically " M ...",
        // and the leading space can be trimmed by run_git() for the first line.
        std::fs::write(change_dir.join("tasks.md"), "- [x] task").unwrap();

        let uncommitted_changes = list_changes_with_uncommitted_files(temp_dir.path())
            .await
            .unwrap();

        assert_eq!(uncommitted_changes, vec!["change-a".to_string()]);
    }

    #[test]
    fn staged_snapshot_anomaly_rejects_thousands_of_files() {
        let paths = (0..5_001)
            .map(|index| format!("generated/artifact-{index}"))
            .collect::<Vec<_>>();

        let anomaly = staged_snapshot_anomaly(paths.iter().map(String::as_str));

        assert!(anomaly.is_some());
        assert!(anomaly.unwrap().contains("5001 staged files"));
    }

    #[test]
    fn staged_snapshot_anomaly_rejects_temporary_paths() {
        assert!(staged_snapshot_anomaly([".agent-target/debug/artifact"].into_iter()).is_some());
    }

    #[test]
    fn staged_snapshot_anomaly_allows_large_legitimate_changes() {
        let paths = (0..5_000)
            .map(|index| format!("src/generated-{index}.rs"))
            .collect::<Vec<_>>();

        assert!(staged_snapshot_anomaly(paths.iter().map(String::as_str)).is_none());
    }

    #[tokio::test]
    async fn validate_staged_snapshot_resets_suspicious_index() {
        let temp_dir = TempDir::new().unwrap();
        Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        let generated = temp_dir.path().join(".agent-target");
        std::fs::create_dir(&generated).unwrap();
        std::fs::write(generated.join("artifact"), "x").unwrap();
        run_git(&["add", "-A"], temp_dir.path()).await.unwrap();

        let error = validate_staged_snapshot(temp_dir.path()).await.unwrap_err();
        let staged = run_git(&["diff", "--cached", "--name-only"], temp_dir.path())
            .await
            .unwrap();

        assert!(error.to_string().contains("forbidden temporary path"));
        assert!(staged.is_empty());
    }

    #[tokio::test]
    async fn validate_staged_snapshot_supports_non_ascii_paths() {
        let temp_dir = TempDir::new().unwrap();
        Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        std::fs::write(temp_dir.path().join(" 日本語.rs"), "fn main() {}").unwrap();
        run_git(&["add", "-A"], temp_dir.path()).await.unwrap();

        validate_staged_snapshot(temp_dir.path()).await.unwrap();
    }

    #[tokio::test]
    async fn archive_wip_rejects_suspicious_snapshots() {
        let temp_dir = TempDir::new().unwrap();
        Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        let generated = temp_dir.path().join(".agent-target");
        std::fs::create_dir(&generated).unwrap();
        std::fs::write(generated.join("artifact"), "x").unwrap();

        assert!(create_archive_wip_commit(temp_dir.path(), "change-a", 1)
            .await
            .is_err());
    }

    #[test]
    fn test_extract_change_id_from_path() {
        assert_eq!(
            extract_change_id_from_path("openspec/changes/my-change/proposal.md"),
            Some("my-change".to_string())
        );
        assert_eq!(
            extract_change_id_from_path("openspec/changes/my-change/specs/auth/spec.md"),
            Some("my-change".to_string())
        );
        assert_eq!(
            extract_change_id_from_path("openspec/changes/archive/old.md"),
            None
        );
        assert_eq!(
            extract_change_id_from_path("openspec/changes/.hidden/file.md"),
            None
        );
        assert_eq!(extract_change_id_from_path("src/main.rs"), None);
        assert_eq!(
            extract_change_id_from_path("openspec/specs/auth/spec.md"),
            None
        );
    }

    #[test]
    fn uncommitted_monitor_argv_disables_optional_locks_before_subcommand() {
        let argv = uncommitted_monitor_argv();
        assert_eq!(
            argv,
            ["--no-optional-locks", "status", "--porcelain", "-u"],
            "monitoring argv must stay exactly `--no-optional-locks status --porcelain -u`"
        );

        let option_index = argv
            .iter()
            .position(|arg| *arg == "--no-optional-locks")
            .expect("monitoring argv must disable optional locks");
        let subcommand_index = argv
            .iter()
            .position(|arg| *arg == "status")
            .expect("monitoring argv must run the status subcommand");
        assert!(
            option_index < subcommand_index,
            "`--no-optional-locks` is a global option and must precede `status`"
        );

        // Suppression must stay child-command-local: a process-wide
        // GIT_OPTIONAL_LOCKS would also weaken repo-mutating Git commands.
        assert!(
            std::env::var_os("GIT_OPTIONAL_LOCKS").is_none(),
            "optional-lock suppression must not be delivered through process-wide environment state"
        );
    }

    /// Run a Git fixture command, failing the test if the command fails.
    async fn git_fixture(cwd: &Path, args: &[&str]) -> String {
        run_git(args, cwd)
            .await
            .unwrap_or_else(|error| panic!("git fixture command {args:?} failed: {error}"))
    }

    /// Create a Git repository whose commits do not depend on ambient user config.
    async fn init_fixture_repo(cwd: &Path) {
        git_fixture(cwd, &["init", "-q"]).await;
        git_fixture(cwd, &["config", "user.email", "test@example.com"]).await;
        git_fixture(cwd, &["config", "user.name", "Test User"]).await;
        git_fixture(cwd, &["config", "commit.gpgsign", "false"]).await;
    }

    fn write_fixture_file(path: &Path, contents: &str) {
        std::fs::create_dir_all(path.parent().expect("fixture path has a parent"))
            .expect("create fixture directory");
        std::fs::write(path, contents).expect("write fixture file");
    }

    #[tokio::test]
    async fn monitoring_classifies_active_changes_and_keeps_exclusions() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_fixture_repo(root).await;

        let changes = root.join("openspec/changes");

        // Committed baseline: every path that later mutates must exist in HEAD.
        write_fixture_file(&changes.join("change-staged-modify/proposal.md"), "base");
        write_fixture_file(&changes.join("change-staged-delete/proposal.md"), "base");
        write_fixture_file(&changes.join("change-unstaged-modify/proposal.md"), "base");
        write_fixture_file(&changes.join("change-unstaged-delete/proposal.md"), "base");
        write_fixture_file(&changes.join("change-rename/old.md"), "base");
        write_fixture_file(&changes.join("change-clean/proposal.md"), "base");
        write_fixture_file(&changes.join("change-ignored/proposal.md"), "base");
        write_fixture_file(&root.join("docs/notes.md"), "base");
        write_fixture_file(&root.join(".gitignore"), "*.log\n");
        git_fixture(root, &["add", "-A"]).await;
        git_fixture(root, &["commit", "-qm", "baseline"]).await;

        // Staged add.
        write_fixture_file(&changes.join("change-staged-add/proposal.md"), "added");
        git_fixture(
            root,
            &["add", "openspec/changes/change-staged-add/proposal.md"],
        )
        .await;

        // Staged modify.
        write_fixture_file(
            &changes.join("change-staged-modify/proposal.md"),
            "modified",
        );
        git_fixture(
            root,
            &["add", "openspec/changes/change-staged-modify/proposal.md"],
        )
        .await;

        // Staged delete.
        git_fixture(
            root,
            &[
                "rm",
                "-q",
                "openspec/changes/change-staged-delete/proposal.md",
            ],
        )
        .await;

        // Unstaged modify.
        write_fixture_file(
            &changes.join("change-unstaged-modify/proposal.md"),
            "modified",
        );

        // Unstaged delete.
        std::fs::remove_file(changes.join("change-unstaged-delete/proposal.md"))
            .expect("remove fixture file");

        // Untracked file in a change that has never been committed.
        write_fixture_file(&changes.join("change-untracked/proposal.md"), "untracked");

        // Rename within the same change.
        git_fixture(
            root,
            &[
                "mv",
                "openspec/changes/change-rename/old.md",
                "openspec/changes/change-rename/new.md",
            ],
        )
        .await;

        // Exclusions: archive entry, hidden change directory, ignored file, and
        // an unrelated repository path.
        write_fixture_file(&changes.join("archive/change-old/proposal.md"), "archived");
        write_fixture_file(&changes.join(".hidden-change/proposal.md"), "hidden");
        write_fixture_file(&changes.join("change-ignored/debug.log"), "ignored");
        write_fixture_file(&root.join("docs/notes.md"), "unrelated change");

        let uncommitted = list_changes_with_uncommitted_files(root).await.unwrap();

        assert_eq!(
            uncommitted,
            vec![
                "change-rename".to_string(),
                "change-staged-add".to_string(),
                "change-staged-delete".to_string(),
                "change-staged-modify".to_string(),
                "change-unstaged-delete".to_string(),
                "change-unstaged-modify".to_string(),
                "change-untracked".to_string(),
            ],
            "classification drifted; raw status was: {:?}",
            run_git(&uncommitted_monitor_argv(), root).await.unwrap()
        );
    }

    #[tokio::test]
    async fn monitoring_does_not_persist_optional_index_refresh() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_fixture_repo(root).await;

        let changes = root.join("openspec/changes");
        write_fixture_file(&changes.join("change-a/proposal.md"), "base");
        write_fixture_file(&changes.join("change-a/tasks.md"), "- [ ] task\n");
        git_fixture(root, &["add", "-A"]).await;
        git_fixture(root, &["commit", "-qm", "baseline"]).await;

        // Current worktree state the monitoring query must still report. The
        // rewrite changes the file size so detection cannot depend on mtime
        // granularity.
        write_fixture_file(
            &changes.join("change-a/tasks.md"),
            "- [x] task\n- [ ] second task\n",
        );

        // Make the cached stat information of a content-identical file stale so
        // that a normal `git status` has a reason to rewrite the index.
        let stale_target = changes.join("change-a/proposal.md");
        let stale_time = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
        std::fs::File::options()
            .write(true)
            .open(&stale_target)
            .expect("open fixture file")
            .set_times(std::fs::FileTimes::new().set_modified(stale_time))
            .expect("backdate fixture mtime");

        let index_path = root.join(".git/index");
        let stale_index = std::fs::read(&index_path).expect("read index");

        // Positive control: without optional-lock suppression the fixture must
        // demonstrably persist an index refresh, otherwise the assertion below
        // would be vacuous.
        git_fixture(root, &["status", "--porcelain", "-u"]).await;
        let control_index = std::fs::read(&index_path).expect("read index after control");
        assert_ne!(
            stale_index, control_index,
            "fixture cannot detect an optional index refresh; the index-safety assertion would be vacuous"
        );

        // Restore the stale index so the production helper faces the same
        // refresh opportunity the control command just took.
        std::fs::write(&index_path, &stale_index).expect("restore stale index");

        let uncommitted = list_changes_with_uncommitted_files(root).await.unwrap();
        let after_index = std::fs::read(&index_path).expect("read index after monitoring");

        assert_eq!(
            uncommitted,
            vec!["change-a".to_string()],
            "monitoring query must still report current worktree changes"
        );
        assert_eq!(
            stale_index, after_index,
            "monitoring query must leave the complete Git index bytes unchanged"
        );
    }
}