memstead-base 0.3.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, no API stability promise.
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! File-adapter persistence for the pipeline configs.
//!
//! Reads and writes [`Medium`] / [`Facet`] / [`Projection`] / v1
//! [`BindingV1`] (and, for the legacy path, the crate-local [`LegacyIngest`])
//! JSON under the workspace store ([`WORKSPACE_STORE_DIR`]):
//!
//! - `<root>/.memstead/mediums/<mem>/<name>.json`
//! - `<root>/.memstead/facets/<mem>/<name>.json`
//! - `<root>/.memstead/projections/<mem>/<name>.json`
//! - `<root>/.memstead/ingests/<name>.json`  — flat; ingests are not per-mem
//!
//! (The plan's acceptance-criteria text lists `projections`/`ingests` under a
//! `.graph/` path; that is a typo for `.memstead/` — the AC header, Goal, and
//! Constraints all place every pipeline config in the `.memstead/` workspace
//! store. All four primitives live under `.memstead/` here.)
//!
//! Mediums, facets, and projections are per-mem (a `<mem>` subdirectory
//! tier preserves the "mem owns its territory" framing); ingests are flat,
//! matching the legacy `ingests/<name>.json` layout. The record's
//! identity is `(mem, name)` derived from the file path; `name` is the file
//! stem.
//!
//! The loader's job is load + validate + expose read-only: a malformed config
//! surfaces a typed [`StoreError::Parse`] naming the offending file (the
//! early-validation value), rather than being silently skipped.

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

use serde::Serialize;
use serde::de::DeserializeOwned;

use serde::Deserialize;

use crate::binding::BindingV1;
use crate::pipeline::{Facet, IngestTrigger, Medium, Projection};
use crate::workspace_store::{StoreError, WORKSPACE_STORE_DIR};

/// The legacy (gen-2) flat **ingest** record — the schedule primitive the
/// binding model retired (its `mode`/`trigger`/`batch_size`/`deny_paths`/
/// `post_actions` collapsed into a binding's `operations.build` block).
///
/// This shape is **migrate-local**: it is parsed only by the legacy path —
/// [`load_legacy_pipeline_configs`], `projection migrate` (which reads it to
/// merge each ingest into its projection), the referential-integrity edit
/// layer, and the gen-1 root-folder converter. No live surface constructs or
/// runs it; the live loader speaks [`BindingV1`]. Kept `pub(crate)` and minimal
/// so the retired `Ingest`/`IngestMode` machinery no longer lives on any public
/// or live surface.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct LegacyIngest {
    /// The projection (by name, `"<mem>/<name>"`) this ingest ran.
    pub projection: String,
    /// Discovery / refinement / one-shot — including the deleted `refinement`
    /// value, parsed so `projection migrate` can *detect and refuse* it (D1).
    pub mode: LegacyIngestMode,
    /// Loop / manual / on-event.
    pub trigger: IngestTrigger,
    /// How many artifacts a single run processed.
    pub batch_size: u32,
    /// Paths excluded for this ingest's runs, on top of facet scope.
    #[serde(default)]
    pub deny_paths: Vec<String>,
    /// Free-form post-run actions (e.g. a one-shot `archive_source` flag).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_actions: Option<serde_json::Value>,
}

/// The legacy ingest mode, including the deleted `refinement` value. Parsed so
/// `projection migrate` can detect and refuse it (D1) — never carried forward
/// into a v1 binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum LegacyIngestMode {
    /// Build out new coverage.
    Discovery,
    /// Improve existing coverage — the deleted refinement-as-writer mode.
    Refinement,
    /// A single bounded pass.
    OneShot,
}

/// Per-primitive subdirectory names under the workspace store.
pub const MEDIUMS_DIR: &str = "mediums";
/// See [`MEDIUMS_DIR`].
pub const FACETS_DIR: &str = "facets";
/// See [`MEDIUMS_DIR`].
pub const PROJECTIONS_DIR: &str = "projections";
/// See [`MEDIUMS_DIR`].
pub const INGESTS_DIR: &str = "ingests";

/// A per-mem pipeline record paired with the mem and name (file stem) that
/// identify it on disk.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MemPipelineRecord<T> {
    /// The mem subdirectory this record lives under.
    pub mem: String,
    /// The record's name — the file stem (e.g. `source-tree`).
    pub name: String,
    /// The parsed config.
    pub config: T,
}

