cflx 0.6.322

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
//! Repository-scoped orchestration lock.
//!
//! At most one local orchestration-owning `cflx` process may run per Git
//! repository. Repository identity is the canonical Git *common* directory, so
//! linked worktrees of one repository share a single exclusion domain while
//! unrelated repositories stay independent.
//!
//! Ownership authority is the OS advisory lock held on an open file descriptor
//! for the process lifetime; normal and abnormal exit both release it. The JSON
//! owner file stored next to the lock is observability-only: it may be missing,
//! partial, malformed, or left over from a dead process, and none of those
//! states can grant or deny ownership. Nothing in this module is a workflow
//! control input.

use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use serde::{Deserialize, Serialize};

/// Lock file held open (and OS-locked) for the owner's process lifetime.
pub const LOCK_FILE_NAME: &str = "cflx-orchestration.lock";

/// Diagnostic owner metadata, replaced atomically. Never an ownership authority.
pub const OWNER_FILE_NAME: &str = "cflx-orchestration-owner.json";

/// How the owning process was invoked. Reported in conflict diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvocationMode {
    Tui,
    Run,
}

impl InvocationMode {
    pub fn as_str(self) -> &'static str {
        match self {
            InvocationMode::Tui => "tui",
            InvocationMode::Run => "run",
        }
    }
}

/// The CLI entrypoint being started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvocationKind {
    /// `cflx` with no subcommand (default TUI).
    DefaultTui,
    /// `cflx tui`.
    Tui,
    /// `cflx run`.
    Run,
    /// Any command that does not own local orchestration.
    Other,
}

/// Whether an invocation must take the repository orchestration lock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockDecision {
    Acquire(InvocationMode),
    Bypass,
}

/// Decide whether an invocation owns local orchestration for this repository.
pub fn classify_invocation(kind: InvocationKind) -> LockDecision {
    match kind {
        InvocationKind::DefaultTui | InvocationKind::Tui => {
            LockDecision::Acquire(InvocationMode::Tui)
        }
        InvocationKind::Run => LockDecision::Acquire(InvocationMode::Run),
        InvocationKind::Other => LockDecision::Bypass,
    }
}

/// Best-effort diagnostic description of the current lock owner.
///
/// Every field is optional so a partially written, truncated, or
/// forward-versioned owner file still yields whatever can be read safely.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnerMetadata {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    /// Legacy single-endpoint field. Still read so metadata written by an older
    /// version stays useful; new owners write [`Self::endpoints`] instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_url: Option<String>,
    /// Every endpoint whose listener completed startup, in publication order.
    ///
    /// Unix endpoints appear as `unix://<path>` and TCP endpoints as their
    /// browser URL, so the transport is readable without a second field.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub endpoints: Vec<String>,
}

impl OwnerMetadata {
    /// True when no field carries usable information.
    pub fn is_empty(&self) -> bool {
        self.pid.is_none()
            && self.started_at.is_none()
            && self.workspace.is_none()
            && self.mode.is_none()
            && self.api_url.is_none()
            && self.endpoints.is_empty()
    }

    /// Endpoints this owner claims, newest format first.
    ///
    /// Legacy metadata carrying only `api_url` reports that URL, so a conflict
    /// diagnostic never loses the endpoint just because the writer predates the
    /// collection.
    pub fn available_endpoints(&self) -> Vec<&str> {
        if !self.endpoints.is_empty() {
            return self.endpoints.iter().map(String::as_str).collect();
        }
        self.api_url.as_deref().into_iter().collect()
    }

    /// Drop fields that cannot describe a live owner (blank strings, pid 0).
    fn sanitized(mut self) -> Self {
        fn clean(value: Option<String>) -> Option<String> {
            value
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        }
        self.pid = self.pid.filter(|pid| *pid > 0);
        self.started_at = clean(self.started_at);
        self.workspace = clean(self.workspace);
        self.mode = clean(self.mode);
        self.api_url = clean(self.api_url);
        // A blank or duplicated entry describes no reachable endpoint.
        let mut seen = Vec::new();
        self.endpoints.retain(|endpoint| {
            let trimmed = endpoint.trim().to_string();
            if trimmed.is_empty() || seen.contains(&trimmed) {
                return false;
            }
            seen.push(trimmed);
            true
        });
        self.endpoints = seen;
        self
    }
}

