rpi-cli 0.34.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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
//! Development workflow for Rust-native rpi extensions.
//!
//! `rpi dev` detects a Cargo `cdylib`, builds it, stages a uniquely named copy
//! under `.rpi/extensions/.dev`, and optionally watches its source tree. Unique
//! staging directories are required on Windows because a loaded DLL cannot be
//! overwritten until the old `Library` handle is released by `/reload`.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

use serde::Deserialize;

use crate::args::Args;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DevOptions {
    pub package: Option<String>,
    pub release: bool,
    pub watch: bool,
    pub local_only: bool,
    pub passthrough: Vec<String>,
    pub help: bool,
}

pub fn parse_args(args: &[String]) -> Result<DevOptions, String> {
    let mut options = DevOptions {
        watch: true,
        ..DevOptions::default()
    };
    let mut passthrough = false;
    let mut index = 0;
    while index < args.len() {
        let value = &args[index];
        if passthrough {
            options.passthrough.push(value.clone());
        } else {
            match value.as_str() {
                "--" => passthrough = true,
                "--help" | "-h" => options.help = true,
                "--release" => options.release = true,
                "--no-watch" => options.watch = false,
                "--local-only" => options.local_only = true,
                "--package" | "-P" => {
                    index += 1;
                    let package = args
                        .get(index)
                        .filter(|value| !value.trim().is_empty())
                        .ok_or("rpi dev --package requires a package name")?;
                    options.package = Some(package.clone());
                }
                _ => options.passthrough.push(value.clone()),
            }
        }
        index += 1;
    }
    Ok(options)
}

pub fn print_help() {
    println!(
        "Usage: rpi dev [dev options] [--] [rpi options/messages...]\n       rpi dev-local [dev options] [--] [rpi options/messages...]\n\n\
Build the current Rust rpi extension, load it, and watch for changes.\n\n\
Dev options:\n  \
--package, -P <name>  Select a cdylib package in a multi-package workspace\n  \
--release              Build with Cargo's release profile\n  \
--no-watch             Build once; /reload still rebuilds manually\n  \
--local-only           Load only this extension and its discovered resources\n  \
--help, -h             Show this help\n\n\
Examples:\n  \
rpi dev\n  \
rpi dev-local\n  \
rpi dev --package my-extension\n  \
rpi dev --release -- --model gateway/model\n"
    );
}

#[derive(Debug, Deserialize)]
struct CargoMetadata {
    packages: Vec<MetadataPackage>,
    workspace_root: PathBuf,
}

#[derive(Debug, Deserialize)]
struct MetadataPackage {
    name: String,
    manifest_path: PathBuf,
    targets: Vec<MetadataTarget>,
}

#[derive(Debug, Deserialize)]
struct MetadataTarget {
    name: String,
    crate_types: Vec<String>,
}

#[derive(Debug, Clone)]
struct ExtensionProject {
    package: String,
    target: String,
    manifest: PathBuf,
    package_root: PathBuf,
    workspace_root: PathBuf,
}

pub struct DevExtension {
    project: ExtensionProject,
    release: bool,
    watch: bool,
    local_only: bool,
    stage_root: PathBuf,
    current_stage: Mutex<Option<PathBuf>>,
    build_lock: Mutex<()>,
    generation: AtomicU64,
    stop: AtomicBool,
}

impl DevExtension {
    pub fn detect(cwd: &Path, options: &DevOptions) -> Result<Arc<Self>, String> {
        let project = detect_project(cwd, options.package.as_deref())?;
        let stage_root =
            crate::host::dev_staging::allocate(&project.workspace_root, &project.package)?;
        Ok(Arc::new(Self {
            project,
            release: options.release,
            watch: options.watch,
            local_only: options.local_only,
            stage_root,
            current_stage: Mutex::new(None),
            build_lock: Mutex::new(()),
            generation: AtomicU64::new(0),
            stop: AtomicBool::new(false),
        }))
    }

