diaryx_core 1.4.4

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
//! Export module - filter and export workspace files by audience
//!
//! # Async-first Design
//!
//! This module uses `AsyncFileSystem` for all filesystem operations.
//! For synchronous contexts (CLI, tests), wrap a sync filesystem with
//! `SyncToAsyncFs` and use `futures_lite::future::block_on()`.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::command::{BinaryFileInfo, ExportedFile};
#[cfg(not(target_arch = "wasm32"))]
use crate::error::DiaryxError;
use crate::error::Result;
use crate::fs::AsyncFileSystem;
use crate::workspace::{IndexFrontmatter, Workspace};

/// Result of planning an export operation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub struct ExportPlan {
    /// Files that will be exported
    pub included: Vec<ExportFile>,
    /// Files that were filtered out (with reason)
    pub excluded: Vec<ExcludedFile>,
    /// The audience being exported for
    pub audience: String,
    /// Source workspace root
    pub source_root: PathBuf,
    /// Destination directory
    pub destination: PathBuf,
}

/// A file to be exported
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub struct ExportFile {
    /// Original path in the workspace
    pub source_path: PathBuf,
    /// Path relative to workspace root
    pub relative_path: PathBuf,
    /// Destination path
    pub dest_path: PathBuf,
    /// Contents entries that will be filtered out (if any)
    pub filtered_contents: Vec<String>,
}

/// A file that was excluded from export
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub struct ExcludedFile {
    /// Path to the excluded file
    pub path: PathBuf,
    /// Reason for exclusion
    pub reason: ExclusionReason,
}

/// Why a file was excluded
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub enum ExclusionReason {
    /// File's audience doesn't include the target audience
    AudienceMismatch {
        /// What audiences are intended to view the document
        file_audience: Vec<String>,
        /// What audiences were requested for the export
        requested: String,
    },
    /// File has no audience defined and no audience inherited from parent
    NoAudienceDefined,
}

impl std::fmt::Display for ExclusionReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExclusionReason::AudienceMismatch {
                file_audience,
                requested,
            } => {
                write!(
                    f,
                    "audience {:?} doesn't include '{}'",
                    file_audience, requested
                )
            }
            ExclusionReason::NoAudienceDefined => {
                write!(f, "no audience defined")
            }
        }
    }
}

/// Options for export operation
#[derive(Debug, Clone, Default, Serialize)]
pub struct ExportOptions {
    /// Whether to overwrite existing destination
    pub force: bool,
    /// Whether to preserve the audience property in exported files
    pub keep_audience: bool,
}

/// Export operations (async-first)
pub struct Exporter<FS: AsyncFileSystem> {
    workspace: Workspace<FS>,
}

impl<FS: AsyncFileSystem> Exporter<FS> {
    /// Create a new exporter
    pub fn new(fs: FS) -> Self {
        Self {
            workspace: Workspace::new(fs),
        }
    }

    /// Plan an export operation without executing it
    /// This traverses the workspace and determines which files would be included/excluded
    ///
    /// `default_audience` is the audience tag assigned to entries with no explicit
    /// or inherited audience. When `None`, such entries are private (excluded).
    pub async fn plan_export(
        &self,
        workspace_root: &Path,
        audience: &str,
        destination: &Path,
        default_audience: Option<&str>,
    ) -> Result<ExportPlan> {
        let mut included = Vec::new();
        let mut excluded = Vec::new();
        let mut visited = HashSet::new();

        // Get the workspace root directory
        let root_dir = workspace_root
            .parent()
            .unwrap_or(workspace_root)
            .to_path_buf();

        // Start traversal from the root index
        self.plan_file_recursive(
            workspace_root,
            &root_dir,
            destination,
            audience,
            None, // No inherited audience at root
            default_audience,
            &mut included,
            &mut excluded,
            &mut visited,
        )
        .await?;

        Ok(ExportPlan {
            included,
            excluded,
            audience: audience.to_string(),
            source_root: root_dir,
            destination: destination.to_path_buf(),
        })
    }