/// Parse owner metadata, returning `None` when nothing usable can be read.
///
/// Malformed or empty content is never an error: the OS lock, not this file,
/// decides ownership.
pub fn parse_owner_metadata(raw: &str) -> Option<OwnerMetadata> {
    let parsed: OwnerMetadata = serde_json::from_str(raw).ok()?;
    let parsed = parsed.sanitized();
    if parsed.is_empty() {
        None
    } else {
        Some(parsed)
    }
}

/// Render the operator-facing conflict diagnostic.
///
/// Unavailable fields are omitted rather than guessed; in particular no API URL
/// is claimed unless the owner published one after a successful bind.
pub fn conflict_message(common_dir: &Path, owner: Option<&OwnerMetadata>) -> String {
    let mut out = String::new();
    out.push_str("Error: another Conflux process is already orchestrating this repository.\n");
    out.push_str(&format!("  repository: {}\n", common_dir.display()));

    let mut described = false;
    if let Some(owner) = owner {
        if let Some(pid) = owner.pid {
            out.push_str(&format!("  owner pid:  {pid}\n"));
            described = true;
        }
        if let Some(mode) = &owner.mode {
            out.push_str(&format!("  mode:       {mode}\n"));
            described = true;
        }
        if let Some(started_at) = &owner.started_at {
            out.push_str(&format!("  started at: {started_at}\n"));
            described = true;
        }
        if let Some(workspace) = &owner.workspace {
            out.push_str(&format!("  workspace:  {workspace}\n"));
            described = true;
        }
        // One line per successfully bound endpoint, so a process serving both
        // UDS and TCP is reported as both rather than as whichever came first.
        for endpoint in owner.available_endpoints() {
            out.push_str(&format!("  api url:    {endpoint}\n"));
            described = true;
        }
    }
    if !described {
        out.push_str("  owner details are unavailable (lock metadata missing or unreadable)\n");
    }

    out.push_str(
        "Stop the owning process, or use its reported endpoint, instead of starting another one.",
    );
    out
}

/// Lexically normalize `.` and `..` without touching the filesystem.
pub fn normalize_path(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => match out.components().next_back() {
                Some(Component::Normal(_)) => {
                    out.pop();
                }
                // `/..` is `/`; a leading `..` has nothing to cancel.
                Some(Component::RootDir) | Some(Component::Prefix(_)) => {}
                _ => out.push(Component::ParentDir),
            },
            other => out.push(other),
        }
    }
    out
}

/// Extract the target of a `gitdir: <path>` pointer file.
pub fn parse_gitdir_pointer(contents: &str) -> Option<&str> {
    contents
        .lines()
        .find_map(|line| line.trim().strip_prefix("gitdir:"))
        .map(str::trim)
        .filter(|target| !target.is_empty())
}

/// Resolve the Git directory for a `.git` entry.
///
/// `pointer_contents` is `None` when `.git` is a real directory and `Some` when
/// it is a linked-worktree pointer file.
pub fn resolve_git_dir(dot_git: &Path, pointer_contents: Option<&str>) -> Option<PathBuf> {
    let Some(contents) = pointer_contents else {
        return Some(normalize_path(dot_git));
    };
    let target = Path::new(parse_gitdir_pointer(contents)?);
    if target.is_absolute() {
        Some(normalize_path(target))
    } else {
        Some(normalize_path(&dot_git.parent()?.join(target)))
    }
}

