spool-memory 0.2.3

Local-first developer memory system — persistent, structured knowledge for AI coding tools
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
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
//! Cursor AI installer adapter.
//!
//! ## What we touch
//! - `~/.cursor/mcp.json`       — `mcpServers.spool` entry
//! - `~/.cursor/settings.json`  — hook entries under `cursor.hooks`
//! - `~/.cursor/hooks/spool-*.sh` — two hook scripts
//!
//! ## Cursor hook format
//! Cursor uses a settings.json with the shape:
//! ```json
//! {
//!   "cursor.hooks": {
//!     "onSessionStart": [{"command": "...", "timeout": 5000}],
//!     "onSessionEnd":   [{"command": "...", "timeout": 10000}]
//!   }
//! }
//! ```
//!
//! Unlike Claude Code (which wraps each entry in a `{matcher, hooks: [...]}`
//! envelope) and Codex (flat `hooks.json`), Cursor puts hooks inside its
//! main settings.json under the `cursor.hooks` namespace.
//!
//! ## Binary resolution
//! Same strategy as Claude/Codex: default to `~/.cargo/bin/spool-mcp`,
//! with `--binary-path` as an escape hatch.

use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

use super::shared::{
    self, McpMergeOutcome, McpRemoveOutcome, build_mcp_entry, merge_mcp_entry, remove_mcp_entry,
};
use super::templates::{self, cursor_hook_specs};
use super::{
    ClientId, DiagnosticCheck, DiagnosticReport, DiagnosticStatus, InstallContext, InstallReport,
    InstallStatus, Installer, UninstallReport, UninstallStatus, UpdateReport, UpdateStatus,
};

/// Default timeout for onSessionStart hooks (ms).
const HOOK_TIMEOUT_DEFAULT_MS: u64 = 5000;
/// Longer timeout for onSessionEnd (distill pipeline may take longer).
const HOOK_TIMEOUT_SESSION_END_MS: u64 = 10000;

pub struct CursorInstaller {
    home_override: Option<PathBuf>,
}

impl CursorInstaller {
    pub fn new() -> Self {
        Self {
            home_override: None,
        }
    }

    #[doc(hidden)]
    pub fn with_home_root(root: PathBuf) -> Self {
        Self {
            home_override: Some(root),
        }
    }

    fn home(&self) -> Result<PathBuf> {
        match &self.home_override {
            Some(p) => Ok(p.clone()),
            None => shared::home_dir(),
        }
    }

    fn cursor_dir(&self) -> Result<PathBuf> {
        Ok(self.home()?.join(".cursor"))
    }

    fn mcp_json_path(&self) -> Result<PathBuf> {
        Ok(self.cursor_dir()?.join("mcp.json"))
    }

    fn settings_json_path(&self) -> Result<PathBuf> {
        Ok(self.cursor_dir()?.join("settings.json"))
    }

    fn hooks_dir(&self) -> Result<PathBuf> {
        Ok(self.cursor_dir()?.join("hooks"))
    }

    fn default_binary_path(&self) -> Result<PathBuf> {
        Ok(self.home()?.join(".cargo").join("bin").join("spool-mcp"))
    }

    fn resolve_binary_path(&self, ctx: &InstallContext) -> Result<PathBuf> {
        match &ctx.binary_path {
            Some(p) => Ok(p.clone()),
            None => self.default_binary_path(),
        }
    }

    fn validate_inputs(&self, ctx: &InstallContext, binary_path: &Path) -> Result<()> {
        if !ctx.config_path.is_absolute() {
            anyhow::bail!(
                "config path must be absolute, got: {}",
                ctx.config_path.display()
            );
        }
        if !binary_path.is_absolute() {
            anyhow::bail!(
                "binary path must be absolute, got: {}",
                binary_path.display()
            );
        }
        Ok(())
    }
}

impl Default for CursorInstaller {
    fn default() -> Self {
        Self::new()
    }
}

impl Installer for CursorInstaller {
    fn id(&self) -> ClientId {
        ClientId::Cursor
    }

    fn detect(&self) -> Result<bool> {
        let cursor_dir = self.cursor_dir()?;
        Ok(cursor_dir.exists())
    }