/// A flat (non-per-mem) pipeline record — used for ingests.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PipelineRecord<T> {
    /// The record's name — the file stem (e.g. `macos-graph`).
    pub name: String,
    /// The parsed config.
    pub config: T,
}

/// Every pipeline config in a workspace store, in the four-primitive shape.
///
/// This is the **legacy** (gen-2) shape — produced only by
/// [`load_legacy_pipeline_configs`], consumed by the referential-integrity
/// edit layer, the `projection migrate` transform, and the macOS
/// `pipeline_configs_json` surface. The live loader
/// ([`load_pipeline_configs`]) returns [`BindingConfigs`] instead.
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct PipelineConfigs {
    /// Per-mem mediums.
    pub mediums: Vec<MemPipelineRecord<Medium>>,
    /// Per-mem facets.
    pub facets: Vec<MemPipelineRecord<Facet>>,
    /// Per-mem projections.
    pub projections: Vec<MemPipelineRecord<Projection>>,
    /// Flat legacy ingests (crate-local — the migrate/edit path reads them; no
    /// live or external surface does).
    pub(crate) ingests: Vec<PipelineRecord<LegacyIngest>>,
}

/// Every pipeline config in a workspace store, in the **binding v1** shape
/// (D1/D2) — mediums, facets, and one [`BindingV1`] per source→mem obligation
/// (the projection + flat-ingest split collapsed into a single versioned
/// record). This is what the live loader [`load_pipeline_configs`] returns and
/// the brief / selection / cursor paths consume.
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct BindingConfigs {
    /// Per-mem mediums.
    pub mediums: Vec<MemPipelineRecord<Medium>>,
    /// Per-mem facets.
    pub facets: Vec<MemPipelineRecord<Facet>>,
    /// Per-mem v1 bindings (occupying the `projections/<mem>/<name>.json` tier,
    /// stem-identity preserved). Canonical id is `<mem>/<stem>` (D3).
    pub bindings: Vec<MemPipelineRecord<BindingV1>>,
}

/// The `<root>/.memstead/<primitive>` directory for a given primitive.
fn primitive_dir(workspace_root: &Path, primitive: &str) -> PathBuf {
    workspace_root.join(WORKSPACE_STORE_DIR).join(primitive)
}

/// Refuse a `mem`/`name` value that is not a single, plain path
/// component: separators, traversal segments, drive/stream colons, NULs,
/// and empty values would let a caller-supplied name write or delete
/// outside the workspace's own metadata directory. Validated here — the
/// one place every mutation's path is built — so no surface above
/// (CLI, UniFFI, engine) can bypass it.
fn validate_component(kind: &str, value: &str) -> Result<(), StoreError> {
    let invalid = value.is_empty()
        || value == "."
        || value == ".."
        || value.contains('/')
        || value.contains('\\')
        || value.contains(':')
        || value.contains('\0');
    if invalid {
        return Err(StoreError::Other(format!(
            "invalid {kind} '{}': must be a single path component \
             (no separators, traversal segments, ':' or NUL)",
            value.escape_default()
        )));
    }
    Ok(())
}

/// File path of a per-mem record: `<root>/.memstead/<primitive>/<mem>/<name>.json`.
fn mem_scoped_path(
    workspace_root: &Path,
    primitive: &str,
    mem: &str,
    name: &str,
) -> Result<PathBuf, StoreError> {
    validate_component("mem", mem)?;
    validate_component("name", name)?;
    Ok(primitive_dir(workspace_root, primitive)
        .join(mem)
        .join(format!("{name}.json")))
}

/// File path of a flat (non-per-mem) record: `<root>/.memstead/<primitive>/<name>.json`.
fn flat_path(workspace_root: &Path, primitive: &str, name: &str) -> Result<PathBuf, StoreError> {
    validate_component("name", name)?;
    Ok(primitive_dir(workspace_root, primitive).join(format!("{name}.json")))
}

/// Remove the file at `path`, mapping IO failures (including a missing
/// file) to a typed [`StoreError::Io`] naming the path. Dumb counterpart
/// to [`write_json`] — referential-integrity / existence checks belong to
/// the calling layer, matching the write-is-upsert / load-validates split.
fn remove_file(path: &Path) -> Result<(), StoreError> {
    std::fs::remove_file(path).map_err(|e| StoreError::Io {
        path: path.to_path_buf(),
        source: e,
    })
}