/// Resolve the Git *common* directory from a Git directory and its optional
/// `commondir` file contents.
///
/// A linked worktree's Git directory contains `commondir` pointing back at the
/// shared directory, which is what makes worktrees of one repository collapse
/// onto a single lock.
pub fn resolve_common_dir(git_dir: &Path, commondir_contents: Option<&str>) -> PathBuf {
    match commondir_contents
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        None => normalize_path(git_dir),
        Some(value) => {
            let target = Path::new(value);
            if target.is_absolute() {
                normalize_path(target)
            } else {
                normalize_path(&git_dir.join(target))
            }
        }
    }
}

/// The repository identities a workspace resolves to.
///
/// `git_dir` and `common_dir` are equal for a main worktree — including one
/// whose `.git` is a pointer file to a separate Git directory — and differ only
/// for a linked worktree, whose Git directory lives under the shared
/// `worktrees/` registry. That difference is the repository evidence the
/// orchestration-owner preflight classifies on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitDirectories {
    /// The working tree root: the directory holding the `.git` entry.
    pub worktree_root: PathBuf,
    /// This working tree's own resolved Git directory.
    pub git_dir: PathBuf,
    /// The Git common directory shared by every worktree of the repository.
    pub common_dir: PathBuf,
}

/// Canonicalize when the path exists, otherwise normalize it lexically.
fn canonical_or_normalized(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| normalize_path(path))
}

/// Resolve both Git identities for `workspace` from repository evidence.
///
/// Returns `None` when the path is not inside a Git working tree; callers treat
/// that as "no repository identity" rather than an error.
pub fn discover_git_directories(workspace: &Path) -> Option<GitDirectories> {
    let start = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
    for dir in start.ancestors() {
        let dot_git = dir.join(".git");
        let Ok(meta) = std::fs::metadata(&dot_git) else {
            continue;
        };
        let git_dir = if meta.is_dir() {
            resolve_git_dir(&dot_git, None)?
        } else {
            let contents = std::fs::read_to_string(&dot_git).ok()?;
            resolve_git_dir(&dot_git, Some(&contents))?
        };
        let commondir = std::fs::read_to_string(git_dir.join("commondir")).ok();
        let common_dir = resolve_common_dir(&git_dir, commondir.as_deref());
        return Some(GitDirectories {
            worktree_root: dir.to_path_buf(),
            git_dir: canonical_or_normalized(&git_dir),
            common_dir: canonical_or_normalized(&common_dir),
        });
    }
    None
}

/// Find the canonical Git common directory for `workspace`, if any.
///
/// Returns `None` when the path is not inside a Git repository; callers treat
/// that as "no repository identity to lock" rather than an error.
pub fn discover_common_dir(workspace: &Path) -> Option<PathBuf> {
    discover_git_directories(workspace).map(|dirs| dirs.common_dir)
}

/// The repository and, when readable, the owner a conflict was lost to.
#[derive(Debug)]
pub struct LockConflict {
    pub common_dir: PathBuf,
    pub owner: Option<OwnerMetadata>,
}

/// Why a repository lock could not be acquired.
#[derive(Debug)]
pub enum LockError {
    /// Another live process holds the OS lock. Boxed to keep this error small
    /// enough to travel in a `Result` without bloating the success path.
    Conflict(Box<LockConflict>),
    /// The lock file itself could not be opened or locked.
    Io { path: PathBuf, source: io::Error },
}

impl std::fmt::Display for LockError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LockError::Conflict(conflict) => {
                write!(
                    f,
                    "{}",
                    conflict_message(&conflict.common_dir, conflict.owner.as_ref())
                )
            }
            LockError::Io { path, source } => {
                write!(
                    f,
                    "failed to use repository lock file '{}': {}",
                    path.display(),
                    source
                )
            }
        }
    }
}

impl std::error::Error for LockError {}

/// An owned repository orchestration lock.
///
/// The OS releases the lock when the descriptor closes, which happens on both
/// normal drop and abnormal process termination. No stale-file cleanup exists
/// because none is needed.
pub struct RepositoryLock {
    _file: File,
    common_dir: PathBuf,
    owner_path: PathBuf,
    metadata: Mutex<OwnerMetadata>,
}