    /// Recursive helper for planning export
    #[allow(clippy::too_many_arguments)]
    async fn plan_file_recursive(
        &self,
        path: &Path,
        root_dir: &Path,
        dest_dir: &Path,
        audience: &str,
        inherited_audience: Option<&Vec<String>>,
        default_audience: Option<&str>,
        included: &mut Vec<ExportFile>,
        excluded: &mut Vec<ExcludedFile>,
        visited: &mut HashSet<PathBuf>,
    ) -> Result<bool> {
        // Avoid cycles
        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        if visited.contains(&canonical) {
            return Ok(false);
        }
        visited.insert(canonical);

        // Parse the file - handle files without frontmatter gracefully
        let parse_result = self.workspace.parse_index(path).await;

        // For files without frontmatter or with parse errors, use default frontmatter
        // and inherit parent's audience
        let (frontmatter, index_for_children) = match parse_result {
            Ok(index) => (index.frontmatter.clone(), Some(index)),
            Err(crate::error::DiaryxError::NoFrontmatter(_)) => {
                // File has no frontmatter - treat as a simple file that inherits parent's visibility
                (IndexFrontmatter::default(), None)
            }
            Err(crate::error::DiaryxError::YamlParse { path, message }) => {
                // Log the YAML parse error but continue with default frontmatter
                log::warn!(
                    "[Export] Skipping file with YAML parse error: {} - {}",
                    path.display(),
                    message
                );
                (IndexFrontmatter::default(), None)
            }
            Err(crate::error::DiaryxError::Yaml(e)) => {
                // Legacy YAML error without path context - log and continue
                log::warn!("[Export] Skipping file with YAML error: {}", e);
                (IndexFrontmatter::default(), None)
            }
            Err(e) => return Err(e),
        };

        // Determine visibility
        let (is_visible, effective_audience) =
            self.check_visibility(&frontmatter, audience, inherited_audience, default_audience);

        if !is_visible {
            // Record exclusion reason
            let reason = self.get_exclusion_reason(
                &frontmatter,
                audience,
                inherited_audience,
                default_audience,
            );
            excluded.push(ExcludedFile {
                path: path.to_path_buf(),
                reason,
            });
            return Ok(false);
        }

        // Calculate relative and destination paths
        let relative_path =
            pathdiff::diff_paths(path, root_dir).unwrap_or_else(|| path.to_path_buf());
        let dest_path = dest_dir.join(&relative_path);

        // If this is an index file, process children and track which will be filtered
        let mut filtered_contents = Vec::new();

        if frontmatter.is_index()
            && let Some(ref index) = index_for_children
        {
            let child_audience = effective_audience.as_ref().or(inherited_audience);

            for child_path_str in frontmatter.contents_list() {
                let child_path = index.resolve_path(child_path_str);

                // Make path absolute if needed by joining with root_dir
                let absolute_child_path = if child_path.is_absolute() {
                    child_path.clone()
                } else {
                    root_dir.join(&child_path)
                };

                if self.workspace.fs_ref().exists(&absolute_child_path).await {
                    let child_included = Box::pin(self.plan_file_recursive(
                        &absolute_child_path,
                        root_dir,
                        dest_dir,
                        audience,
                        child_audience,
                        default_audience,
                        included,
                        excluded,
                        visited,
                    ))
                    .await?;

                    if !child_included {
                        filtered_contents.push(child_path_str.clone());
                    }
                }
            }
        }

        // Add this file to included list
        included.push(ExportFile {
            source_path: path.to_path_buf(),
            relative_path,
            dest_path,
            filtered_contents,
        });

        Ok(true)
    }

    /// Check if a file is visible to the given audience.
    /// Returns (is_visible, effective_audience_for_children).
    fn check_visibility(
        &self,
        frontmatter: &IndexFrontmatter,
        audience: &str,
        inherited: Option<&Vec<String>>,
        default_audience: Option<&str>,
    ) -> (bool, Option<Vec<String>>) {
        let audience = audience.trim();

        // Special case: "*" means "all files"
        if audience == "*" {
            let effective_audience = frontmatter.audience.clone();
            return (true, effective_audience);
        }

        // Check explicit audience
        if let Some(file_audience) = &frontmatter.audience {
            let visible = file_audience
                .iter()
                .any(|a| a.trim().eq_ignore_ascii_case(audience));
            return (visible, Some(file_audience.clone()));
        }

        // Inherit from parent
        if let Some(parent_audience) = inherited {
            let visible = parent_audience
                .iter()
                .any(|a| a.trim().eq_ignore_ascii_case(audience));
            return (visible, None);
        }

        // No audience defined anywhere — apply default_audience if set, otherwise private
        if let Some(default) = default_audience {
            let visible = default.eq_ignore_ascii_case(audience);
            (visible, Some(vec![default.to_string()]))
        } else {
            (false, None)
        }
    }