/// Rename the record file `from` → `to`. Refuses to clobber an existing
/// target (silent overwrite would lose a distinct record); that guard is
/// the one non-dumb concession here because the failure mode is data loss.
/// A missing source surfaces as [`StoreError::Io`]. Reference rewriting in
/// dependent primitives is the calling layer's job.
fn rename_file(from: &Path, to: &Path) -> Result<(), StoreError> {
    if to.exists() {
        return Err(StoreError::Other(format!(
            "rename target already exists: {}",
            to.display()
        )));
    }
    std::fs::rename(from, to).map_err(|e| StoreError::Io {
        path: from.to_path_buf(),
        source: e,
    })
}

/// Serialise `config` (pretty JSON) into `path`, creating parent directories.
fn write_json<T: Serialize>(path: &Path, config: &T) -> Result<(), StoreError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| StoreError::Io {
            path: parent.to_path_buf(),
            source: e,
        })?;
    }
    let bytes = serde_json::to_vec_pretty(config).map_err(|e| StoreError::Parse {
        path: path.to_path_buf(),
        message: e.to_string(),
    })?;
    std::fs::write(path, bytes).map_err(|e| StoreError::Io {
        path: path.to_path_buf(),
        source: e,
    })
}

/// Load every `<primitive>/<mem>/<name>.json` under the store, parsed.
/// Absent primitive directory → empty (a workspace may declare no pipelines).
/// A malformed file surfaces a typed parse error naming the path.
fn load_mem_scoped<T: DeserializeOwned>(
    workspace_root: &Path,
    primitive: &str,
) -> Result<Vec<MemPipelineRecord<T>>, StoreError> {
    let dir = primitive_dir(workspace_root, primitive);
    let mut out: Vec<MemPipelineRecord<T>> = Vec::new();
    let mem_dirs = match std::fs::read_dir(&dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
        Err(e) => {
            return Err(StoreError::Io {
                path: dir,
                source: e,
            });
        }
    };
    for mem_entry in mem_dirs.flatten() {
        let mem_path = mem_entry.path();
        if !mem_path.is_dir() {
            continue;
        }
        let mem = mem_entry.file_name().to_string_lossy().into_owned();
        let files = match std::fs::read_dir(&mem_path) {
            Ok(rd) => rd,
            Err(e) => {
                return Err(StoreError::Io {
                    path: mem_path,
                    source: e,
                });
            }
        };
        for file in files.flatten() {
            let path = file.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            let Some(name) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else {
                continue;
            };
            let config = read_json::<T>(&path)?;
            out.push(MemPipelineRecord {
                mem: mem.clone(),
                name,
                config,
            });
        }
    }
    // Deterministic order so callers (and tests) see a stable enumeration.
    out.sort_by(|a, b| (a.mem.as_str(), a.name.as_str()).cmp(&(b.mem.as_str(), b.name.as_str())));
    Ok(out)
}

/// Load every `ingests/<name>.json` (flat), parsed.
fn load_flat<T: DeserializeOwned>(
    workspace_root: &Path,
    primitive: &str,
) -> Result<Vec<PipelineRecord<T>>, StoreError> {
    let dir = primitive_dir(workspace_root, primitive);
    let mut out: Vec<PipelineRecord<T>> = Vec::new();
    let files = match std::fs::read_dir(&dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
        Err(e) => {
            return Err(StoreError::Io {
                path: dir,
                source: e,
            });
        }
    };
    for file in files.flatten() {
        let path = file.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let Some(name) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else {
            continue;
        };
        let config = read_json::<T>(&path)?;
        out.push(PipelineRecord { name, config });
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(out)
}

/// Read + parse one JSON file into `T`, mapping IO/parse failures to typed
/// [`StoreError`]s naming the path.
fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, StoreError> {
    let bytes = std::fs::read(path).map_err(|e| StoreError::Io {
        path: path.to_path_buf(),
        source: e,
    })?;
    serde_json::from_slice(&bytes).map_err(|e| StoreError::Parse {
        path: path.to_path_buf(),
        message: e.to_string(),
    })
}

/// Write a medium to `<root>/.memstead/mediums/<mem>/<name>.json`.
pub fn write_medium(
    workspace_root: &Path,
    mem: &str,
    name: &str,
    medium: &Medium,
) -> Result<(), StoreError> {
    write_json(
        &mem_scoped_path(workspace_root, MEDIUMS_DIR, mem, name)?,
        medium,
    )
}

/// Write a facet to `<root>/.memstead/facets/<mem>/<name>.json`.
pub fn write_facet(
    workspace_root: &Path,
    mem: &str,
    name: &str,
    facet: &Facet,
) -> Result<(), StoreError> {
    write_json(
        &mem_scoped_path(workspace_root, FACETS_DIR, mem, name)?,
        facet,
    )
}

/// Write a projection to `<root>/.memstead/projections/<mem>/<name>.json`.
pub fn write_projection(
    workspace_root: &Path,
    mem: &str,
    name: &str,
    projection: &Projection,
) -> Result<(), StoreError> {
    write_json(
        &mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, name)?,
        projection,
    )
}