impl RepositoryLock {
    pub fn common_dir(&self) -> &Path {
        &self.common_dir
    }

    /// Snapshot of the metadata this process last published.
    pub fn metadata_snapshot(&self) -> OwnerMetadata {
        self.metadata
            .lock()
            .map(|guard| guard.clone())
            .unwrap_or_default()
    }

    /// Record every endpoint whose listener has actually bound.
    ///
    /// Called only after the whole startup transaction succeeded, so a
    /// conflicting invocation never sees an endpoint that was requested but not
    /// reachable. Purely observational: nothing about lock ownership or workflow
    /// routing reads this.
    pub fn publish_endpoints(&self, endpoints: &[String]) {
        let Ok(mut guard) = self.metadata.lock() else {
            return;
        };
        if guard.endpoints == endpoints {
            return;
        }
        guard.endpoints = endpoints.to_vec();
        let snapshot = guard.clone();
        drop(guard);
        write_owner_metadata(&self.owner_path, &snapshot);
    }

    /// Record a single API base URL after a listener has actually bound.
    pub fn publish_api_url(&self, url: &str) {
        self.publish_endpoints(std::slice::from_ref(&url.to_string()));
    }
}

/// Try to take the repository orchestration lock for `workspace`.
///
/// `Ok(None)` means the workspace is not in a Git repository, so there is no
/// repository identity to exclude on.
pub fn acquire(
    workspace: &Path,
    mode: InvocationMode,
) -> Result<Option<RepositoryLock>, LockError> {
    let Some(common_dir) = discover_common_dir(workspace) else {
        return Ok(None);
    };
    let lock_path = common_dir.join(LOCK_FILE_NAME);
    let owner_path = common_dir.join(OWNER_FILE_NAME);

    // `truncate(false)`: the file's contents are irrelevant, only the lock on
    // its descriptor matters, and truncating would race with a live owner.
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .map_err(|source| LockError::Io {
            path: lock_path.clone(),
            source,
        })?;

    match try_lock_exclusive(&file) {
        Ok(true) => {}
        Ok(false) => {
            return Err(LockError::Conflict(Box::new(LockConflict {
                common_dir,
                owner: read_owner_metadata(&owner_path),
            })))
        }
        Err(source) => {
            return Err(LockError::Io {
                path: lock_path,
                source,
            })
        }
    }

    let workspace_display = std::fs::canonicalize(workspace)
        .unwrap_or_else(|_| workspace.to_path_buf())
        .display()
        .to_string();
    let metadata = OwnerMetadata {
        pid: Some(std::process::id()),
        started_at: Some(chrono::Utc::now().to_rfc3339()),
        workspace: Some(workspace_display),
        mode: Some(mode.as_str().to_string()),
        api_url: None,
        endpoints: Vec::new(),
    };
    write_owner_metadata(&owner_path, &metadata);

    Ok(Some(RepositoryLock {
        _file: file,
        common_dir,
        owner_path,
        metadata: Mutex::new(metadata),
    }))
}

/// Read owner metadata best-effort. Any failure yields `None`.
pub fn read_owner_metadata(owner_path: &Path) -> Option<OwnerMetadata> {
    let raw = std::fs::read_to_string(owner_path).ok()?;
    parse_owner_metadata(&raw)
}

/// Replace the owner file atomically so a competitor never reads partial JSON.
fn write_owner_metadata(owner_path: &Path, metadata: &OwnerMetadata) {
    let Ok(json) = serde_json::to_string_pretty(metadata) else {
        return;
    };
    let tmp_path =
        owner_path.with_file_name(format!("{}.{}.tmp", OWNER_FILE_NAME, std::process::id()));
    if std::fs::write(&tmp_path, json.as_bytes()).is_err() {
        let _ = std::fs::remove_file(&tmp_path);
        return;
    }
    if std::fs::rename(&tmp_path, owner_path).is_err() {
        let _ = std::fs::remove_file(&tmp_path);
    }
}