    fn install(&self, ctx: &InstallContext) -> Result<InstallReport> {
        let binary_path = self.resolve_binary_path(ctx)?;
        self.validate_inputs(ctx, &binary_path)?;

        let mut planned_writes: Vec<PathBuf> = Vec::new();
        let mut backups: Vec<PathBuf> = Vec::new();
        let mut notes: Vec<String> = Vec::new();

        // ── 1. mcpServers entry in ~/.cursor/mcp.json ────────────
        let mcp_json = self.mcp_json_path()?;
        let mut mcp_doc = shared::read_json_or_empty(&mcp_json)?;
        let desired = build_mcp_entry(&binary_path, &ctx.config_path);
        let mcp_outcome = merge_mcp_entry(&mut mcp_doc, "spool", desired, ctx.force);

        if !binary_path.exists() {
            notes.push(format!(
                "spool-mcp binary not found at {}. Run `cargo install --path .` or pass --binary-path.",
                binary_path.display()
            ));
        }

        let mcp_status = match mcp_outcome {
            McpMergeOutcome::Inserted => MergeStatus::Changed,
            McpMergeOutcome::Unchanged => MergeStatus::Unchanged,
            McpMergeOutcome::Conflict {
                force_applied: true,
            } => {
                notes.push(format!(
                    "Existing spool mcpServers entry was overwritten (force=true). Backup at {}.",
                    mcp_json.display()
                ));
                MergeStatus::Changed
            }
            McpMergeOutcome::Conflict {
                force_applied: false,
            } => {
                notes.push(
                    "Existing spool mcpServers entry differs. Re-run with --force to overwrite, or `spool mcp uninstall` first.".to_string(),
                );
                MergeStatus::Conflict
            }
        };

        if matches!(mcp_status, MergeStatus::Conflict) {
            return Ok(InstallReport {
                client: ClientId::Cursor.as_str().to_string(),
                binary_path,
                config_path: ctx.config_path.clone(),
                status: InstallStatus::Conflict,
                planned_writes,
                backups,
                notes,
            });
        }

        // ── 2. settings.json hook entries ────────────────────────
        let settings_json = self.settings_json_path()?;
        let mut settings_doc = shared::read_json_or_empty(&settings_json)?;
        let hooks_dir = self.hooks_dir()?;
        let hook_specs = cursor_hook_specs();
        let mut settings_changed = false;
        for spec in &hook_specs {
            let target_path = hooks_dir.join(spec.file_name);
            let target_str = target_path.to_string_lossy().into_owned();
            let timeout = timeout_for_event(spec.hook_event);
            match upsert_cursor_hook_entry(&mut settings_doc, spec.hook_event, &target_str, timeout)
            {
                CursorHookOutcome::Appended => settings_changed = true,
                CursorHookOutcome::Unchanged => {}
            }
        }

        // ── 3. plan hook script writes ───────────────────────────
        let spool_bin_for_hook = templates::bin_path_for_hook(&binary_path);
        let hook_files: Vec<HookFilePlan> = hook_specs
            .iter()
            .map(|spec| HookFilePlan {
                target_path: hooks_dir.join(spec.file_name),
                rendered: templates::render_hook(spec.body, &spool_bin_for_hook, &ctx.config_path),
            })
            .collect();
        let hook_files_changed = hook_files
            .iter()
            .any(|p| !file_has_exact_contents(&p.target_path, &p.rendered));

        // ── 4. dry-run preview ───────────────────────────────────
        let any_change =
            matches!(mcp_status, MergeStatus::Changed) || settings_changed || hook_files_changed;

        if ctx.dry_run {
            if matches!(mcp_status, MergeStatus::Changed) {
                planned_writes.push(mcp_json.clone());
            }
            if settings_changed {
                planned_writes.push(settings_json.clone());
            }
            for plan in &hook_files {
                if !file_has_exact_contents(&plan.target_path, &plan.rendered) {
                    planned_writes.push(plan.target_path.clone());
                }
            }
            return Ok(InstallReport {
                client: ClientId::Cursor.as_str().to_string(),
                binary_path,
                config_path: ctx.config_path.clone(),
                status: if any_change {
                    InstallStatus::DryRun
                } else {
                    InstallStatus::Unchanged
                },
                planned_writes,
                backups,
                notes,
            });
        }

        // ── 5. apply mcpServers ──────────────────────────────────
        if matches!(mcp_status, MergeStatus::Changed) {
            if let Some(b) = shared::backup_file(&mcp_json)
                .with_context(|| format!("backing up {}", mcp_json.display()))?
            {
                backups.push(b);
            }
            shared::write_json_atomic(&mcp_json, &mcp_doc)
                .with_context(|| format!("writing {}", mcp_json.display()))?;
            planned_writes.push(mcp_json.clone());
        }

        // ── 6. apply settings.json ──────────────────────────────
        if settings_changed {
            if let Some(b) = shared::backup_file(&settings_json)
                .with_context(|| format!("backing up {}", settings_json.display()))?
            {
                backups.push(b);
            }
            shared::write_json_atomic(&settings_json, &settings_doc)
                .with_context(|| format!("writing {}", settings_json.display()))?;
            planned_writes.push(settings_json.clone());
        }

        // ── 7. apply hook script files ───────────────────────────
        if !hooks_dir.exists() {
            std::fs::create_dir_all(&hooks_dir)
                .with_context(|| format!("creating {}", hooks_dir.display()))?;
        }
        for plan in &hook_files {
            if file_has_exact_contents(&plan.target_path, &plan.rendered) {
                continue;
            }
            std::fs::write(&plan.target_path, &plan.rendered)
                .with_context(|| format!("writing {}", plan.target_path.display()))?;
            set_executable(&plan.target_path)?;
            planned_writes.push(plan.target_path.clone());
        }

        let final_status = if any_change {
            InstallStatus::Installed
        } else {
            InstallStatus::Unchanged
        };

        Ok(InstallReport {
            client: ClientId::Cursor.as_str().to_string(),
            binary_path,
            config_path: ctx.config_path.clone(),
            status: final_status,
            planned_writes,
            backups,
            notes,
        })
    }

