vaultdb-core 1.0.0

Library engine for vaultdb — markdown-as-database for Obsidian-style vaults
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
//! Frontmatter write primitives. [`set_field`], [`unset_field`], [`add_tag`],
//! [`remove_tag`] each return `(new_content, ChangeDescription)` without
//! touching disk; [`apply`] flushes a [`WriteResult`] to the filesystem. The
//! public mutation builders in [`crate::mutation`] wrap these.

use crate::error::{Result, VaultdbError};

/// Describes a single change made to a file.
#[derive(Debug)]
pub enum ChangeDescription {
    SetField {
        field: String,
        old_value: String,
        new_value: String,
    },
    UnsetField {
        field: String,
        old_value: String,
    },
    AddTag {
        tag: String,
    },
    RemoveTag {
        tag: String,
    },
}

impl std::fmt::Display for ChangeDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChangeDescription::SetField {
                field,
                old_value,
                new_value,
            } => write!(f, "set {} = {} (was: {})", field, new_value, old_value),
            ChangeDescription::UnsetField { field, old_value } => {
                write!(f, "unset {} (was: {})", field, old_value)
            }
            ChangeDescription::AddTag { tag } => write!(f, "add tag: {}", tag),
            ChangeDescription::RemoveTag { tag } => write!(f, "remove tag: {}", tag),
        }
    }
}

/// Result of a write operation on a single file.
pub struct WriteResult {
    pub path: std::path::PathBuf,
    pub original_content: String,
    pub modified_content: String,
    pub changes: Vec<ChangeDescription>,
}

/// Split file content into frontmatter lines and body.
/// Returns (frontmatter_lines_including_delimiters, body_str).
fn split_frontmatter(content: &str) -> Result<(Vec<&str>, &str)> {
    let lines: Vec<&str> = content.lines().collect();

    if lines.is_empty() || lines[0].trim() != "---" {
        return Err(VaultdbError::NoFrontmatter("content".into()));
    }

    // Find closing ---
    let close_idx = lines[1..]
        .iter()
        .position(|l| l.trim() == "---")
        .map(|i| i + 1); // offset by 1 because we started from lines[1..]

    match close_idx {
        Some(idx) => {
            let fm_lines = &lines[..=idx];
            // Body starts after the closing --- line
            // We need to find the byte offset of the body
            let mut byte_offset = 0;
            for (i, line) in content.lines().enumerate() {
                byte_offset += line.len();
                // Account for the newline character
                if byte_offset < content.len() {
                    if content.as_bytes().get(byte_offset) == Some(&b'\r') {
                        byte_offset += 1; // \r
                    }
                    if byte_offset < content.len() {
                        byte_offset += 1; // \n
                    }
                }
                if i == idx {
                    break;
                }
            }
            let body = &content[byte_offset..];
            Ok((fm_lines.to_vec(), body))
        }
        None => Err(VaultdbError::NoFrontmatter("content".into())),
    }
}

/// Detect the indentation used for list items under a key.
/// Returns the prefix string (e.g., "  - " or "- ").
fn detect_list_indent(fm_lines: &[&str], key_line_idx: usize) -> String {
    // Look at the line after the key line
    for line in fm_lines.iter().skip(key_line_idx + 1) {
        let trimmed = line.trim();

        // Stop if we hit another top-level key or delimiter
        if trimmed == "---"
            || (!line.starts_with(' ') && !line.starts_with('-') && trimmed.contains(':'))
        {
            break;
        }

        if trimmed.starts_with("- ") || trimmed == "-" {
            // Return the actual prefix including whitespace
            let dash_pos = line.find('-').unwrap();
            let prefix = &line[..dash_pos];
            return format!("{}- ", prefix);
        }
    }
    // Default: 2-space indent
    "  - ".to_string()
}

/// Find the line index of a top-level key in frontmatter lines (between delimiters).
fn find_key_line(fm_lines: &[&str], key: &str) -> Option<usize> {
    let patterns = [format!("{}:", key), format!("{} :", key)];
    for (i, line) in fm_lines.iter().enumerate() {
        if i == 0 || line.trim() == "---" {
            continue; // skip delimiters
        }
        let trimmed = line.trim_start();
        for pattern in &patterns {
            if trimmed.starts_with(pattern) {
                // Make sure we matched the full key, not a prefix
                let after = &trimmed[pattern.len()..];
                if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
                    return Some(i);
                }
            }
        }
    }
    None
}