#[cfg(unix)]
fn try_lock_exclusive(file: &File) -> io::Result<bool> {
    use std::os::unix::io::AsRawFd;

    // Non-blocking: a busy repository must fail fast, never queue behind the
    // current owner.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(true);
    }
    let err = io::Error::last_os_error();
    match err.raw_os_error() {
        Some(code) if code == libc::EWOULDBLOCK || code == libc::EAGAIN => Ok(false),
        _ => Err(err),
    }
}

/// Windows locking is future work; until it lands, no exclusion is claimed
/// rather than a false one being reported.
#[cfg(not(unix))]
fn try_lock_exclusive(_file: &File) -> io::Result<bool> {
    Ok(true)
}

/// Process-wide lock owner, kept alive for the whole process lifetime.
static ACTIVE_LOCK: OnceLock<RepositoryLock> = OnceLock::new();

/// Retain the acquired lock for the process lifetime.
pub fn install(lock: RepositoryLock) {
    let _ = ACTIVE_LOCK.set(lock);
}

/// Publish bound API endpoints onto the installed lock, if this process owns one.
///
/// A no-op for bypassed invocations and for non-repository workspaces, so
/// listener startup paths can call it unconditionally after a successful bind.
pub fn publish_endpoints(endpoints: &[String]) {
    if let Some(lock) = ACTIVE_LOCK.get() {
        lock.publish_endpoints(endpoints);
    }
}