    /// Determine the reason a file was excluded.
    fn get_exclusion_reason(
        &self,
        frontmatter: &IndexFrontmatter,
        audience: &str,
        _inherited: Option<&Vec<String>>,
        default_audience: Option<&str>,
    ) -> ExclusionReason {
        if let Some(file_audience) = &frontmatter.audience {
            return ExclusionReason::AudienceMismatch {
                file_audience: file_audience.clone(),
                requested: audience.to_string(),
            };
        }

        if let Some(default) = default_audience {
            // Has a default audience but it didn't match the requested audience
            return ExclusionReason::AudienceMismatch {
                file_audience: vec![default.to_string()],
                requested: audience.to_string(),
            };
        }

        ExclusionReason::NoAudienceDefined
    }

    /// Execute an export plan
    /// Only available on native platforms (not WASM) since it writes to the filesystem
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn execute_export(
        &self,
        plan: &ExportPlan,
        options: &ExportOptions,
    ) -> Result<ExportStats> {
        // Check if destination exists
        if self.workspace.fs_ref().exists(&plan.destination).await && !options.force {
            return Err(DiaryxError::WorkspaceAlreadyExists(
                plan.destination.clone(),
            ));
        }

        // Create destination directory
        self.workspace
            .fs_ref()
            .create_dir_all(&plan.destination)
            .await?;

        let mut stats = ExportStats::default();

        for export_file in &plan.included {
            // Create parent directories if needed
            if let Some(parent) = export_file.dest_path.parent() {
                self.workspace.fs_ref().create_dir_all(parent).await?;
            }

            // Read source file
            let content = self
                .workspace
                .fs_ref()
                .read_to_string(&export_file.source_path)
                .await
                .map_err(|e| DiaryxError::FileRead {
                    path: export_file.source_path.clone(),
                    source: e,
                })?;

            // Process content if needed (filter contents array)
            let processed_content = if !export_file.filtered_contents.is_empty() {
                self.filter_contents_in_file(&content, &export_file.filtered_contents, options)?
            } else if !options.keep_audience {
                self.remove_audience_property(&content)?
            } else {
                content
            };

            // Write to destination
            self.workspace
                .fs_ref()
                .write_file(&export_file.dest_path, &processed_content)
                .await?;
            stats.files_exported += 1;
        }

        stats.files_excluded = plan.excluded.len();
        Ok(stats)
    }

    /// Filter out excluded children from a file's contents array.
    #[cfg(not(target_arch = "wasm32"))]
    fn filter_contents_in_file(
        &self,
        content: &str,
        filtered: &[String],
        options: &ExportOptions,
    ) -> Result<String> {
        // Parse frontmatter
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(content.to_string());
        }

        let rest = &content[4..];
        let end_idx = rest
            .find("\n---\n")
            .or_else(|| rest.find("\n---\r\n"))
            .ok_or_else(|| DiaryxError::InvalidFrontmatter(PathBuf::from("export")))?;

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..];

        // Parse as YAML
        let mut frontmatter: crate::yaml_value::YamlValue = serde_yaml::from_str(frontmatter_str)?;

        // Filter contents array
        if let Some(contents) = frontmatter
            .as_mapping_mut()
            .and_then(|m| m.get_mut("contents"))
            && let Some(arr) = contents.as_sequence_mut()
        {
            arr.retain(|item| {
                if let Some(s) = item.as_str() {
                    !filtered.iter().any(|f| f == s)
                } else {
                    true
                }
            });
        }

        // Optionally remove audience property
        if !options.keep_audience
            && let Some(map) = frontmatter.as_mapping_mut()
        {
            map.shift_remove("audience");
        }

        // Reconstruct file
        let new_frontmatter = serde_yaml::to_string(&frontmatter)?;
        // Remove trailing newline from YAML output for cleaner formatting
        let new_frontmatter = new_frontmatter.trim_end();

        Ok(format!("---\n{}\n---\n{}", new_frontmatter, body))
    }

    /// Remove audience property from a file.
    #[cfg(not(target_arch = "wasm32"))]
    fn remove_audience_property(&self, content: &str) -> Result<String> {
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(content.to_string());
        }

        let rest = &content[4..];
        let end_idx = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"));

        let Some(end_idx) = end_idx else {
            return Ok(content.to_string());
        };

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..];

        // Parse as YAML
        let mut frontmatter: crate::yaml_value::YamlValue = serde_yaml::from_str(frontmatter_str)?;

        // Remove audience property
        if let Some(map) = frontmatter.as_mapping_mut() {
            let had_audience = map.shift_remove("audience").is_some();

            if !had_audience {
                // No audience property, return original
                return Ok(content.to_string());
            }
        }

        // Reconstruct file
        let new_frontmatter = serde_yaml::to_string(&frontmatter)?;
        let new_frontmatter = new_frontmatter.trim_end();

        Ok(format!("---\n{}\n---\n{}", new_frontmatter, body))
    }
}