/// Determine how many lines a field spans (including nested list/map items).
fn field_extent(fm_lines: &[&str], key_line_idx: usize) -> usize {
    let key_line = fm_lines[key_line_idx];
    let key_indent = key_line.len() - key_line.trim_start().len();

    // Check if the key has an inline value (not a list/map)
    let after_colon = key_line.trim_start();
    if let Some(colon_pos) = after_colon.find(':') {
        let value_part = after_colon[colon_pos + 1..].trim();
        if !value_part.is_empty() && !value_part.starts_with('[') && !value_part.starts_with('{') {
            // Inline scalar value — single line
            return 1;
        }
    }

    let mut extent = 1;
    for line in fm_lines.iter().skip(key_line_idx + 1) {
        let trimmed = line.trim();

        // Stop at closing delimiter
        if trimmed == "---" {
            break;
        }

        // Empty line ends the field
        if trimmed.is_empty() {
            break;
        }

        let line_indent = line.len() - line.trim_start().len();

        // If this line is at the same or lesser indentation and doesn't start with '-',
        // it's a new top-level key
        if line_indent <= key_indent && !trimmed.starts_with('-') {
            break;
        }

        // Lines starting with '-' at the same indent level are list items of this key
        if line_indent == key_indent && trimmed.starts_with('-') {
            extent += 1;
            continue;
        }

        // Indented lines are continuations
        if line_indent > key_indent {
            extent += 1;
            continue;
        }

        break;
    }
    extent
}

/// Check if a field line uses flow-style list syntax: `key: [a, b, c]`
fn is_flow_style_list(line: &str) -> bool {
    if let Some(colon_pos) = line.find(':') {
        let value = line[colon_pos + 1..].trim();
        value.starts_with('[') && value.ends_with(']')
    } else {
        false
    }
}

/// Check if a field line uses a multiline scalar indicator: `key: |` or `key: >`
fn is_multiline_scalar(line: &str) -> bool {
    if let Some(colon_pos) = line.find(':') {
        let value = line[colon_pos + 1..].trim();
        value == "|"
            || value == ">"
            || value == "|+"
            || value == "|-"
            || value == ">+"
            || value == ">-"
    } else {
        false
    }
}

/// Quote a YAML value if it contains special characters.
pub fn quote_value(value: &str) -> String {
    yaml_quote_value(value)
}

fn yaml_quote_value(value: &str) -> String {
    let needs_quoting = value.contains(':')
        || value.contains('#')
        || value.contains('[')
        || value.contains(']')
        || value.contains('{')
        || value.contains('}')
        || value.contains('\'')
        || value.contains('"')
        || value.contains('&')
        || value.contains('*')
        || value.contains('!')
        || value.contains('|')
        || value.contains('>')
        || value.contains('%')
        || value.contains('@')
        || value.starts_with(' ')
        || value.ends_with(' ')
        || value.starts_with('-')
        || value.starts_with('?');

    if needs_quoting {
        if value.contains('\'') {
            format!("\"{}\"", value.replace('"', "\\\""))
        } else {
            format!("'{}'", value)
        }
    } else {
        value.to_string()
    }
}