/// Publish a single API base URL onto the installed lock.
pub fn publish_api_url(url: &str) {
    publish_endpoints(std::slice::from_ref(&url.to_string()));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn local_orchestration_entrypoints_acquire_and_others_bypass() {
        assert_eq!(
            classify_invocation(InvocationKind::DefaultTui),
            LockDecision::Acquire(InvocationMode::Tui)
        );
        assert_eq!(
            classify_invocation(InvocationKind::Tui),
            LockDecision::Acquire(InvocationMode::Tui)
        );
        assert_eq!(
            classify_invocation(InvocationKind::Run),
            LockDecision::Acquire(InvocationMode::Run)
        );
        assert_eq!(
            classify_invocation(InvocationKind::Other),
            LockDecision::Bypass
        );
    }

    #[test]
    fn owner_metadata_round_trips_without_endpoints() {
        let metadata = OwnerMetadata {
            pid: Some(4321),
            started_at: Some("2026-07-31T12:00:00+00:00".to_string()),
            workspace: Some("/repo".to_string()),
            mode: Some("run".to_string()),
            api_url: None,
            endpoints: Vec::new(),
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(!json.contains("api_url"), "json={json}");
        assert!(!json.contains("endpoints"), "json={json}");
        assert_eq!(parse_owner_metadata(&json), Some(metadata));
    }

    /// A dual-listener owner serializes both endpoints and reads them back in
    /// publication order.
    #[test]
    fn owner_metadata_round_trips_a_dual_endpoint_collection() {
        let metadata = OwnerMetadata {
            pid: Some(4321),
            mode: Some("tui".to_string()),
            endpoints: vec![
                "unix:///repo/.git/cflx-api.sock".to_string(),
                "http://localhost:39876".to_string(),
            ],
            ..OwnerMetadata::default()
        };
        let json = serde_json::to_string(&metadata).unwrap();
        let parsed = parse_owner_metadata(&json).expect("metadata");
        assert_eq!(parsed, metadata);
        assert_eq!(
            parsed.available_endpoints(),
            vec!["unix:///repo/.git/cflx-api.sock", "http://localhost:39876"]
        );
    }

    /// Metadata written before the collection existed must keep reporting its
    /// endpoint rather than becoming silently endpoint-less.
    #[test]
    fn legacy_single_url_metadata_still_reports_its_endpoint() {
        let parsed =
            parse_owner_metadata(r#"{"pid": 91, "api_url": "http://localhost:39876"}"#).unwrap();
        assert_eq!(parsed.available_endpoints(), vec!["http://localhost:39876"]);
        assert!(parsed.endpoints.is_empty());

        // When both forms are present the collection wins: it is the one the
        // current startup transaction wrote.
        let both = parse_owner_metadata(
            r#"{"api_url": "http://legacy", "endpoints": ["unix:///repo/.git/cflx-api.sock"]}"#,
        )
        .unwrap();
        assert_eq!(
            both.available_endpoints(),
            vec!["unix:///repo/.git/cflx-api.sock"]
        );
    }

    #[test]
    fn blank_and_duplicate_endpoints_describe_nothing_and_are_dropped() {
        let parsed = parse_owner_metadata(
            r#"{"pid": 3, "endpoints": ["  ", "unix:///a.sock", "unix:///a.sock", " http://x "]}"#,
        )
        .unwrap();
        assert_eq!(parsed.endpoints, vec!["unix:///a.sock", "http://x"]);

        // Endpoints alone are enough to describe an owner...
        let only_endpoints =
            parse_owner_metadata(r#"{"endpoints": ["unix:///a.sock"]}"#).expect("readable");
        assert_eq!(only_endpoints.available_endpoints(), vec!["unix:///a.sock"]);
        // ...but an all-blank collection describes none.
        assert_eq!(parse_owner_metadata(r#"{"endpoints": ["", "   "]}"#), None);
    }

    #[test]
    fn partial_metadata_keeps_readable_fields() {
        let parsed = parse_owner_metadata(r#"{"pid": 77, "mode": "server"}"#).unwrap();
        assert_eq!(parsed.pid, Some(77));
        assert_eq!(parsed.mode.as_deref(), Some("server"));
        assert_eq!(parsed.started_at, None);
        assert_eq!(parsed.api_url, None);
    }

    #[test]
    fn malformed_or_useless_metadata_parses_to_none() {
        assert_eq!(parse_owner_metadata("not json at all"), None);
        assert_eq!(parse_owner_metadata("{\"pid\": 12"), None);
        assert_eq!(parse_owner_metadata("{}"), None);
        // Blank fields and pid 0 describe no owner.
        assert_eq!(
            parse_owner_metadata(r#"{"pid": 0, "mode": "  ", "workspace": ""}"#),
            None
        );
        // A forward-compatible extra field must not discard readable fields.
        let parsed = parse_owner_metadata(r#"{"pid": 5, "future_field": true}"#).unwrap();
        assert_eq!(parsed.pid, Some(5));
    }

    #[test]
    fn conflict_message_reports_every_available_field() {
        let owner = OwnerMetadata {
            pid: Some(4321),
            started_at: Some("2026-07-31T12:00:00+00:00".to_string()),
            workspace: Some("/repo".to_string()),
            mode: Some("server".to_string()),
            api_url: Some("http://localhost:39876".to_string()),
            endpoints: Vec::new(),
        };
        let message = conflict_message(Path::new("/repo/.git"), Some(&owner));
        assert!(message.contains("/repo/.git"), "message={message}");
        assert!(message.contains("4321"), "message={message}");
        assert!(message.contains("server"), "message={message}");
        assert!(
            message.contains("2026-07-31T12:00:00+00:00"),
            "message={message}"
        );
        assert!(message.contains("/repo"), "message={message}");
        assert!(
            message.contains("http://localhost:39876"),
            "message={message}"
        );
    }

    #[test]
    fn conflict_message_reports_both_bound_endpoints() {
        let owner = OwnerMetadata {
            pid: Some(4321),
            endpoints: vec![
                "unix:///repo/.git/cflx-api.sock".to_string(),
                "http://localhost:39876".to_string(),
            ],
            ..OwnerMetadata::default()
        };
        let message = conflict_message(Path::new("/repo/.git"), Some(&owner));
        assert!(
            message.contains("unix:///repo/.git/cflx-api.sock"),
            "message={message}"
        );
        assert!(
            message.contains("http://localhost:39876"),
            "message={message}"
        );
    }

    /// A failed startup transaction publishes nothing, so a conflict must not
    /// name an endpoint the owner never finished binding.
    #[test]
    fn conflict_message_claims_no_endpoint_after_a_partial_startup() {
        let owner = OwnerMetadata {
            pid: Some(4321),
            mode: Some("run".to_string()),
            ..OwnerMetadata::default()
        };
        let message = conflict_message(Path::new("/repo/.git"), Some(&owner));
        assert!(!message.contains("api url"), "message={message}");
        assert!(!message.contains("unix://"), "message={message}");
    }

    #[test]
    fn conflict_message_omits_api_url_when_absent() {
        let owner = OwnerMetadata {
            pid: Some(4321),
            mode: Some("run".to_string()),
            ..OwnerMetadata::default()
        };
        let message = conflict_message(Path::new("/repo/.git"), Some(&owner));
        assert!(!message.contains("api url"), "message={message}");
        assert!(message.contains("4321"), "message={message}");
    }

    #[test]
    fn conflict_message_stays_valid_without_metadata() {
        let message = conflict_message(Path::new("/repo/.git"), None);
        assert!(
            message.contains("already orchestrating this repository"),
            "message={message}"
        );
        assert!(
            message.contains("owner details are unavailable"),
            "message={message}"
        );
        assert!(!message.contains("api url"), "message={message}");
    }

    #[test]
    fn normalize_path_cancels_parent_components() {
        assert_eq!(
            normalize_path(Path::new("/repo/.git/worktrees/wt/../..")),
            PathBuf::from("/repo/.git")
        );
        assert_eq!(
            normalize_path(Path::new("/repo/./.git")),
            PathBuf::from("/repo/.git")
        );
        assert_eq!(normalize_path(Path::new("/..")), PathBuf::from("/"));
    }

    #[test]
    fn plain_git_directory_is_its_own_common_dir() {
        let git_dir = resolve_git_dir(Path::new("/repo/.git"), None).unwrap();
        assert_eq!(git_dir, PathBuf::from("/repo/.git"));
        assert_eq!(
            resolve_common_dir(&git_dir, None),
            PathBuf::from("/repo/.git")
        );
    }

    #[test]
    fn linked_worktree_resolves_to_the_shared_common_dir() {
        let git_dir = resolve_git_dir(
            Path::new("/repo/wt/.git"),
            Some("gitdir: /repo/.git/worktrees/wt\n"),
        )
        .unwrap();
        assert_eq!(git_dir, PathBuf::from("/repo/.git/worktrees/wt"));
        assert_eq!(
            resolve_common_dir(&git_dir, Some("../..\n")),
            PathBuf::from("/repo/.git")
        );
    }

    #[test]
    fn relative_gitdir_pointer_resolves_against_the_worktree() {
        let git_dir = resolve_git_dir(
            Path::new("/repo/wt/.git"),
            Some("gitdir: ../.git/worktrees/wt"),
        )
        .unwrap();
        assert_eq!(git_dir, PathBuf::from("/repo/.git/worktrees/wt"));
    }

    #[test]
    fn absolute_commondir_is_used_verbatim() {
        assert_eq!(
            resolve_common_dir(
                Path::new("/repo/.git/worktrees/wt"),
                Some("/elsewhere/.git")
            ),
            PathBuf::from("/elsewhere/.git")
        );
    }

    #[test]
    fn unusable_gitdir_pointers_are_rejected() {
        assert_eq!(
            parse_gitdir_pointer("gitdir: /repo/.git"),
            Some("/repo/.git")
        );
        assert_eq!(parse_gitdir_pointer("gitdir:   "), None);
        assert_eq!(parse_gitdir_pointer("something else"), None);
        assert!(resolve_git_dir(Path::new("/repo/.git"), Some("garbage")).is_none());
    }
}