/// Write a legacy ingest to `<root>/.memstead/ingests/<name>.json` (flat).
/// Crate-local dumb file op — used by the gen-1 root-folder converter and the
/// projection-rename repoint; the live path writes bindings, not ingests.
pub(crate) fn write_ingest(
    workspace_root: &Path,
    name: &str,
    ingest: &LegacyIngest,
) -> Result<(), StoreError> {
    write_json(&flat_path(workspace_root, INGESTS_DIR, name)?, ingest)
}

/// Write a v1 binding to `<root>/.memstead/projections/<mem>/<name>.json`.
///
/// A binding (`BindingV1`) occupies the *same* per-mem projections tier and
/// file identity a gen-2 [`Projection`] did (stem-identity preserved, D1/D3),
/// so this overwrites the gen-2 projection file in place when promoting a
/// workspace. Additive counterpart to [`write_projection`]; nothing in the
/// live loader reads the v1 shape yet (that gate is a later slice).
pub fn write_binding(
    workspace_root: &Path,
    mem: &str,
    name: &str,
    binding: &BindingV1,
) -> Result<(), StoreError> {
    write_json(
        &mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, name)?,
        binding,
    )
}

/// Read the v1 binding at `<root>/.memstead/projections/<mem>/<name>.json`.
///
/// The read counterpart of [`write_binding`] — reads the *same* per-mem
/// projections tier and file identity, parsed as a [`BindingV1`]. A missing
/// file surfaces [`StoreError::Io`] (kind `NotFound`); a file present but not a
/// v1 binding (e.g. a not-yet-migrated gen-2 projection) surfaces
/// [`StoreError::Parse`]. Callers wanting a friendly "no such binding" message
/// pre-check existence and keep the two apart. Additive; the live loader does
/// not consult this yet (that gate is a later slice).
pub fn read_binding(workspace_root: &Path, mem: &str, name: &str) -> Result<BindingV1, StoreError> {
    read_json(&mem_scoped_path(
        workspace_root,
        PROJECTIONS_DIR,
        mem,
        name,
    )?)
}

/// Delete a medium file. Missing → [`StoreError::Io`]; callers that want a
/// friendly "no such medium" pre-check existence via [`load_pipeline_configs`].
pub fn delete_medium(workspace_root: &Path, mem: &str, name: &str) -> Result<(), StoreError> {
    remove_file(&mem_scoped_path(workspace_root, MEDIUMS_DIR, mem, name)?)
}

/// Delete a facet file. See [`delete_medium`] for missing-file semantics.
pub fn delete_facet(workspace_root: &Path, mem: &str, name: &str) -> Result<(), StoreError> {
    remove_file(&mem_scoped_path(workspace_root, FACETS_DIR, mem, name)?)
}

/// Delete a projection file. See [`delete_medium`] for missing-file semantics.
pub fn delete_projection(workspace_root: &Path, mem: &str, name: &str) -> Result<(), StoreError> {
    remove_file(&mem_scoped_path(
        workspace_root,
        PROJECTIONS_DIR,
        mem,
        name,
    )?)
}

/// Delete an ingest file (flat). See [`delete_medium`] for missing-file semantics.
pub fn delete_ingest(workspace_root: &Path, name: &str) -> Result<(), StoreError> {
    remove_file(&flat_path(workspace_root, INGESTS_DIR, name)?)
}

// Rename is exposed only for the *nameless* records (projection, ingest),
// whose identity is the file stem alone. Mediums and facets carry an embedded
// `name` field that must equal the stem (facets reference mediums by name,
// projections reference facets by name); a pure file move would leave that
// field stale, so their rename lives in the `pipeline_edit` layer, which
// rewrites the embedded name and dependent references together.