/// Set a scalar field to a new value in the frontmatter.
pub fn set_field(content: &str, key: &str, value: &str) -> Result<(String, ChangeDescription)> {
    let (fm_lines, body) = split_frontmatter(content)?;
    let quoted_value = yaml_quote_value(value);

    if let Some(key_idx) = find_key_line(&fm_lines, key) {
        let extent = field_extent(&fm_lines, key_idx);
        if extent > 1 {
            return Err(VaultdbError::InvalidFrontmatter {
                file: String::new(),
                reason: format!(
                    "field '{}' is a complex type (list/map). Use --unset first, then re-add.",
                    key
                ),
            });
        }

        if is_flow_style_list(fm_lines[key_idx]) {
            return Err(VaultdbError::InvalidFrontmatter {
                file: String::new(),
                reason: format!(
                    "field '{}' uses flow-style YAML (e.g., [a, b]). Use --unset first, then re-add.",
                    key
                ),
            });
        }

        if is_multiline_scalar(fm_lines[key_idx]) {
            return Err(VaultdbError::InvalidFrontmatter {
                file: String::new(),
                reason: format!(
                    "field '{}' uses a multiline scalar (| or >). Use --unset first, then re-add.",
                    key
                ),
            });
        }

        let old_line = fm_lines[key_idx];
        // Extract old value for the change description
        let old_value = old_line
            .find(':')
            .map(|pos| old_line[pos + 1..].trim())
            .unwrap_or("")
            .to_string();

        let new_line = format!("{}: {}", key, quoted_value);

        let mut result_lines: Vec<String> = Vec::new();
        for (i, line) in fm_lines.iter().enumerate() {
            if i == key_idx {
                result_lines.push(new_line.clone());
            } else {
                result_lines.push(line.to_string());
            }
        }

        let change = ChangeDescription::SetField {
            field: key.to_string(),
            old_value,
            new_value: value.to_string(),
        };

        Ok((reassemble(&result_lines, body, content), change))
    } else {
        // Key doesn't exist — insert before closing ---
        let mut result_lines: Vec<String> = Vec::new();
        for (i, line) in fm_lines.iter().enumerate() {
            if i == fm_lines.len() - 1 && line.trim() == "---" {
                result_lines.push(format!("{}: {}", key, quoted_value));
            }
            result_lines.push(line.to_string());
        }

        let change = ChangeDescription::SetField {
            field: key.to_string(),
            old_value: String::new(),
            new_value: value.to_string(),
        };

        Ok((reassemble(&result_lines, body, content), change))
    }
}

/// Remove a field entirely from the frontmatter.
pub fn unset_field(content: &str, key: &str) -> Result<(String, ChangeDescription)> {
    let (fm_lines, body) = split_frontmatter(content)?;

    let key_idx =
        find_key_line(&fm_lines, key).ok_or_else(|| VaultdbError::InvalidFrontmatter {
            file: String::new(),
            reason: format!("field '{}' not found", key),
        })?;

    let extent = field_extent(&fm_lines, key_idx);
    let old_value = fm_lines[key_idx]
        .find(':')
        .map(|pos| fm_lines[key_idx][pos + 1..].trim())
        .unwrap_or("")
        .to_string();

    let mut result_lines: Vec<String> = Vec::new();
    for (i, line) in fm_lines.iter().enumerate() {
        if i >= key_idx && i < key_idx + extent {
            continue; // skip this field's lines
        }
        result_lines.push(line.to_string());
    }

    let change = ChangeDescription::UnsetField {
        field: key.to_string(),
        old_value,
    };

    Ok((reassemble(&result_lines, body, content), change))
}

/// Add a tag to the tags list.
pub fn add_tag(content: &str, tag: &str) -> Result<(String, ChangeDescription)> {
    let (fm_lines, body) = split_frontmatter(content)?;

    let key_idx =
        find_key_line(&fm_lines, "tags").ok_or_else(|| VaultdbError::InvalidFrontmatter {
            file: String::new(),
            reason: "no 'tags' field found".into(),
        })?;

    if is_flow_style_list(fm_lines[key_idx]) {
        return Err(VaultdbError::InvalidFrontmatter {
            file: String::new(),
            reason: "tags field uses flow-style YAML (e.g., tags: [a, b]). Convert to block-style first.".into(),
        });
    }

    let indent_prefix = detect_list_indent(&fm_lines, key_idx);
    let extent = field_extent(&fm_lines, key_idx);
    let insert_after = key_idx + extent - 1; // last line of the tags section

    let new_tag_line = format!("{}{}", indent_prefix, tag);

    let mut result_lines: Vec<String> = Vec::new();
    for (i, line) in fm_lines.iter().enumerate() {
        result_lines.push(line.to_string());
        if i == insert_after {
            result_lines.push(new_tag_line.clone());
        }
    }

    let change = ChangeDescription::AddTag {
        tag: tag.to_string(),
    };

    Ok((reassemble(&result_lines, body, content), change))
}