    fn update(&self, ctx: &InstallContext) -> Result<UpdateReport> {
        let report = self.install(ctx)?;
        let status = match report.status {
            InstallStatus::Installed => UpdateStatus::Updated,
            InstallStatus::Unchanged => UpdateStatus::Unchanged,
            InstallStatus::DryRun => UpdateStatus::DryRun,
            InstallStatus::Conflict => UpdateStatus::NotInstalled,
        };
        Ok(UpdateReport {
            client: report.client,
            status,
            updated_paths: report.planned_writes,
            notes: report.notes,
        })
    }

    fn uninstall(&self, ctx: &InstallContext) -> Result<UninstallReport> {
        let mcp_json = self.mcp_json_path()?;
        let settings_json = self.settings_json_path()?;
        let hooks_dir = self.hooks_dir()?;

        let mut notes: Vec<String> = Vec::new();
        let mut removed_paths: Vec<PathBuf> = Vec::new();
        let mut backups: Vec<PathBuf> = Vec::new();
        let mut any_change = false;

        // ── 1. mcpServers ────────────────────────────────────────
        let mcp_doc_after_purge = if mcp_json.exists() {
            let mut doc = shared::read_json_or_empty(&mcp_json)?;
            match remove_mcp_entry(&mut doc, "spool") {
                McpRemoveOutcome::Removed => {
                    any_change = true;
                    Some(doc)
                }
                McpRemoveOutcome::NotPresent => None,
            }
        } else {
            None
        };

        // ── 2. settings.json purge ───────────────────────────────
        let settings_doc_after_purge = if settings_json.exists() {
            let mut doc = shared::read_json_or_empty(&settings_json)?;
            let removed = purge_cursor_hook_entries(&mut doc, "spool-");
            if removed > 0 {
                any_change = true;
                Some(doc)
            } else {
                None
            }
        } else {
            None
        };

        // ── 3. plan file removals ────────────────────────────────
        let hook_files: Vec<PathBuf> = cursor_hook_specs()
            .iter()
            .map(|s| hooks_dir.join(s.file_name))
            .filter(|p| p.exists())
            .collect();
        if !hook_files.is_empty() {
            any_change = true;
        }

        if !any_change {
            notes.push("nothing to uninstall — no spool artifacts found.".to_string());
            return Ok(UninstallReport {
                client: ClientId::Cursor.as_str().to_string(),
                status: UninstallStatus::NotInstalled,
                removed_paths,
                backups,
                notes,
            });
        }

        if ctx.dry_run {
            if mcp_doc_after_purge.is_some() {
                removed_paths.push(mcp_json);
            }
            if settings_doc_after_purge.is_some() {
                removed_paths.push(settings_json);
            }
            removed_paths.extend(hook_files);
            return Ok(UninstallReport {
                client: ClientId::Cursor.as_str().to_string(),
                status: UninstallStatus::DryRun,
                removed_paths,
                backups,
                notes,
            });
        }

        // ── 4. apply mcpServers purge ────────────────────────────
        if let Some(doc) = mcp_doc_after_purge {
            if let Some(b) = shared::backup_file(&mcp_json)? {
                backups.push(b);
            }
            shared::write_json_atomic(&mcp_json, &doc)?;
            removed_paths.push(mcp_json);
        }

        // ── 5. apply settings.json purge ─────────────────────────
        if let Some(doc) = settings_doc_after_purge {
            if let Some(b) = shared::backup_file(&settings_json)? {
                backups.push(b);
            }
            shared::write_json_atomic(&settings_json, &doc)?;
            removed_paths.push(settings_json);
        }

        // ── 6. delete hook scripts ───────────────────────────────
        for p in hook_files {
            std::fs::remove_file(&p).with_context(|| format!("removing {}", p.display()))?;
            removed_paths.push(p);
        }

        Ok(UninstallReport {
            client: ClientId::Cursor.as_str().to_string(),
            status: UninstallStatus::Removed,
            removed_paths,
            backups,
            notes,
        })
    }