/// Rename a projection within its mem (`old` → `new`, same `<mem>` tier).
/// Refuses to clobber an existing target. A projection has no embedded name,
/// so a file move is its whole rename; rewriting dependent ingest `projection`
/// references is the calling layer's job.
pub fn rename_projection(
    workspace_root: &Path,
    mem: &str,
    old: &str,
    new: &str,
) -> Result<(), StoreError> {
    rename_file(
        &mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, old)?,
        &mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, new)?,
    )
}

/// Rename an ingest (flat). Refuses to clobber an existing target. An ingest
/// has no embedded name and nothing references it, so a file move is the whole
/// rename.
pub fn rename_ingest(workspace_root: &Path, old: &str, new: &str) -> Result<(), StoreError> {
    rename_file(
        &flat_path(workspace_root, INGESTS_DIR, old)?,
        &flat_path(workspace_root, INGESTS_DIR, new)?,
    )
}

/// Load the **legacy** (gen-2) four-primitive store from the workspace.
/// Absent directories resolve to empty; a malformed file surfaces a typed
/// [`StoreError::Parse`]. This reader is the counterpart of the version-gated
/// [`load_pipeline_configs`]: it deliberately reads the old
/// `Projection` + flat-`Ingest` shape (parsing a v1 binding file lossily as a
/// [`Projection`], which ignores `version`/`operations`), so
/// `projection migrate`, the referential-integrity edit layer, and the macOS
/// `pipeline_configs_json` surface keep working. It performs **no** version
/// gate — it is the escape hatch the gate points migrations at.
pub fn load_legacy_pipeline_configs(workspace_root: &Path) -> Result<PipelineConfigs, StoreError> {
    Ok(PipelineConfigs {
        mediums: load_mem_scoped(workspace_root, MEDIUMS_DIR)?,
        facets: load_mem_scoped(workspace_root, FACETS_DIR)?,
        projections: load_mem_scoped(workspace_root, PROJECTIONS_DIR)?,
        ingests: load_flat(workspace_root, INGESTS_DIR)?,
    })
}

/// Load every `projections/<mem>/<name>.json` as a **v1 binding**, version-gated
/// (D2). Absent directory → empty. For each file:
///
/// - no `version` field → [`StoreError::LegacyProjectionStore`] (the pre-v1
///   layout the loader no longer serves; the message names
///   `memstead projection migrate`);
/// - `version` present but not `1` → [`StoreError::UnknownBindingVersion`];
/// - `version: 1` → parsed as [`BindingV1`] (a malformed operations block etc.
///   surfaces [`StoreError::Parse`] naming the file).
///
/// The gate refuses the whole load on the first offending file — a version-less
/// workspace fails loudly (pointing at migrate) rather than loading half-served.
fn load_bindings(workspace_root: &Path) -> Result<Vec<MemPipelineRecord<BindingV1>>, StoreError> {
    let dir = primitive_dir(workspace_root, PROJECTIONS_DIR);
    let mut out: Vec<MemPipelineRecord<BindingV1>> = Vec::new();
    let mem_dirs = match std::fs::read_dir(&dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
        Err(e) => {
            return Err(StoreError::Io {
                path: dir,
                source: e,
            });
        }
    };
    for mem_entry in mem_dirs.flatten() {
        let mem_path = mem_entry.path();
        if !mem_path.is_dir() {
            continue;
        }
        let mem = mem_entry.file_name().to_string_lossy().into_owned();
        let files = match std::fs::read_dir(&mem_path) {
            Ok(rd) => rd,
            Err(e) => {
                return Err(StoreError::Io {
                    path: mem_path,
                    source: e,
                });
            }
        };
        for file in files.flatten() {
            let path = file.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            let Some(name) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else {
                continue;
            };
            // Peek at `version` before committing to the BindingV1 shape so a
            // pre-v1 (version-less) file yields the migrate-naming error rather
            // than an opaque "missing field `version`" parse error.
            let value: serde_json::Value = read_json(&path)?;
            match value.get("version") {
                None => return Err(StoreError::LegacyProjectionStore { path }),
                Some(v) => {
                    let n = v.as_i64();
                    if n != Some(i64::from(crate::binding::BINDING_VERSION)) {
                        return Err(StoreError::UnknownBindingVersion {
                            path,
                            version: n.unwrap_or(-1),
                        });
                    }
                }
            }
            let config: BindingV1 =
                serde_json::from_value(value).map_err(|e| StoreError::Parse {
                    path: path.clone(),
                    message: e.to_string(),
                })?;
            out.push(MemPipelineRecord {
                mem: mem.clone(),
                name,
                config,
            });
        }
    }
    out.sort_by(|a, b| (a.mem.as_str(), a.name.as_str()).cmp(&(b.mem.as_str(), b.name.as_str())));
    Ok(out)
}