/// Remove a tag from the tags list.
pub fn remove_tag(content: &str, tag: &str) -> Result<(String, ChangeDescription)> {
    let (fm_lines, body) = split_frontmatter(content)?;

    let key_idx =
        find_key_line(&fm_lines, "tags").ok_or_else(|| VaultdbError::InvalidFrontmatter {
            file: String::new(),
            reason: "no 'tags' field found".into(),
        })?;

    if is_flow_style_list(fm_lines[key_idx]) {
        return Err(VaultdbError::InvalidFrontmatter {
            file: String::new(),
            reason: "tags field uses flow-style YAML (e.g., tags: [a, b]). Convert to block-style first.".into(),
        });
    }

    let extent = field_extent(&fm_lines, key_idx);

    // Find the tag line within the tags section
    let tag_line_idx = fm_lines
        .iter()
        .enumerate()
        .skip(key_idx + 1)
        .take(extent.saturating_sub(1))
        .find_map(|(i, line)| {
            let trimmed = line.trim();
            let tag_value = trimmed.strip_prefix("- ").unwrap_or(trimmed);
            (tag_value == tag).then_some(i)
        });

    let tag_line_idx = tag_line_idx.ok_or_else(|| VaultdbError::InvalidFrontmatter {
        file: String::new(),
        reason: format!("tag '{}' not found in tags list", tag),
    })?;

    let mut result_lines: Vec<String> = Vec::new();
    for (i, line) in fm_lines.iter().enumerate() {
        if i == tag_line_idx {
            continue;
        }
        result_lines.push(line.to_string());
    }

    let change = ChangeDescription::RemoveTag {
        tag: tag.to_string(),
    };

    Ok((reassemble(&result_lines, body, content), change))
}

/// Reassemble a file from frontmatter lines and body, preserving the original line ending style.
fn reassemble(fm_lines: &[String], body: &str, original: &str) -> String {
    let line_ending = if original.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };

    let mut result = fm_lines.join(line_ending);
    result.push_str(line_ending);
    result.push_str(body);
    result
}

/// Options controlling how a write touches the filesystem.
///
/// Default values match the previous (pre-Phase-A) `std::fs::write`
/// behaviour: atomic at the rename, but not durable against power loss.
/// Set `fsync: true` to force the data to stable storage before the
/// write returns.
///
/// Designed to be `Copy + Default + serde::*` so it can be piped through
/// the mutation builders, configured from env vars or config files, or
/// surfaced over a Tauri command.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WriteOptions {
    /// fsync the temp file's data, then fsync the parent directory's
    /// metadata, before considering the write complete. Adds one or two
    /// disk-flush IOs per write — typically 1–10ms on consumer SSDs and
    /// 10–50ms on spinning disks. Required for durable mutations (e.g. a
    /// long-lived Tauri app) that need to survive sudden power loss with
    /// the change preserved.
    pub fsync: bool,
}

impl WriteOptions {
    /// Convenience: opts with `fsync` set to true.
    pub fn durable() -> Self {
        Self { fsync: true }
    }
}

/// fsync a directory so its dirent updates (renames, creates, removes)
/// are durable. Best-effort on Windows: opening a directory for sync
/// is supported on NTFS but not all filesystems.
pub fn fsync_dir(dir: &std::path::Path) -> std::io::Result<()> {
    let f = std::fs::File::open(dir)?;
    f.sync_all()
}

/// Atomically replace the contents of `path` with `content` using the
/// default [`WriteOptions`] (no fsync). See [`atomic_write_with`] for the
/// version that takes options.
pub fn atomic_write(path: &std::path::Path, content: &str) -> std::io::Result<()> {
    atomic_write_with(path, content, WriteOptions::default())
}