    fn diagnose(&self, ctx: &InstallContext) -> Result<DiagnosticReport> {
        let mut checks = Vec::new();

        // Cursor dir presence
        let cursor_dir = self.cursor_dir()?;
        checks.push(DiagnosticCheck {
            name: "cursor_dir_exists".into(),
            status: if cursor_dir.exists() {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Warn
            },
            detail: format!("{}", cursor_dir.display()),
        });

        // mcpServers.spool registration
        let mcp_json = self.mcp_json_path()?;
        let registration_status = if mcp_json.exists() {
            let doc = shared::read_json_or_empty(&mcp_json)?;
            if doc.get("mcpServers").and_then(|v| v.get("spool")).is_some() {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Warn
            }
        } else {
            DiagnosticStatus::NotApplicable
        };
        checks.push(DiagnosticCheck {
            name: "mcp_servers_spool_registered".into(),
            status: registration_status,
            detail: "mcpServers.spool entry presence".into(),
        });

        // Binary path
        let binary_path = self.resolve_binary_path(ctx)?;
        checks.push(DiagnosticCheck {
            name: "spool_mcp_binary".into(),
            status: if binary_path.exists() {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Fail
            },
            detail: format!("{}", binary_path.display()),
        });

        // Config TOML readable
        checks.push(DiagnosticCheck {
            name: "spool_config_readable".into(),
            status: if ctx.config_path.exists() {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Fail
            },
            detail: format!("{}", ctx.config_path.display()),
        });

        // settings.json has spool hook entries
        let settings_json = self.settings_json_path()?;
        let hooks_registered_status = if settings_json.exists() {
            let doc = shared::read_json_or_empty(&settings_json)?;
            if has_any_spool_cursor_hook(&doc) {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Warn
            }
        } else {
            DiagnosticStatus::Warn
        };
        checks.push(DiagnosticCheck {
            name: "cursor_hooks_registered".into(),
            status: hooks_registered_status,
            detail: format!("{}", settings_json.display()),
        });

        // hook script files present
        let hooks_dir = self.hooks_dir()?;
        let mut missing: Vec<String> = Vec::new();
        for spec in cursor_hook_specs() {
            let p = hooks_dir.join(spec.file_name);
            if !p.exists() {
                missing.push(spec.file_name.to_string());
            }
        }
        let hook_files_detail = if missing.is_empty() {
            format!("{} (2/2 present)", hooks_dir.display())
        } else {
            format!("{} missing: {}", hooks_dir.display(), missing.join(", "))
        };
        checks.push(DiagnosticCheck {
            name: "spool_hook_scripts".into(),
            status: if missing.is_empty() {
                DiagnosticStatus::Ok
            } else {
                DiagnosticStatus::Warn
            },
            detail: hook_files_detail,
        });

        Ok(DiagnosticReport {
            client: ClientId::Cursor.as_str().to_string(),
            checks,
        })
    }
}