/// Load the live **binding v1** store from the workspace (D2). Mediums and
/// facets load as before; `projections/` is read as version-gated v1 bindings
/// via [`load_bindings`] — a version-less (pre-v1) `projections/` refuses with
/// [`StoreError::LegacyProjectionStore`] naming `memstead projection migrate`.
/// The flat `ingests/` directory is **never read** by this path (bindings carry
/// their operations); it is served only by [`load_legacy_pipeline_configs`] for
/// migration.
pub fn load_pipeline_configs(workspace_root: &Path) -> Result<BindingConfigs, StoreError> {
    Ok(BindingConfigs {
        mediums: load_mem_scoped(workspace_root, MEDIUMS_DIR)?,
        facets: load_mem_scoped(workspace_root, FACETS_DIR)?,
        bindings: load_bindings(workspace_root)?,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::{MediumType, PatternEntry, PatternMode};
    use tempfile::TempDir;

    fn sample() -> (Medium, Facet, Projection, LegacyIngest) {
        let medium = Medium {
            name: "source-tree".to_string(),
            medium_type: MediumType::Codebase,
            pointer: "../macos".to_string(),
            change_detection: None,
        };
        let facet = Facet {
            name: "source-files".to_string(),
            medium: "source-tree".to_string(),
            scope: vec![PatternEntry {
                path: "../macos/**/*.swift".to_string(),
                mode: PatternMode::Allow,
            }],
            engagement: None,
            preparation: None,
        };
        let projection = Projection {
            intent: Some("Swift macOS app source.".to_string()),
            source_facets: vec!["source-files".to_string()],
            reference_mems: vec!["engine".to_string()],
            destination_mem: "macos".to_string(),
            rules: None,
        };
        let ingest = LegacyIngest {
            projection: "macos/graph".to_string(),
            mode: LegacyIngestMode::Discovery,
            trigger: IngestTrigger::Loop,
            batch_size: 20,
            deny_paths: vec!["VISION.md".to_string()],
            post_actions: None,
        };
        (medium, facet, projection, ingest)
    }

    #[test]
    fn mutations_refuse_traversal_in_mem_and_name() {
        // Every mutation path-builds from caller-supplied mem/name; a
        // separator or traversal segment must refuse with a typed error
        // and leave nothing on disk outside the store.
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (medium, _, _, ingest) = sample();

        let evil_values = [
            "..",
            ".",
            "",
            "../escape",
            "a/b",
            "a\\b",
            "..\\up",
            "c:evil",
            "nul\0byte",
        ];
        for evil in evil_values {
            assert!(
                write_medium(root, evil, "ok", &medium).is_err(),
                "mem '{}' must refuse",
                evil.escape_default()
            );
            assert!(
                write_medium(root, "ok", evil, &medium).is_err(),
                "name '{}' must refuse",
                evil.escape_default()
            );
            assert!(write_ingest(root, evil, &ingest).is_err());
            assert!(delete_medium(root, evil, "ok").is_err());
            assert!(delete_ingest(root, evil).is_err());
            assert!(rename_projection(root, evil, "a", "b").is_err());
            assert!(rename_projection(root, "ok", evil, "b").is_err());
            assert!(rename_projection(root, "ok", "a", evil).is_err());
            assert!(rename_ingest(root, evil, "b").is_err());
            assert!(rename_ingest(root, "a", evil).is_err());
        }

        // A traversal write must not have escaped: the only thing under
        // the temp root may be the (empty) store dir, and the parent of
        // the temp root gained no `escape.json`.
        assert!(
            !root.parent().unwrap().join("escape.json").exists(),
            "no write may land outside the workspace"
        );

        // Existing valid names keep working.
        write_medium(root, "macos", "source-tree", &medium).unwrap();
        assert!(
            root.join(".memstead/mediums/macos/source-tree.json")
                .is_file()
        );
    }

    #[test]
    fn empty_store_loads_empty_configs() {
        let tmp = TempDir::new().unwrap();
        let configs = load_legacy_pipeline_configs(tmp.path()).unwrap();
        assert_eq!(configs, PipelineConfigs::default());
    }

    #[test]
    fn write_then_load_round_trips_all_four_primitives() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (medium, facet, projection, ingest) = sample();

        write_medium(root, "macos", "source-tree", &medium).unwrap();
        write_facet(root, "macos", "source-files", &facet).unwrap();
        write_projection(root, "macos", "graph", &projection).unwrap();
        write_ingest(root, "macos-graph", &ingest).unwrap();

        // Files land at the documented `.memstead/` locations.
        assert!(
            root.join(".memstead/mediums/macos/source-tree.json")
                .is_file()
        );
        assert!(
            root.join(".memstead/facets/macos/source-files.json")
                .is_file()
        );
        assert!(
            root.join(".memstead/projections/macos/graph.json")
                .is_file()
        );
        assert!(root.join(".memstead/ingests/macos-graph.json").is_file());

        let configs = load_legacy_pipeline_configs(root).unwrap();
        assert_eq!(configs.mediums.len(), 1);
        assert_eq!(configs.mediums[0].mem, "macos");
        assert_eq!(configs.mediums[0].name, "source-tree");
        assert_eq!(configs.mediums[0].config, medium);
        assert_eq!(configs.facets[0].config, facet);
        assert_eq!(configs.projections[0].config, projection);
        assert_eq!(configs.ingests.len(), 1);
        assert_eq!(configs.ingests[0].name, "macos-graph");
        assert_eq!(configs.ingests[0].config, ingest);
    }

    #[test]
    fn load_enumeration_is_sorted_and_per_mem() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (medium, _, _, _) = sample();
        write_medium(root, "engine", "z-medium", &medium).unwrap();
        write_medium(root, "engine", "a-medium", &medium).unwrap();
        write_medium(root, "macos", "m-medium", &medium).unwrap();

        let configs = load_legacy_pipeline_configs(root).unwrap();
        let keys: Vec<_> = configs
            .mediums
            .iter()
            .map(|r| (r.mem.as_str(), r.name.as_str()))
            .collect();
        assert_eq!(
            keys,
            vec![
                ("engine", "a-medium"),
                ("engine", "z-medium"),
                ("macos", "m-medium"),
            ]
        );
    }

    #[test]
    fn malformed_config_surfaces_typed_parse_error_naming_the_file() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let bad = root.join(".memstead/mediums/macos");
        std::fs::create_dir_all(&bad).unwrap();
        std::fs::write(bad.join("broken.json"), b"{ not valid json").unwrap();

        let err = load_legacy_pipeline_configs(root).unwrap_err();
        match err {
            StoreError::Parse { path, .. } => {
                assert!(path.ends_with("broken.json"), "got {path:?}");
            }
            other => panic!("expected Parse error, got {other:?}"),
        }
    }

    #[test]
    fn delete_removes_the_record_and_load_reflects_it() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (medium, _, _, ingest) = sample();
        write_medium(root, "macos", "source-tree", &medium).unwrap();
        write_ingest(root, "macos-graph", &ingest).unwrap();

        delete_medium(root, "macos", "source-tree").unwrap();
        delete_ingest(root, "macos-graph").unwrap();

        assert!(
            !root
                .join(".memstead/mediums/macos/source-tree.json")
                .exists()
        );
        assert!(!root.join(".memstead/ingests/macos-graph.json").exists());
        let configs = load_legacy_pipeline_configs(root).unwrap();
        assert!(configs.mediums.is_empty());
        assert!(configs.ingests.is_empty());
    }

    #[test]
    fn delete_of_missing_record_surfaces_io_error() {
        let tmp = TempDir::new().unwrap();
        let err = delete_medium(tmp.path(), "macos", "nope").unwrap_err();
        match err {
            StoreError::Io { source, .. } => {
                assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
            }
            other => panic!("expected Io error, got {other:?}"),
        }
    }

    #[test]
    fn rename_moves_the_record_preserving_config() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (_, _, projection, _) = sample();
        write_projection(root, "macos", "old-name", &projection).unwrap();

        rename_projection(root, "macos", "old-name", "new-name").unwrap();

        assert!(
            !root
                .join(".memstead/projections/macos/old-name.json")
                .exists()
        );
        let configs = load_legacy_pipeline_configs(root).unwrap();
        assert_eq!(configs.projections.len(), 1);
        assert_eq!(configs.projections[0].name, "new-name");
        assert_eq!(configs.projections[0].config, projection);
    }

    #[test]
    fn rename_refuses_to_clobber_an_existing_target() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let (_, _, projection, _) = sample();
        write_projection(root, "macos", "a", &projection).unwrap();
        write_projection(root, "macos", "b", &projection).unwrap();

        let err = rename_projection(root, "macos", "a", "b").unwrap_err();
        assert!(matches!(err, StoreError::Other(_)), "got {err:?}");
        // Both records survive — nothing was lost.
        assert!(root.join(".memstead/projections/macos/a.json").exists());
        assert!(root.join(".memstead/projections/macos/b.json").exists());
    }

    #[test]
    fn rename_of_missing_source_surfaces_io_error() {
        let tmp = TempDir::new().unwrap();
        let err = rename_ingest(tmp.path(), "missing", "whatever").unwrap_err();
        assert!(matches!(err, StoreError::Io { .. }), "got {err:?}");
    }

    // ── binding v1 loader (D2 version gate) ──────────────────────────────

    fn sample_binding() -> BindingV1 {
        use crate::binding::{
            BINDING_VERSION, BuildMode, BuildOperation, CoverageSemantics, Operations,
        };
        use crate::pipeline::IngestTrigger;
        BindingV1 {
            version: BINDING_VERSION,
            intent: Some("prose".to_string()),
            source_facets: vec!["source-tree".to_string()],
            reference_mems: vec![],
            destination_mem: "engine".to_string(),
            deny_paths: vec![],
            coverage_semantics: CoverageSemantics::Exhaustive,
            rules: None,
            prune: None,
            operations: Operations {
                build: Some(BuildOperation {
                    mode: BuildMode::Discovery,
                    trigger: IngestTrigger::Loop,
                    batch_size: 20,
                    post_actions: None,
                }),
                sync: None,
                verify: None,
            },
        }
    }

    #[test]
    fn empty_store_loads_empty_binding_configs() {
        let tmp = TempDir::new().unwrap();
        let configs = load_pipeline_configs(tmp.path()).unwrap();
        assert_eq!(configs, BindingConfigs::default());
    }

    #[test]
    fn binding_loader_round_trips_a_v1_binding() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let binding = sample_binding();
        write_binding(root, "engine", "graph", &binding).unwrap();

        let configs = load_pipeline_configs(root).unwrap();
        assert_eq!(configs.bindings.len(), 1);
        assert_eq!(configs.bindings[0].mem, "engine");
        assert_eq!(configs.bindings[0].name, "graph");
        assert_eq!(configs.bindings[0].config, binding);
    }

    #[test]
    fn version_less_projection_refuses_with_migrate_naming_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        // A gen-2 (version-less) projection file.
        let projection = Projection {
            intent: Some("legacy".to_string()),
            source_facets: vec!["f".to_string()],
            reference_mems: vec![],
            destination_mem: "engine".to_string(),
            rules: None,
        };
        write_projection(root, "engine", "graph", &projection).unwrap();

        let err = load_pipeline_configs(root).unwrap_err();
        match err {
            StoreError::LegacyProjectionStore { path } => {
                assert!(path.ends_with("graph.json"), "got {path:?}");
                assert!(
                    err_message(&StoreError::LegacyProjectionStore { path })
                        .contains("memstead projection migrate")
                );
            }
            other => panic!("expected LegacyProjectionStore, got {other:?}"),
        }
    }

    #[test]
    fn unknown_binding_version_refuses() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let dir = root.join(".memstead/projections/engine");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("graph.json"),
            br#"{"version": 99, "destination_mem": "engine", "operations": {"build": {"mode": "discovery", "trigger": "loop", "batch_size": 20}}}"#,
        )
        .unwrap();

        let err = load_pipeline_configs(root).unwrap_err();
        assert!(
            matches!(err, StoreError::UnknownBindingVersion { version: 99, .. }),
            "got {err:?}"
        );
    }

    fn err_message(e: &StoreError) -> String {
        e.to_string()
    }
}