    /// Initial preparation only: no other strong/weak owner, watcher or staged
    /// generation may exist yet. Failed builds can then discard this namespace
    /// without touching loaded DLLs, another instance, or legacy directories.
    pub(crate) fn prepare_initial(
        mut self: Arc<Self>,
        args: &mut Args,
    ) -> Result<Arc<Self>, String> {
        let dev = Arc::get_mut(&mut self)
            .ok_or("initial dev preparation requires exclusive ownership")?;
        if dev.generation.load(Ordering::SeqCst) != 0
            || dev
                .current_stage
                .get_mut()
                .map_err(|_| "dev stage state is poisoned")?
                .is_some()
        {
            return Err("initial dev preparation requires an unbuilt instance".into());
        }
        if let Err(error) = dev.rebuild().and_then(|_| dev.apply_to_args(args)) {
            if let Err(cleanup) = crate::host::dev_staging::discard_unloaded(&dev.stage_root) {
                return Err(format!(
                    "{error}\nInitial staging cleanup failed at {}: {cleanup}; directory may remain",
                    dev.stage_root.display()
                ));
            }
            return Err(error);
        }
        Ok(self)
    }

    pub fn package_name(&self) -> &str {
        &self.project.package
    }

    pub fn watch_enabled(&self) -> bool {
        self.watch
    }

    /// Compile and stage a fresh copy. The current stage changes only after a
    /// successful Cargo build and copy, so failed reloads keep the live plugin.
    pub fn rebuild(&self) -> Result<PathBuf, String> {
        let _guard = self.build_lock.lock().unwrap();
        let artifact = build_cdylib(&self.project, self.release)?;
        let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
        let stage = self.stage_root.join(generation.to_string());
        std::fs::create_dir_all(&stage)
            .map_err(|error| format!("could not create {}: {error}", stage.display()))?;
        let file_name = artifact
            .file_name()
            .ok_or_else(|| format!("Cargo artifact has no file name: {}", artifact.display()))?;
        let staged = stage.join(file_name);
        std::fs::copy(&artifact, &staged).map_err(|error| {
            format!(
                "could not stage extension {} as {}: {error}",
                artifact.display(),
                staged.display()
            )
        })?;
        *self.current_stage.lock().unwrap() = Some(stage.clone());
        Ok(stage)
    }

    pub fn apply_to_args(&self, args: &mut Args) -> Result<(), String> {
        let current = self
            .current_stage
            .lock()
            .unwrap()
            .clone()
            .ok_or("development extension has not been built")?;
        if self.local_only {
            args.dev_local_only = true;
            args.extensions_dir.clear();
            args.extension.clear();
            args.skill.clear();
            args.prompt_template.clear();
        } else {
            args.extensions_dir
                .retain(|path| !path.starts_with(&self.stage_root));
        }
        args.extensions_dir.push(current);
        Ok(())
    }

    /// Poll the extension inputs in a background thread. A change signals the
    /// existing reload mailbox; the TUI serializes compilation and the plugin
    /// swap on its async main loop, so watcher and manual reloads share one path.
    pub fn start_watcher(
        self: &Arc<Self>,
        mailbox: rpi_extensions::ReloadMailbox,
    ) -> Option<std::thread::JoinHandle<()>> {
        if !self.watch {
            return None;
        }
        let weak = Arc::downgrade(self);
        let mut fingerprint = source_fingerprint(&self.project);
        eprintln!(
            "dev: watching {} (use /reload to rebuild manually)",
            self.project.package_root.display()
        );
        Some(std::thread::spawn(move || loop {
            std::thread::sleep(Duration::from_millis(650));
            let Some(dev) = weak.upgrade() else {
                break;
            };
            if dev.stop.load(Ordering::SeqCst) {
                break;
            }
            let next = source_fingerprint(&dev.project);
            if next == fingerprint {
                continue;
            }
            fingerprint = next;
            if mailbox.signal().is_err() {
                eprintln!("dev: source changed; run /reload to rebuild it");
            }
        }))
    }

    pub fn stop_watcher(&self) {
        self.stop.store(true, Ordering::SeqCst);
    }

    pub fn cleanup(&self) {
        if std::fs::remove_dir_all(&self.stage_root).is_ok() {
            remove_empty_dev_dir(&self.stage_root);
            return;
        }
        // A host-side keepalive can retain the mapped DLL until process exit.
        // A detached copy of rpi retries after this process releases the file.
        if let Ok(exe) = std::env::current_exe() {
            let _ = Command::new(exe)
                .arg("__rpi_dev_cleanup")
                .arg(&self.stage_root)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn();
        }
    }
}

impl Drop for DevExtension {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
    }
}