// ─────────────────────────────────────────────────────────────────────
// internal helpers
// ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MergeStatus {
    Changed,
    Unchanged,
    Conflict,
}

struct HookFilePlan {
    target_path: PathBuf,
    rendered: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum CursorHookOutcome {
    Appended,
    Unchanged,
}

fn timeout_for_event(event: &str) -> u64 {
    match event {
        "onSessionEnd" => HOOK_TIMEOUT_SESSION_END_MS,
        _ => HOOK_TIMEOUT_DEFAULT_MS,
    }
}

/// Ensure `doc["cursor.hooks"][event]` contains an entry with `command_path`.
/// Cursor hook entries are: `{"command": "...", "timeout": N}`.
fn upsert_cursor_hook_entry(
    doc: &mut Value,
    event: &str,
    command_path: &str,
    timeout_ms: u64,
) -> CursorHookOutcome {
    let root = match doc.as_object_mut() {
        Some(obj) => obj,
        None => {
            *doc = json!({});
            doc.as_object_mut().expect("just inserted")
        }
    };
    let cursor_hooks = root.entry("cursor.hooks").or_insert_with(|| json!({}));
    if !cursor_hooks.is_object() {
        *cursor_hooks = json!({});
    }
    let hooks_obj = cursor_hooks
        .as_object_mut()
        .expect("cursor.hooks must be object");
    let entries = hooks_obj
        .entry(event)
        .or_insert_with(|| Value::Array(Vec::new()));
    if !entries.is_array() {
        *entries = Value::Array(Vec::new());
    }
    let array = entries.as_array_mut().expect("entries must be array");

    for entry in array.iter() {
        if entry.get("command").and_then(Value::as_str) == Some(command_path) {
            return CursorHookOutcome::Unchanged;
        }
    }

    array.push(json!({
        "command": command_path,
        "timeout": timeout_ms,
    }));
    CursorHookOutcome::Appended
}

/// Remove entries from `doc["cursor.hooks"][event]` whose `command`
/// contains `marker_substring`. Returns the number of entries removed.
fn purge_cursor_hook_entries(doc: &mut Value, marker_substring: &str) -> usize {
    let mut removed = 0usize;
    let Some(root) = doc.as_object_mut() else {
        return 0;
    };
    let Some(cursor_hooks) = root.get_mut("cursor.hooks").and_then(|v| v.as_object_mut()) else {
        return 0;
    };
    for (_event, entries) in cursor_hooks.iter_mut() {
        let Some(array) = entries.as_array_mut() else {
            continue;
        };
        let before = array.len();
        array.retain(|entry| {
            !entry
                .get("command")
                .and_then(Value::as_str)
                .is_some_and(|c| c.contains(marker_substring))
        });
        removed += before - array.len();
    }
    cursor_hooks.retain(|_event, entries| !entries.as_array().is_some_and(|a| a.is_empty()));
    if cursor_hooks.is_empty() {
        root.remove("cursor.hooks");
    }
    removed
}

fn has_any_spool_cursor_hook(doc: &Value) -> bool {
    let Some(cursor_hooks) = doc.get("cursor.hooks").and_then(|v| v.as_object()) else {
        return false;
    };
    for entries in cursor_hooks.values() {
        let Some(arr) = entries.as_array() else {
            continue;
        };
        for entry in arr {
            if entry
                .get("command")
                .and_then(Value::as_str)
                .is_some_and(|c| c.contains("spool-"))
            {
                return true;
            }
        }
    }
    false
}

fn file_has_exact_contents(path: &Path, expected: &str) -> bool {
    if !path.exists() {
        return false;
    }
    match std::fs::read_to_string(path) {
        Ok(actual) => actual == expected,
        Err(_) => false,
    }
}

#[cfg(unix)]
fn set_executable(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)
        .with_context(|| format!("stat {}", path.display()))?
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).with_context(|| format!("chmod {}", path.display()))?;
    Ok(())
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn setup() -> (tempfile::TempDir, CursorInstaller, InstallContext) {
        let temp = tempdir().unwrap();
        let home = temp.path().to_path_buf();
        let installer = CursorInstaller::with_home_root(home.clone());

        let config_path = home.join("spool.toml");
        fs::write(&config_path, "[vault]\nroot=\"/tmp\"\n").unwrap();
        let binary_path = home.join("fake-spool-mcp");
        fs::write(&binary_path, "#!/bin/sh\nexit 0\n").unwrap();

        let ctx = InstallContext {
            binary_path: Some(binary_path),
            config_path,
            dry_run: false,
            force: false,
        };
        (temp, installer, ctx)
    }

    #[test]
    fn detect_returns_false_when_no_cursor_dir() {
        let temp = tempdir().unwrap();
        let installer = CursorInstaller::with_home_root(temp.path().to_path_buf());
        assert!(!installer.detect().unwrap());
    }

    #[test]
    fn detect_returns_true_when_cursor_dir_present() {
        let temp = tempdir().unwrap();
        fs::create_dir_all(temp.path().join(".cursor")).unwrap();
        let installer = CursorInstaller::with_home_root(temp.path().to_path_buf());
        assert!(installer.detect().unwrap());
    }

    #[test]
    fn install_creates_mcp_json_and_hooks() {
        let (temp, installer, ctx) = setup();
        let report = installer.install(&ctx).unwrap();
        assert_eq!(report.status, InstallStatus::Installed);

        // mcp.json written with mcpServers.spool
        let mcp_json = temp.path().join(".cursor").join("mcp.json");
        assert!(mcp_json.exists());
        let doc: Value = serde_json::from_str(&fs::read_to_string(&mcp_json).unwrap()).unwrap();
        assert!(doc["mcpServers"]["spool"].is_object());

        // settings.json written with cursor.hooks
        let settings_json = temp.path().join(".cursor").join("settings.json");
        assert!(settings_json.exists());
        let settings_doc: Value =
            serde_json::from_str(&fs::read_to_string(&settings_json).unwrap()).unwrap();
        assert!(settings_doc["cursor.hooks"]["onSessionStart"].is_array());
        assert!(settings_doc["cursor.hooks"]["onSessionEnd"].is_array());

        // onSessionEnd has longer timeout
        let end_entry = &settings_doc["cursor.hooks"]["onSessionEnd"][0];
        assert_eq!(end_entry["timeout"], HOOK_TIMEOUT_SESSION_END_MS);

        // hook script files exist
        for spec in cursor_hook_specs() {
            let p = temp
                .path()
                .join(".cursor")
                .join("hooks")
                .join(spec.file_name);
            assert!(p.exists(), "{} missing", p.display());
        }
    }

    #[test]
    fn install_dry_run_does_not_write() {
        let (temp, installer, mut ctx) = setup();
        ctx.dry_run = true;
        let report = installer.install(&ctx).unwrap();
        assert_eq!(report.status, InstallStatus::DryRun);
        assert!(!report.planned_writes.is_empty());
        assert!(!temp.path().join(".cursor").exists());
    }

    #[test]
    fn install_unchanged_on_repeat() {
        let (_temp, installer, ctx) = setup();
        let _ = installer.install(&ctx).unwrap();
        let second = installer.install(&ctx).unwrap();
        assert_eq!(second.status, InstallStatus::Unchanged);
    }

    #[test]
    fn uninstall_removes_entries() {
        let (temp, installer, ctx) = setup();
        let _ = installer.install(&ctx).unwrap();

        let report = installer.uninstall(&ctx).unwrap();
        assert_eq!(report.status, UninstallStatus::Removed);

        // hook scripts gone
        for spec in cursor_hook_specs() {
            let p = temp
                .path()
                .join(".cursor")
                .join("hooks")
                .join(spec.file_name);
            assert!(!p.exists(), "{} should be removed", p.display());
        }

        // mcpServers.spool gone
        let mcp_json = temp.path().join(".cursor").join("mcp.json");
        let doc: Value = serde_json::from_str(&fs::read_to_string(&mcp_json).unwrap()).unwrap();
        assert!(doc["mcpServers"].get("spool").is_none());
    }

    #[test]
    fn uninstall_not_installed_when_clean() {
        let (_temp, installer, ctx) = setup();
        let report = installer.uninstall(&ctx).unwrap();
        assert_eq!(report.status, UninstallStatus::NotInstalled);
    }

    #[test]
    fn update_unchanged_when_templates_match() {
        let (_temp, installer, ctx) = setup();
        let _ = installer.install(&ctx).unwrap();
        let report = installer.update(&ctx).unwrap();
        assert_eq!(report.status, UpdateStatus::Unchanged);
    }

    #[test]
    fn diagnose_reports_full_check_set_after_install() {
        let (_temp, installer, ctx) = setup();
        let _ = installer.install(&ctx).unwrap();
        let report = installer.diagnose(&ctx).unwrap();
        let names: Vec<&str> = report.checks.iter().map(|c| c.name.as_str()).collect();
        for expected in [
            "cursor_dir_exists",
            "mcp_servers_spool_registered",
            "spool_mcp_binary",
            "spool_config_readable",
            "cursor_hooks_registered",
            "spool_hook_scripts",
        ] {
            assert!(names.contains(&expected), "missing check {}", expected);
        }
    }

    #[cfg(unix)]
    #[test]
    fn install_makes_hook_scripts_executable() {
        use std::os::unix::fs::PermissionsExt;
        let (temp, installer, ctx) = setup();
        let _ = installer.install(&ctx).unwrap();
        let session = temp
            .path()
            .join(".cursor")
            .join("hooks")
            .join("spool-on_session_start.sh");
        let perms = fs::metadata(&session).unwrap().permissions();
        assert_eq!(perms.mode() & 0o777, 0o755);
    }

    #[test]
    fn cursor_hook_entries_use_flat_format_with_timeout() {
        let mut doc = json!({});
        upsert_cursor_hook_entry(
            &mut doc,
            "onSessionStart",
            "/abs/spool-on_session_start.sh",
            5000,
        );
        let entries = doc["cursor.hooks"]["onSessionStart"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0]["command"], "/abs/spool-on_session_start.sh");
        assert_eq!(entries[0]["timeout"], 5000);
    }

    #[test]
    fn upsert_cursor_hook_unchanged_on_repeat() {
        let mut doc = json!({});
        upsert_cursor_hook_entry(&mut doc, "onSessionStart", "/abs/hook.sh", 5000);
        let outcome = upsert_cursor_hook_entry(&mut doc, "onSessionStart", "/abs/hook.sh", 5000);
        assert_eq!(outcome, CursorHookOutcome::Unchanged);
        assert_eq!(
            doc["cursor.hooks"]["onSessionStart"]
                .as_array()
                .unwrap()
                .len(),
            1
        );
    }

    #[test]
    fn purge_cursor_hook_entries_removes_spool_only() {
        let mut doc = json!({
            "cursor.hooks": {
                "onSessionStart": [
                    {"command": "/other/tool", "timeout": 3000},
                    {"command": "/abs/.cursor/hooks/spool-on_session_start.sh", "timeout": 5000}
                ],
                "onSessionEnd": [
                    {"command": "/abs/spool-on_session_end.sh", "timeout": 10000}
                ]
            }
        });
        let removed = purge_cursor_hook_entries(&mut doc, "spool-");
        assert_eq!(removed, 2);
        let entries = doc["cursor.hooks"]["onSessionStart"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0]["command"], "/other/tool");
        // onSessionEnd is now empty → swept.
        assert!(doc["cursor.hooks"].get("onSessionEnd").is_none());
    }
}