/// Atomically replace the contents of `path` with `content`, honoring
/// [`WriteOptions`].
///
/// Writes to a temp file in the same directory, optionally fsyncs the
/// temp file's data, then renames over the target. The rename is atomic
/// on POSIX same-filesystem operations and on Windows with
/// `MoveFileEx(MOVEFILE_REPLACE_EXISTING)`. Concurrent readers either
/// see the full old content or the full new content; they never see a
/// partial write.
///
/// When `opts.fsync` is true, the temp file is fsynced before rename
/// AND the parent directory is fsynced after rename, so the change
/// survives power loss the moment this function returns Ok.
pub fn atomic_write_with(
    path: &std::path::Path,
    content: &str,
    opts: WriteOptions,
) -> std::io::Result<()> {
    let dir = path.parent().ok_or_else(|| {
        std::io::Error::other(format!(
            "atomic_write target has no parent dir: {}",
            path.display()
        ))
    })?;

    // tempfile::NamedTempFile creates a uniquely-named file in `dir`,
    // which guarantees same-filesystem rename below. The file is
    // cleaned up automatically on drop if `persist` isn't called (e.g.
    // if the write fails mid-way).
    let mut tmp = tempfile::NamedTempFile::new_in(dir)?;

    use std::io::Write;
    tmp.write_all(content.as_bytes())?;
    tmp.flush()?;

    // Optional data fsync before the rename. The order matters: if we
    // rename first and then fsync, a power loss between the rename and
    // the fsync can leave the rename visible but pointing at undefined
    // data. POSIX guarantees that data fsynced before the rename is
    // durable as soon as the rename's directory entry is durable.
    if opts.fsync {
        tmp.as_file().sync_all()?;
    }

    // `persist` does the atomic rename. On error it returns the temp
    // file plus the io::Error; we discard the temp file (it'll be
    // cleaned up by Drop) and propagate just the error.
    tmp.persist(path).map_err(|e| e.error)?;

    if opts.fsync {
        fsync_dir(dir)?;
    }
    Ok(())
}

/// Write a WriteResult to disk atomically with default options.
pub fn apply(result: &WriteResult) -> std::io::Result<()> {
    apply_with(result, WriteOptions::default())
}

/// Write a WriteResult to disk atomically, honoring [`WriteOptions`].
pub fn apply_with(result: &WriteResult, opts: WriteOptions) -> std::io::Result<()> {
    atomic_write_with(&result.path, &result.modified_content, opts)
}

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

    const MOVIE_FILE: &str = "\
---
aliases:
tags:
  - type/leaf
  - topic/movies
  - source/video
  - genre/drama
status: to-watch
rating:
director: Sam Mendes
year: 2019
related-to:
---

Part of [[Watchlist]]
";

    const CHINESE_FILE: &str = "\
---
aliases:
- kuài
tags:
- type/concept
- topic/chinese
- source/self-study
pinyin: kuài
anlam: hızlı
tür: sifat
hsk: 1
kaliplar:
- kalip: 快乐
  pinyin: kuàilè
  anlam: mutlu, neşeli
ornekler:
- cumle: 他跑得很快。
  pinyin: Tā pǎo de hěn kuài.
  anlam: O çok hızlı koşuyor.
related-to:
---

# 快 (kuài) — hızlı