fn detect_project(cwd: &Path, requested: Option<&str>) -> Result<ExtensionProject, String> {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .current_dir(cwd)
        .stdin(Stdio::null())
        .output()
        .map_err(|error| format!("could not execute cargo metadata: {error}"))?;
    if !output.status.success() {
        return Err(format!(
            "cargo metadata failed:\n{}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    let metadata: CargoMetadata = serde_json::from_slice(&output.stdout)
        .map_err(|error| format!("invalid cargo metadata output: {error}"))?;
    let cwd = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
    let mut candidates = Vec::new();
    for package in metadata.packages {
        if requested.is_some_and(|name| package.name != name) {
            continue;
        }
        let package_root = package
            .manifest_path
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_default();
        for target in package
            .targets
            .iter()
            .filter(|target| target.crate_types.iter().any(|kind| kind == "cdylib"))
        {
            candidates.push(ExtensionProject {
                package: package.name.clone(),
                target: target.name.clone(),
                manifest: package.manifest_path.clone(),
                package_root: package_root.clone(),
                workspace_root: metadata.workspace_root.clone(),
            });
        }
    }
    if candidates.is_empty() {
        return Err(match requested {
            Some(name) => format!("Cargo package `{name}` is not a cdylib extension"),
            None => "current Cargo project does not contain a cdylib extension".to_string(),
        });
    }
    if requested.is_none() {
        let mut local: Vec<_> = candidates
            .iter()
            .filter(|project| cwd.starts_with(&project.package_root))
            .cloned()
            .collect();
        local.sort_by_key(|project| std::cmp::Reverse(project.package_root.components().count()));
        if let Some(project) = local.into_iter().next() {
            return Ok(project);
        }
    }
    if candidates.len() == 1 {
        return Ok(candidates.remove(0));
    }
    Err(format!(
        "multiple cdylib extensions found: {}. Select one with `rpi dev --package <name>`",
        candidates
            .iter()
            .map(|project| project.package.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    ))
}

fn build_cdylib(project: &ExtensionProject, release: bool) -> Result<PathBuf, String> {
    let mut command = Command::new("cargo");
    command
        .arg("build")
        .args(["--manifest-path"])
        .arg(&project.manifest)
        .args([
            "--package",
            &project.package,
            "--message-format=json-render-diagnostics",
        ])
        .current_dir(&project.workspace_root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if release {
        command.arg("--release");
    }
    let output = command
        .output()
        .map_err(|error| format!("could not execute cargo build: {error}"))?;
    let mut artifact = None;
    let mut diagnostics = String::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if let Some(rendered) = value
            .get("message")
            .and_then(|message| message.get("rendered"))
            .and_then(serde_json::Value::as_str)
        {
            append_diagnostic(&mut diagnostics, rendered);
        }
        if value.get("reason").and_then(serde_json::Value::as_str) != Some("compiler-artifact")
            || value
                .get("target")
                .and_then(|target| target.get("name"))
                .and_then(serde_json::Value::as_str)
                != Some(project.target.as_str())
        {
            continue;
        }
        artifact = value
            .get("filenames")
            .and_then(serde_json::Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(serde_json::Value::as_str)
            .map(PathBuf::from)
            .find(|path| is_cdylib(path));
    }
    append_diagnostic(
        &mut diagnostics,
        String::from_utf8_lossy(&output.stderr).as_ref(),
    );
    if !output.status.success() {
        return Err(format_build_failure(output.status, &diagnostics));
    }
    artifact.ok_or_else(|| {
        format!(
            "Cargo built `{}` but did not report a cdylib artifact for `{}`",
            project.package, project.target
        )
    })
}

/// Keep Cargo output out of the terminal while the interactive TUI owns it.
/// Successful diagnostics are intentionally discarded; failures are returned
/// to the caller so the TUI can render them inside its transcript.
fn append_diagnostic(buffer: &mut String, diagnostic: &str) {
    if diagnostic.is_empty() {
        return;
    }
    if !buffer.is_empty() && !buffer.ends_with('\n') {
        buffer.push('\n');
    }
    buffer.push_str(diagnostic);
}

fn format_build_failure(status: impl std::fmt::Display, diagnostics: &str) -> String {
    let diagnostics = diagnostics.trim();
    if diagnostics.is_empty() {
        format!("cargo build exited with {status}")
    } else {
        format!("cargo build exited with {status}:\n{diagnostics}")
    }
}

fn is_cdylib(path: &Path) -> bool {
    matches!(
        path.extension()
            .and_then(|value| value.to_str())
            .map(|value| value.to_ascii_lowercase())
            .as_deref(),
        Some("dll" | "so" | "dylib")
    )
}

fn source_fingerprint(project: &ExtensionProject) -> u64 {
    let mut hasher = DefaultHasher::new();
    fingerprint_path(&project.package_root.join("src"), &mut hasher);
    for path in [
        project.manifest.clone(),
        project.package_root.join("build.rs"),
        project.workspace_root.join("Cargo.toml"),
        project.workspace_root.join("Cargo.lock"),
    ] {
        fingerprint_file(&path, &mut hasher);
    }
    hasher.finish()
}

fn fingerprint_path(path: &Path, hasher: &mut DefaultHasher) {
    let Ok(entries) = std::fs::read_dir(path) else {
        return;
    };
    let mut paths: Vec<_> = entries.flatten().map(|entry| entry.path()).collect();
    paths.sort();
    for path in paths {
        if path.is_dir() {
            fingerprint_path(&path, hasher);
        } else if matches!(
            path.extension().and_then(|value| value.to_str()),
            Some("rs" | "toml" | "json")
        ) {
            fingerprint_file(&path, hasher);
        }
    }
}

fn fingerprint_file(path: &Path, hasher: &mut DefaultHasher) {
    if let Ok(metadata) = std::fs::metadata(path) {
        path.hash(hasher);
        metadata.len().hash(hasher);
        metadata
            .modified()
            .unwrap_or(SystemTime::UNIX_EPOCH)
            .hash(hasher);
    }
}

pub fn run_cleanup_helper(args: &[String]) -> i32 {
    let Some(raw) = args.first() else {
        return 2;
    };
    let path = PathBuf::from(raw);
    if !is_dev_stage_root(&path) {
        return 2;
    }
    for _ in 0..100 {
        match std::fs::remove_dir_all(&path) {
            Ok(()) => {
                remove_empty_dev_dir(&path);
                return 0;
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return 0,
            Err(_) => std::thread::sleep(Duration::from_millis(100)),
        }
    }
    1
}

fn is_dev_stage_root(path: &Path) -> bool {
    path.parent()
        .and_then(Path::file_name)
        .and_then(|v| v.to_str())
        == Some(".dev")
        && path
            .parent()
            .and_then(Path::parent)
            .and_then(Path::file_name)
            .and_then(|v| v.to_str())
            == Some("extensions")
        && path
            .parent()
            .and_then(Path::parent)
            .and_then(Path::parent)
            .and_then(Path::file_name)
            .and_then(|v| v.to_str())
            == Some(".rpi")
}

fn remove_empty_dev_dir(stage_root: &Path) {
    if let Some(parent) = stage_root.parent() {
        let _ = std::fs::remove_dir(parent);
    }
}

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

    #[test]
    fn parses_dev_options_without_consuming_rpi_options() {
        let options = parse_args(&[
            "--package".into(),
            "demo".into(),
            "--release".into(),
            "--model".into(),
            "gateway/model".into(),
        ])
        .unwrap();
        assert_eq!(options.package.as_deref(), Some("demo"));
        assert!(options.release);
        assert!(options.watch);
        assert_eq!(options.passthrough, ["--model", "gateway/model"]);
    }

    #[test]
    fn no_watch_is_honored() {
        let options = parse_args(&["--no-watch".into()]).unwrap();
        assert!(!options.watch);
    }

    #[test]
    fn local_only_is_honored_without_leaking_to_passthrough() {
        let options = parse_args(&[
            "--local-only".into(),
            "--model".into(),
            "gateway/model".into(),
        ])
        .unwrap();
        assert!(options.local_only);
        assert_eq!(options.passthrough, ["--model", "gateway/model"]);
    }

    #[test]
    fn local_only_apply_keeps_only_the_current_stage() {
        let stage_root = PathBuf::from("workspace/.rpi/extensions/.dev/demo-123");
        let current_stage = stage_root.join("1");
        let dev = DevExtension {
            project: ExtensionProject {
                package: "demo".into(),
                target: "demo".into(),
                manifest: PathBuf::from("workspace/Cargo.toml"),
                package_root: PathBuf::from("workspace"),
                workspace_root: PathBuf::from("workspace"),
            },
            release: false,
            watch: true,
            local_only: true,
            stage_root,
            current_stage: Mutex::new(Some(current_stage.clone())),
            build_lock: Mutex::new(()),
            generation: AtomicU64::new(1),
            stop: AtomicBool::new(false),
        };
        let mut args = Args {
            extensions_dir: vec![PathBuf::from("global/extensions")],
            extension: vec![PathBuf::from("other.dll")],
            skill: vec![PathBuf::from("other-skill")],
            prompt_template: vec![PathBuf::from("other-prompt.md")],
            ..Args::default()
        };

        dev.apply_to_args(&mut args).unwrap();

        assert!(args.dev_local_only);
        assert_eq!(args.extensions_dir, [current_stage]);
        assert!(args.extension.is_empty());
        assert!(args.skill.is_empty());
        assert!(args.prompt_template.is_empty());
    }

    #[test]
    fn build_diagnostics_are_buffered_for_ui_errors() {
        let mut diagnostics = String::new();
        append_diagnostic(&mut diagnostics, "warning: unused import\n");
        append_diagnostic(&mut diagnostics, "error: could not compile extension");

        let message = format_build_failure("exit code: 101", &diagnostics);

        assert_eq!(
            message,
            "cargo build exited with exit code: 101:\nwarning: unused import\nerror: could not compile extension"
        );
    }

    #[test]
    fn build_failure_without_diagnostics_stays_compact() {
        assert_eq!(
            format_build_failure("exit code: 101", "\n"),
            "cargo build exited with exit code: 101"
        );
    }

    #[test]
    fn real_metadata_detects_get_separate_stages_and_cleanup_does_not_touch_other_owners() {
        let temp = initial_project("pub fn fixture() {}\n");
        let workspace = temp.path().canonicalize().unwrap();
        // A prior PID-only namespace is not a directory this instance may adopt.
        let legacy = workspace
            .join(".rpi/extensions/.dev")
            .join(format!("stage-fixture-{}", std::process::id()));
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("keep-legacy"), b"prior owner").unwrap();
        let first = DevExtension::detect(&workspace, &DevOptions::default()).unwrap();
        let second = DevExtension::detect(&workspace, &DevOptions::default()).unwrap();
        assert_ne!(first.stage_root, second.stage_root);
        assert_ne!(first.stage_root, legacy);
        assert_ne!(second.stage_root, legacy);
        std::fs::write(second.stage_root.join("keep-second"), b"other instance").unwrap();
        first.cleanup();
        assert!(!first.stage_root.exists());
        assert_eq!(
            std::fs::read(second.stage_root.join("keep-second")).unwrap(),
            b"other instance"
        );
        assert_eq!(
            std::fs::read(legacy.join("keep-legacy")).unwrap(),
            b"prior owner"
        );
        second.cleanup();
        assert_eq!(
            std::fs::read(legacy.join("keep-legacy")).unwrap(),
            b"prior owner"
        );
    }

    fn initial_project(source: &str) -> tempfile::TempDir {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("src")).unwrap();
        std::fs::write(temp.path().join("src/lib.rs"), source).unwrap();
        std::fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"stage-fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n[lib]\ncrate-type = [\"cdylib\"]\n[workspace]\n",
        ).unwrap();
        #[cfg(target_os = "macos")]
        {
            // cargoc may re-key the output root when this fixture adds a staging
            // blocker. A legitimate rebuild must not change install_name/UUID
            // and make the test confuse linker metadata with cleanup damage.
            std::fs::create_dir(temp.path().join(".cargo")).unwrap();
            std::fs::write(temp.path().join(".cargo/config.toml"),
                "[build]\nrustflags = [\"-C\", \"link-arg=-Wl,-no_uuid\", \"-C\", \"link-arg=-Wl,-install_name,@rpath/libstage_fixture.dylib\"]\n",
            ).unwrap();
        }
        temp
    }

    #[test]
    fn initial_build_failure_discards_only_its_unloaded_namespace() {
        let temp = initial_project("this is intentionally invalid Rust\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let own = dev.stage_root.clone();
        let other = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let old = own.parent().unwrap().join("stage-fixture-old-pid");
        std::fs::create_dir(&old).unwrap();
        for path in [&other.stage_root, &old] {
            std::fs::write(path.join("keep"), b"not the failed preparation").unwrap();
        }
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("cargo build"), "{error}");
        assert!(!own.exists());
        for path in [&other.stage_root, &old] {
            assert_eq!(
                std::fs::read(path.join("keep")).unwrap(),
                b"not the failed preparation"
            );
        }
    }

    #[test]
    fn initial_staging_failure_after_real_build_discards_partial_stage() {
        let temp = initial_project("pub fn fixture() {}\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let own = dev.stage_root.clone();
        // Block the first generation directory after Cargo has actually built.
        std::fs::write(own.join("1"), b"incomplete initial preparation").unwrap();
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("could not create"), "{error}");
        assert!(!own.exists());
    }

    #[test]
    fn initial_copy_failure_after_real_build_preserves_other_owners() {
        let temp = initial_project("pub fn fixture() {}\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        // Discover the actual Cargo DLL name; block only the copy destination,
        // not creation of the generation directory or compilation of the DLL.
        let artifact = build_cdylib(&dev.project, dev.release).unwrap();
        let own = dev.stage_root.clone();
        let blocked = own.join("1").join(artifact.file_name().unwrap());
        std::fs::create_dir_all(&blocked).unwrap();
        let other = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let legacy = own.parent().unwrap().join("stage-fixture-legacy-copy");
        std::fs::create_dir(&legacy).unwrap();
        for path in [&other.stage_root, &legacy] {
            std::fs::write(path.join("keep"), b"not this preparation").unwrap();
        }
        let artifact_bytes = std::fs::read(&artifact).unwrap();
        assert!(!artifact_bytes.is_empty());
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("could not stage extension"), "{error}");
        assert!(error.contains(blocked.to_str().unwrap()), "{error}");
        assert!(!own.exists());
        assert_eq!(std::fs::read(artifact).unwrap(), artifact_bytes);
        for path in [&other.stage_root, &legacy] {
            assert_eq!(
                std::fs::read(path.join("keep")).unwrap(),
                b"not this preparation"
            );
        }
    }

    #[test]
    fn initial_preparation_refuses_shared_ownership_without_deleting_files() {
        let temp = initial_project("unused before ownership validation\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let shared = dev.clone();
        let sentinel = shared.stage_root.join("keep");
        std::fs::write(&sentinel, b"shared namespace").unwrap();
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("exclusive ownership"));
        assert_eq!(std::fs::read(sentinel).unwrap(), b"shared namespace");
    }

    #[test]
    fn initial_preparation_refuses_weak_observers_without_deleting_files() {
        let temp = initial_project("unused before ownership validation\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let observer = Arc::downgrade(&dev);
        let sentinel = dev.stage_root.join("keep");
        std::fs::write(&sentinel, b"possibly observed by watcher").unwrap();
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("exclusive ownership"));
        assert_eq!(
            std::fs::read(sentinel).unwrap(),
            b"possibly observed by watcher"
        );
        drop(observer);
    }

    #[test]
    fn initial_success_commits_same_owner_and_reprepare_keeps_built_artifact() {
        let temp = initial_project("pub fn fixture() {}\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let identity = Arc::as_ptr(&dev);
        let mut args = Args::default();
        let prepared = dev.prepare_initial(&mut args).unwrap();
        assert_eq!(Arc::as_ptr(&prepared), identity);
        let stage = prepared.current_stage.lock().unwrap().clone().unwrap();
        assert_eq!(args.extensions_dir.last(), Some(&stage));
        let artifact = std::fs::read_dir(&stage)
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
            .path();
        let bytes = std::fs::read(&artifact).unwrap();
        assert!(!bytes.is_empty());
        let error = prepared.prepare_initial(&mut args).err().unwrap();
        assert!(error.contains("unbuilt instance"));
        assert_eq!(std::fs::read(artifact).unwrap(), bytes);
    }

    #[test]
    fn initial_cleanup_error_preserves_build_error_and_reports_remaining_path() {
        let temp = initial_project("this is intentionally invalid Rust\n");
        let dev = DevExtension::detect(temp.path(), &DevOptions::default()).unwrap();
        let own = dev.stage_root.clone();
        // A non-directory cannot be discarded as our original owner directory.
        std::fs::remove_dir(&own).unwrap();
        std::fs::write(&own, b"do not silently unlink a replacement").unwrap();
        let error = dev.prepare_initial(&mut Args::default()).err().unwrap();
        assert!(error.contains("cargo build"), "{error}");
        assert!(error.contains("Initial staging cleanup failed"), "{error}");
        assert!(error.contains(own.to_str().unwrap()), "{error}");
        assert_eq!(
            std::fs::read(&own).unwrap(),
            b"do not silently unlink a replacement"
        );
    }

    #[test]
    fn cleanup_helper_rejects_non_dev_paths() {
        assert!(!is_dev_stage_root(Path::new("target/debug")));
        assert!(is_dev_stage_root(Path::new(
            "workspace/.rpi/extensions/.dev/example-123"
        )));
    }
}