/// Check if a file is a binary attachment (not markdown/text).
pub fn is_binary_file(path: &Path) -> bool {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_lowercase());

    match ext.as_deref() {
        // Text/markdown files - not binary
        Some("md" | "txt" | "json" | "yaml" | "yml" | "toml") => false,
        // Common binary formats
        Some(
            "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "ico" | "bmp" | "pdf" | "heic"
            | "heif" | "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx" | "mp3" | "mp4" | "wav"
            | "ogg" | "flac" | "m4a" | "aac" | "mov" | "avi" | "mkv" | "webm" | "zip" | "tar"
            | "gz" | "rar" | "7z" | "ttf" | "otf" | "woff" | "woff2" | "sqlite" | "db",
        ) => true,
        _ => false,
    }
}

impl<FS: AsyncFileSystem> Exporter<FS> {
    /// Export files to memory by running `plan_export()` and reading each included file.
    ///
    /// Returns the raw file contents without body rendering — callers (plugins)
    /// can post-process the results as needed.
    pub async fn export_to_memory(
        &self,
        workspace_root: &Path,
        audience: &str,
        default_audience: Option<&str>,
    ) -> Result<Vec<ExportedFile>> {
        let plan = self
            .plan_export(
                workspace_root,
                audience,
                Path::new("/tmp/export"),
                default_audience,
            )
            .await?;

        let root_dir = workspace_root
            .parent()
            .unwrap_or(workspace_root)
            .to_path_buf();

        let mut files = Vec::new();
        for included in &plan.included {
            match self
                .workspace
                .fs_ref()
                .read_to_string(&included.source_path)
                .await
            {
                Ok(content) => {
                    let relative_path = pathdiff::diff_paths(&included.source_path, &root_dir)
                        .unwrap_or_else(|| included.source_path.clone());
                    files.push(ExportedFile {
                        path: relative_path.to_string_lossy().to_string(),
                        content,
                    });
                }
                Err(e) => {
                    log::warn!("[Exporter] read failed: {:?} - {}", included.source_path, e);
                }
            }
        }
        Ok(files)
    }

    /// Walk a directory tree collecting binary (non-text) file paths.
    pub async fn collect_binary_attachments(&self, root_path: &Path) -> Vec<BinaryFileInfo> {
        let root_dir = root_path.parent().unwrap_or(root_path);
        let Ok(file_set) = self.workspace.collect_workspace_file_set(root_path).await else {
            return Vec::new();
        };

        let mut attachments = Vec::new();
        for relative_path in file_set {
            let entry_path = root_dir.join(&relative_path);
            if entry_path.extension().is_some_and(|ext| ext == "md") {
                continue;
            }
            if !self.workspace.fs_ref().exists(&entry_path).await {
                continue;
            }
            if !is_binary_file(&entry_path) {
                continue;
            }

            attachments.push(BinaryFileInfo {
                source_path: entry_path.to_string_lossy().to_string(),
                relative_path,
            });
        }

        attachments
    }
}

/// Statistics from an export operation
#[derive(Debug, Clone, Default, Serialize)]
pub struct ExportStats {
    /// Number of files successfully exported
    pub files_exported: usize,
    /// Number of files excluded for some reason
    pub files_excluded: usize,
}