Body text.
";

    #[test]
    fn set_existing_scalar_field() {
        let (result, change) = set_field(MOVIE_FILE, "status", "watched").unwrap();
        assert!(result.contains("status: watched"));
        assert!(!result.contains("to-watch"));
        // Body preserved
        assert!(result.contains("Part of [[Watchlist]]"));
        match change {
            ChangeDescription::SetField {
                field,
                old_value,
                new_value,
            } => {
                assert_eq!(field, "status");
                assert_eq!(old_value, "to-watch");
                assert_eq!(new_value, "watched");
            }
            _ => panic!("expected SetField"),
        }
    }

    #[test]
    fn set_null_field() {
        let (result, _) = set_field(MOVIE_FILE, "rating", "8").unwrap();
        assert!(result.contains("rating: 8"));
    }

    #[test]
    fn set_new_field() {
        let (result, _) = set_field(MOVIE_FILE, "language", "English").unwrap();
        assert!(result.contains("language: English"));
        // Should be inserted before closing ---
        let closing_idx = result.rfind("\n---\n").unwrap();
        let lang_idx = result.find("language: English").unwrap();
        assert!(lang_idx < closing_idx);
    }

    #[test]
    fn set_complex_field_rejected() {
        let result = set_field(CHINESE_FILE, "kaliplar", "something");
        assert!(result.is_err());
    }

    #[test]
    fn set_value_needing_quotes() {
        let (result, _) = set_field(MOVIE_FILE, "note", "key: value").unwrap();
        assert!(result.contains("note: 'key: value'"));
    }

    #[test]
    fn unset_scalar_field() {
        let (result, _) = unset_field(MOVIE_FILE, "director").unwrap();
        assert!(!result.contains("director:"));
        // Other fields preserved
        assert!(result.contains("status: to-watch"));
        assert!(result.contains("year: 2019"));
        assert!(result.contains("Part of [[Watchlist]]"));
    }

    #[test]
    fn unset_list_field() {
        let (result, _) = unset_field(CHINESE_FILE, "kaliplar").unwrap();
        assert!(!result.contains("kaliplar:"));
        assert!(!result.contains("快乐"));
        // Other fields preserved
        assert!(result.contains("pinyin: kuài"));
        assert!(result.contains("Body text."));
    }

    #[test]
    fn unset_nonexistent_field() {
        let result = unset_field(MOVIE_FILE, "nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn add_tag_2space_indent() {
        let (result, _) = add_tag(MOVIE_FILE, "genre/war").unwrap();
        assert!(result.contains("  - genre/war"));
        // Existing tags still present
        assert!(result.contains("  - type/leaf"));
        assert!(result.contains("  - genre/drama"));
    }

    #[test]
    fn add_tag_0indent() {
        let (result, _) = add_tag(CHINESE_FILE, "topic/hsk1").unwrap();
        assert!(result.contains("- topic/hsk1"));
        // Existing tags preserved
        assert!(result.contains("- type/concept"));
        assert!(result.contains("- topic/chinese"));
    }

    #[test]
    fn remove_tag_2space_indent() {
        let (result, _) = remove_tag(MOVIE_FILE, "genre/drama").unwrap();
        assert!(!result.contains("genre/drama"));
        // Other tags preserved
        assert!(result.contains("  - type/leaf"));
        assert!(result.contains("  - source/video"));
    }

    #[test]
    fn remove_tag_0indent() {
        let (result, _) = remove_tag(CHINESE_FILE, "topic/chinese").unwrap();
        assert!(!result.contains("topic/chinese"));
        assert!(result.contains("- type/concept"));
        assert!(result.contains("- source/self-study"));
    }

    #[test]
    fn remove_nonexistent_tag() {
        let result = remove_tag(MOVIE_FILE, "nonexistent/tag");
        assert!(result.is_err());
    }

    #[test]
    fn body_preserved_after_set() {
        let (result, _) = set_field(MOVIE_FILE, "status", "watched").unwrap();
        assert!(result.ends_with("Part of [[Watchlist]]\n"));
    }

    #[test]
    fn body_preserved_after_unset() {
        let (result, _) = unset_field(CHINESE_FILE, "hsk").unwrap();
        assert!(result.contains("# 快 (kuài) — hızlı"));
        assert!(result.contains("Body text."));
    }

    #[test]
    fn body_preserved_after_add_tag() {
        let (result, _) = add_tag(CHINESE_FILE, "topic/hsk1").unwrap();
        assert!(result.contains("# 快 (kuài) — hızlı"));
    }

    #[test]
    fn chinese_content_preserved() {
        let (result, _) = set_field(CHINESE_FILE, "hsk", "2").unwrap();
        assert!(result.contains("pinyin: kuài"));
        assert!(result.contains("anlam: hızlı"));
        assert!(result.contains("tür: sifat"));
        assert!(result.contains("kalip: 快乐"));
        assert!(result.contains("cumle: 他跑得很快。"));
    }

    // ── Safety checks ─────────────────────────

    #[test]
    fn set_field_rejects_flow_style() {
        let content = "---\ntags: [a, b, c]\n---\nBody.\n";
        let result = set_field(content, "tags", "x");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("flow-style"));
    }

    #[test]
    fn set_field_rejects_multiline_scalar() {
        let content = "---\ndescription: |\n  Multi line\n  content here\n---\nBody.\n";
        let result = set_field(content, "description", "new value");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("multiline"));
    }

    #[test]
    fn add_tag_rejects_flow_style() {
        let content = "---\ntags: [type/concept, topic/ai]\n---\nBody.\n";
        let result = add_tag(content, "topic/new");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("flow-style"));
    }

    #[test]
    fn remove_tag_rejects_flow_style() {
        let content = "---\ntags: [type/concept, topic/ai]\n---\nBody.\n";
        let result = remove_tag(content, "topic/ai");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("flow-style"));
    }
}