impl std::fmt::Display for ExportStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Exported {} files, excluded {} files",
            self.files_exported, self.files_excluded
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{FileSystem, InMemoryFileSystem, SyncToAsyncFs, block_on_test};

    type TestFs = SyncToAsyncFs<InMemoryFileSystem>;

    fn make_test_fs() -> InMemoryFileSystem {
        InMemoryFileSystem::new()
    }

    #[test]
    fn test_audience_mismatch_excluded() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents:\n  - secret.md\naudience:\n  - family\n---\n\n# Root\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/secret.md"),
            "---\ntitle: Secret\npart_of: README.md\naudience:\n  - internal\n---\n\n# Secret\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        assert_eq!(plan.included.len(), 1);
        assert_eq!(plan.excluded.len(), 1);
        assert_eq!(
            plan.excluded[0].reason,
            ExclusionReason::AudienceMismatch {
                file_audience: vec!["internal".to_string()],
                requested: "family".to_string(),
            }
        );
    }

    #[test]
    fn test_audience_inheritance() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents:\n  - child.md\naudience:\n  - family\n---\n\n# Root\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/child.md"),
            "---\ntitle: Child\npart_of: README.md\n---\n\n# Child inherits family audience\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        // Both should be included - child inherits family audience
        assert_eq!(plan.included.len(), 2);
        assert_eq!(plan.excluded.len(), 0);
    }

    #[test]
    fn test_no_audience_private_by_default() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents: []\n---\n\n# Root with no audience\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        // No audience + no default_audience = private (excluded)
        assert_eq!(plan.included.len(), 0);
        assert_eq!(plan.excluded.len(), 1);
        assert_eq!(plan.excluded[0].reason, ExclusionReason::NoAudienceDefined);
    }

    #[test]
    fn test_no_audience_with_default_audience_included() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents: []\n---\n\n# Root with no audience\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "public",
            Path::new("/export"),
            Some("public"),
        ))
        .unwrap();

        // No audience + default_audience=public, requesting "public" = included
        assert_eq!(plan.included.len(), 1);
        assert_eq!(plan.excluded.len(), 0);
    }

    #[test]
    fn test_no_audience_with_default_audience_mismatch() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents: []\n---\n\n# Root with no audience\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            Some("public"),
        ))
        .unwrap();

        // No audience + default_audience=public, requesting "family" = excluded
        assert_eq!(plan.included.len(), 0);
        assert_eq!(plan.excluded.len(), 1);
    }

    #[test]
    fn test_explicit_audience_overrides_default() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents: []\naudience:\n  - family\n---\n\n# Root\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        // Explicit audience "family" should override default_audience "public"
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            Some("public"),
        ))
        .unwrap();

        assert_eq!(plan.included.len(), 1);
        assert_eq!(plan.excluded.len(), 0);
    }

    #[test]
    fn test_wildcard_audience_includes_all() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents: []\n---\n\n# Root\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "*",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        // Wildcard always includes everything
        assert_eq!(plan.included.len(), 1);
        assert_eq!(plan.excluded.len(), 0);
    }

    #[test]
    fn test_filtered_contents_tracked() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents:\n  - visible.md\n  - hidden.md\naudience:\n  - family\n---\n\n# Root\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/visible.md"),
            "---\ntitle: Visible\npart_of: README.md\n---\n\n# Visible\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/hidden.md"),
            "---\ntitle: Hidden\npart_of: README.md\naudience:\n  - internal\n---\n\n# Hidden\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        // Find the root in included files
        let root = plan
            .included
            .iter()
            .find(|f| f.source_path == Path::new("/workspace/README.md"))
            .unwrap();

        // Root should track that hidden.md was filtered
        assert!(root.filtered_contents.contains(&"hidden.md".to_string()));
    }

    #[test]
    fn test_audience_values_trimmed_for_visibility() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/README.md"),
            "---\ntitle: Root\ncontents:\n  - child.md\naudience:\n  - \" family \"\n  - \" ENGL212 \"\n---\n\n# Root\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/child.md"),
            "---\ntitle: Child\npart_of: README.md\n---\n\n# Child\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let plan_family = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "family",
            Path::new("/export"),
            None,
        ))
        .unwrap();
        let plan_engl = block_on_test(exporter.plan_export(
            Path::new("/workspace/README.md"),
            "engl212",
            Path::new("/export"),
            None,
        ))
        .unwrap();

        assert_eq!(plan_family.included.len(), 2);
        assert_eq!(plan_family.excluded.len(), 0);
        assert_eq!(plan_engl.included.len(), 2);
        assert_eq!(plan_engl.excluded.len(), 0);
    }

    #[test]
    fn test_collect_binary_attachments_uses_logical_workspace_file_set() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/workspace/Diaryx.md"),
            "---\ntitle: Root\ncontents:\n  - notes/day.md\nattachments:\n  - assets/root.png\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/workspace/notes/day.md"),
            "---\ntitle: Day\npart_of: ../Diaryx.md\nattachments:\n  - _attachments/day.jpg\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("/workspace/assets/root.png"), "root")
            .unwrap();
        fs.write_file(Path::new("/workspace/notes/_attachments/day.jpg"), "day")
            .unwrap();
        fs.write_file(Path::new("/workspace/target/debug/app.bin"), "bin")
            .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let exporter = Exporter::new(async_fs);
        let attachments =
            block_on_test(exporter.collect_binary_attachments(Path::new("/workspace/Diaryx.md")));

        assert_eq!(
            attachments
                .iter()
                .map(|file| file.relative_path.as_str())
                .collect::<Vec<_>>(),
            vec!["assets/root.png", "notes/_attachments/day.jpg"]
        );
    }
}