Skip to main content

memstead_base/
pipeline_edit.rs

1//! Edit operations over the v2 single-record pipeline store.
2//!
3//! Sits above the dumb file ops in [`crate::pipeline_store`]: each function
4//! loads the current store, enforces identity rules (no clobber, no silent
5//! overwrite), validates the candidate record in-place, then writes. The
6//! engine's in-memory `pipeline_configs` cache is refreshed by the `Engine`
7//! wrapper methods that call these — not here — so these functions stay pure
8//! disk ops that unit-test with a bare `TempDir`.
9//!
10//! One record kind, four verbs: a binding is created / patched / deleted /
11//! renamed under its `(mem, name)` file identity. The cross-record
12//! referential-integrity machinery of the three-file era (dangling facet /
13//! medium refs, delete-blocked-by-referrer, rename repointing) is gone with
14//! the references — **in-record source validation**
15//! ([`crate::binding::validate_binding`]) covers what remains: source name
16//! rules plus the medium-capability matrix.
17//!
18//! The JSON entry points ([`add_binding_json`] / [`update_binding_json`])
19//! accept a [`BindingPatch`] over the full author-editable record —
20//! `sources`, operations block, `deny_paths`, `coverage_semantics`, `rules`
21//! (clearable via explicit `null`), `prune` — with `version` engine-managed.
22//! A field absent from the payload is preserved from the stored record (the
23//! tail-preservation contract): edits merge over the stored record, never
24//! rebuild it from form fields.
25
26use std::path::Path;
27
28use serde::Deserialize;
29
30use crate::binding::{
31    BINDING_VERSION, Binding, BuildMode, BuildOperation, CapabilityError, CoverageSemantics,
32    Operations, PruneConfig, validate_binding,
33};
34use crate::engine::Engine;
35use crate::pipeline::{IngestTrigger, Source};
36use crate::pipeline_store::{self, BindingConfigs};
37use crate::workspace_store::StoreError;
38
39/// Failure modes of a pipeline edit. Distinct from the entity-centric
40/// [`crate::engine::EngineError`] — these describe binding-store edits.
41/// `key` is the display identity: `"<mem>/<name>"`.
42#[derive(Debug, thiserror::Error)]
43pub enum PipelineEditError {
44    /// The engine was not booted from a workspace root, so there is no
45    /// binding store to edit (e.g. an engine built from a bare mount
46    /// list in a test or in-memory consumer).
47    #[error("engine has no workspace root — pipeline edits require a workspace-backed engine")]
48    NoWorkspaceRoot,
49    /// The edit landed on disk but its provenance record (the
50    /// `__MEMSTEAD` mirror commit carrying the note) could not be
51    /// committed. The disk state is live; the audit trail is missing
52    /// this event — callers surface it rather than silently dropping
53    /// the note.
54    #[error("pipeline edit landed, but recording provenance failed: {0}")]
55    Provenance(String),
56    /// A create targeted a `(mem, name)` that already holds a record.
57    #[error("{primitive} '{key}' already exists")]
58    AlreadyExists {
59        primitive: &'static str,
60        key: String,
61    },
62    /// An update / delete / rename targeted a record that does not exist.
63    #[error("{primitive} '{key}' does not exist")]
64    NotFound {
65        primitive: &'static str,
66        key: String,
67    },
68    /// A rename target `(mem, new)` already holds a record.
69    #[error("rename target {primitive} '{key}' already exists")]
70    RenameTargetExists {
71        primitive: &'static str,
72        key: String,
73    },
74    /// A JSON-string edit entry point received a payload that did not
75    /// deserialize into the target shape.
76    #[error("invalid {primitive} JSON: {message}")]
77    InvalidJson {
78        primitive: &'static str,
79        message: String,
80    },
81    /// A binding edit was refused by in-record validation — a malformed
82    /// source (empty / duplicate name) or a medium-capability violation
83    /// (e.g. declaring `sync` over a medium with no change signal). Carries
84    /// only the refusals the edit would *introduce*: refusals the stored
85    /// record already produces never block an unrelated edit. Each refusal
86    /// message includes its remedy.
87    #[error(
88        "binding '{key}' edit refused by validation: {}",
89        format_refusals(refusals)
90    )]
91    Capability {
92        key: String,
93        refusals: Vec<CapabilityError>,
94    },
95    /// The write would put an intent into the record that names a
96    /// relationship the destination schema does not declare
97    /// ([`crate::ingest::intent`]). Refused on `init` and on an `edit` that
98    /// sets the intent; a stored record already carrying one keeps loading
99    /// and is reported on every brief instead. Nothing was written.
100    #[error(
101        "binding '{key}' intent refused: {}",
102        findings.iter().map(|f| f.to_string()).collect::<Vec<_>>().join("; ")
103    )]
104    IntentUnknownRelationship {
105        key: String,
106        findings: Vec<crate::ingest::intent::IntentFinding>,
107    },
108    /// Underlying store IO / parse failure.
109    #[error(transparent)]
110    Store(#[from] StoreError),
111}
112
113/// The destination schema a binding write is checked against: the pin as
114/// displayed (`software@0.5.0`) and the loaded schema. `None` when the
115/// destination mem is not mounted or carries no schema — there is no
116/// vocabulary to read, so the intent rule cannot apply and the write goes
117/// through (the brief's absent-destination note carries that case).
118pub type DestinationSchema<'a> = Option<(&'a str, &'a memstead_schema::Schema, &'a [String])>;
119
120/// The intent rule at a write front door: the intent about to be written,
121/// checked against the destination schema when one is at hand.
122fn refuse_unknown_intent(
123    key: String,
124    intent: Option<&str>,
125    schema: DestinationSchema<'_>,
126) -> Result<(), PipelineEditError> {
127    let Some((pin, schema, known)) = schema else {
128        return Ok(());
129    };
130    let findings = crate::ingest::intent::intent_findings(intent, pin, schema, known);
131    if findings.is_empty() {
132        Ok(())
133    } else {
134        Err(PipelineEditError::IntentUnknownRelationship { key, findings })
135    }
136}
137
138fn key(mem: &str, name: &str) -> String {
139    format!("{mem}/{name}")
140}
141
142fn format_refusals(refusals: &[CapabilityError]) -> String {
143    refusals
144        .iter()
145        .map(|r| r.to_string())
146        .collect::<Vec<_>>()
147        .join("; ")
148}
149
150fn binding_exists(c: &BindingConfigs, mem: &str, name: &str) -> bool {
151    c.bindings.iter().any(|r| r.mem == mem && r.name == name)
152}
153
154// --- Binding record (JSON patch) --------------------------------------------
155
156/// Deserialize helper distinguishing an absent field (outer `None` —
157/// preserve) from an explicit `null` (inner `None` — clear). serde's plain
158/// `Option<Option<T>>` collapses `null` to the outer `None`; wrapping the
159/// parsed value in `Some` keeps the two cases apart.
160fn patch_field<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
161where
162    D: serde::Deserializer<'de>,
163    T: serde::Deserialize<'de>,
164{
165    Option::<T>::deserialize(deserializer).map(Some)
166}
167
168/// A partial edit of a binding record, decoded from the JSON edit entry
169/// points ([`update_binding_json`] / [`add_binding_json`]).
170///
171/// **Patch semantics**: a field absent from the payload is preserved from
172/// the stored record — the tail-preservation guarantee extends to every
173/// field. A field present is applied. The natively-optional record fields
174/// (`intent`, `rules`, `prune`) additionally distinguish explicit `null`
175/// (clear) from absence (preserve). `sources` and `operations` are replaced
176/// as whole blocks when present: each is the unit of its authoring, so an
177/// entry absent from a supplied block is removed (for operations that is
178/// legal — an absent mutating op refuses at run time with its enable
179/// remedy).
180///
181/// `version` is engine-managed and never author input: a `version` key in
182/// the payload is ignored, like every unknown key (the format grows
183/// additively — tolerance is deliberate).
184#[derive(Debug, Default, Deserialize)]
185pub struct BindingPatch {
186    /// Set / clear (`null`) / preserve (absent) the binding's intent prose.
187    #[serde(default, deserialize_with = "patch_field")]
188    pub intent: Option<Option<String>>,
189    /// Replace the inline source list when present.
190    #[serde(default)]
191    pub sources: Option<Vec<Source>>,
192    /// Replace the read-only reference-mem list when present.
193    #[serde(default)]
194    pub reference_mems: Option<Vec<String>>,
195    /// Repoint the destination mem when present (`null` preserves — a
196    /// required record field cannot be cleared).
197    #[serde(default)]
198    pub destination_mem: Option<String>,
199    /// Replace the deny-path glob list when present.
200    #[serde(default)]
201    pub deny_paths: Option<Vec<String>>,
202    /// Replace the coverage claim when present. Patch semantics are
203    /// option-as-patch: absent (`None`) = leave untouched. This surface
204    /// therefore cannot express *clearing* a declaration back to
205    /// unstated — deliberate: clearing stays out of scope, an author
206    /// edits the declaration in the binding file itself.
207    #[serde(default)]
208    pub coverage_semantics: Option<CoverageSemantics>,
209    /// Set / clear (`null`) / preserve (absent) the free-form rules value.
210    #[serde(default, deserialize_with = "patch_field")]
211    pub rules: Option<Option<serde_json::Value>>,
212    /// Set / clear (`null`) / preserve (absent) the prune policy.
213    #[serde(default, deserialize_with = "patch_field")]
214    pub prune: Option<Option<PruneConfig>>,
215    /// Replace the whole operations block when present.
216    #[serde(default)]
217    pub operations: Option<Operations>,
218}
219
220impl BindingPatch {
221    /// Overlay this patch onto `binding` (patch semantics; `version`
222    /// untouched).
223    fn apply(self, binding: &mut Binding) {
224        if let Some(v) = self.intent {
225            binding.intent = v;
226        }
227        if let Some(v) = self.sources {
228            binding.sources = v;
229        }
230        if let Some(v) = self.reference_mems {
231            binding.reference_mems = v;
232        }
233        if let Some(v) = self.destination_mem {
234            binding.destination_mem = v;
235        }
236        if let Some(v) = self.deny_paths {
237            binding.deny_paths = v;
238        }
239        if let Some(v) = self.coverage_semantics {
240            binding.coverage_semantics = Some(v);
241        }
242        if let Some(v) = self.rules {
243            binding.rules = v;
244        }
245        if let Some(v) = self.prune {
246            binding.prune = v;
247        }
248        if let Some(v) = self.operations {
249            binding.operations = v;
250        }
251    }
252}
253
254/// The default scaffold a fresh binding is patched onto: version pinned, a
255/// default `build` block (discovery / loop / batch 20), sync and verify
256/// absent, everything else empty — the caller's patch overlays it.
257fn default_binding_scaffold() -> Binding {
258    Binding {
259        version: BINDING_VERSION,
260        intent: None,
261        sources: Vec::new(),
262        reference_mems: Vec::new(),
263        destination_mem: String::new(),
264        deny_paths: Vec::new(),
265        // Unstated: the scaffold asserts nothing — the effective value
266        // resolves per medium once sources are patched in.
267        coverage_semantics: None,
268        rules: None,
269        prune: None,
270        operations: Operations {
271            build: Some(BuildOperation {
272                mode: BuildMode::Discovery,
273                trigger: IngestTrigger::Loop,
274                batch_size: 20,
275                post_actions: None,
276            }),
277            sync: None,
278            verify: None,
279        },
280    }
281}
282
283/// Create a binding from a JSON [`BindingPatch`] applied to the default
284/// scaffold. Refuses when `(mem, name)` already holds a record
285/// ([`PipelineEditError::AlreadyExists`]), when the patch leaves
286/// `destination_mem` empty ([`PipelineEditError::InvalidJson`]), or when
287/// the candidate fails in-record validation
288/// ([`PipelineEditError::Capability`] — every refusal blocks; a fresh
289/// record has no pre-existing state to grandfather). Returns the written
290/// record.
291pub fn add_binding_json(
292    root: &Path,
293    mem: &str,
294    name: &str,
295    patch_json: &str,
296) -> Result<Binding, PipelineEditError> {
297    add_binding_json_against(root, mem, name, patch_json, None)
298}
299
300/// [`add_binding_json`] with the destination schema at hand: the created
301/// record's intent must name only relationships that schema declares
302/// ([`PipelineEditError::IntentUnknownRelationship`] otherwise, nothing
303/// written). `None` skips the rule — the destination has no vocabulary.
304pub fn add_binding_json_against(
305    root: &Path,
306    mem: &str,
307    name: &str,
308    patch_json: &str,
309    schema: DestinationSchema<'_>,
310) -> Result<Binding, PipelineEditError> {
311    let configs = pipeline_store::load_pipeline_configs_strict(root)?;
312    if binding_exists(&configs, mem, name) {
313        return Err(PipelineEditError::AlreadyExists {
314            primitive: "projection",
315            key: key(mem, name),
316        });
317    }
318    let patch: BindingPatch = parse_json(patch_json, "projection")?;
319    let mut binding = default_binding_scaffold();
320    patch.apply(&mut binding);
321    if binding.destination_mem.is_empty() {
322        return Err(PipelineEditError::InvalidJson {
323            primitive: "projection",
324            message: "destination_mem is required".to_string(),
325        });
326    }
327    if let Err(refusals) = validate_binding(&binding) {
328        return Err(PipelineEditError::Capability {
329            key: key(mem, name),
330            refusals,
331        });
332    }
333    refuse_unknown_intent(key(mem, name), binding.intent.as_deref(), schema)?;
334    pipeline_store::write_binding(root, mem, name, &binding)?;
335    Ok(binding)
336}
337
338/// Patch an existing binding from a JSON [`BindingPatch`] — the update path
339/// over the full author-editable record (`sources`, operations,
340/// `deny_paths`, `coverage_semantics`, `rules` including clearing,
341/// `prune`). Absent fields are preserved (the tail-preservation contract);
342/// explicit `null` clears `intent` / `rules` / `prune`; a present `sources`
343/// or `operations` block replaces that whole block; `version` stays
344/// engine-managed.
345///
346/// Refuses when the record does not exist
347/// ([`PipelineEditError::NotFound`]) or when the patch introduces a
348/// validation refusal the stored record did not already carry
349/// ([`PipelineEditError::Capability`] — pre-existing refusals never block
350/// an unrelated edit). Nothing is written on refusal. Returns the written
351/// record.
352pub fn update_binding_json(
353    root: &Path,
354    mem: &str,
355    name: &str,
356    patch_json: &str,
357) -> Result<Binding, PipelineEditError> {
358    update_binding_json_against(root, mem, name, patch_json, None)
359}
360
361/// [`update_binding_json`] with the destination schema at hand: a patch
362/// that SETS the intent must name only relationships that schema declares
363/// ([`PipelineEditError::IntentUnknownRelationship`] otherwise, nothing
364/// written). A patch that leaves the intent untouched, or clears it, is
365/// not a new intent and is never refused on its account — a stored record
366/// carrying an unknown token keeps loading, and the brief reports it.
367pub fn update_binding_json_against(
368    root: &Path,
369    mem: &str,
370    name: &str,
371    patch_json: &str,
372    schema: DestinationSchema<'_>,
373) -> Result<Binding, PipelineEditError> {
374    let configs = pipeline_store::load_pipeline_configs_strict(root)?;
375    if !binding_exists(&configs, mem, name) {
376        return Err(PipelineEditError::NotFound {
377            primitive: "projection",
378            key: key(mem, name),
379        });
380    }
381    let patch: BindingPatch = parse_json(patch_json, "projection")?;
382    let existing = pipeline_store::read_binding(root, mem, name)?;
383    let mut patched = existing.clone();
384    // Whether this patch SETS an intent (as opposed to preserving or
385    // clearing it) — the one case the intent rule applies to on update.
386    let sets_intent = matches!(patch.intent, Some(Some(_)));
387    patch.apply(&mut patched);
388    if let Err(refusals) = validate_binding(&patched) {
389        let before = validate_binding(&existing).err().unwrap_or_default();
390        let introduced: Vec<CapabilityError> = refusals
391            .into_iter()
392            .filter(|r| !before.contains(r))
393            .collect();
394        if !introduced.is_empty() {
395            return Err(PipelineEditError::Capability {
396                key: key(mem, name),
397                refusals: introduced,
398            });
399        }
400    }
401    if sets_intent {
402        refuse_unknown_intent(key(mem, name), patched.intent.as_deref(), schema)?;
403    }
404    pipeline_store::write_binding(root, mem, name, &patched)?;
405    Ok(patched)
406}
407
408/// Delete a binding. Refuses if `(mem, name)` does not exist. Nothing
409/// references a binding record, so there is no referential gate — the
410/// binding's own state files (advance / findings / watermarks) simply stop
411/// being consulted.
412pub fn delete_binding(root: &Path, mem: &str, name: &str) -> Result<(), PipelineEditError> {
413    let configs = pipeline_store::load_pipeline_configs_strict(root)?;
414    if !binding_exists(&configs, mem, name) {
415        return Err(PipelineEditError::NotFound {
416            primitive: "projection",
417            key: key(mem, name),
418        });
419    }
420    pipeline_store::delete_projection(root, mem, name)?;
421    Ok(())
422}
423
424/// Rename a binding within its mem (`old` → `new`, same `<mem>` tier). A
425/// binding has no embedded name, so a file move is its whole rename.
426/// Refuses a missing source or an existing target. No-op when `old == new`.
427pub fn rename_binding(
428    root: &Path,
429    mem: &str,
430    old: &str,
431    new: &str,
432) -> Result<(), PipelineEditError> {
433    if old == new {
434        return Ok(());
435    }
436    let configs = pipeline_store::load_pipeline_configs_strict(root)?;
437    if !binding_exists(&configs, mem, old) {
438        return Err(PipelineEditError::NotFound {
439            primitive: "projection",
440            key: key(mem, old),
441        });
442    }
443    if binding_exists(&configs, mem, new) {
444        return Err(PipelineEditError::RenameTargetExists {
445            primitive: "projection",
446            key: key(mem, new),
447        });
448    }
449    pipeline_store::rename_projection(root, mem, old, new)?;
450    Ok(())
451}
452
453// --- Engine surface --------------------------------------------------------
454//
455// Thin wrappers that route an edit through the free functions above (disk +
456// in-record validation) and then refresh the engine's in-memory
457// `pipeline_configs` snapshot so a subsequent `pipeline_configs()` read sees
458// the change. They use only the engine's public accessors, so this block stays
459// out of the `engine` module's internals.
460
461impl Engine {
462    fn pipeline_edit_root(&self) -> Result<std::path::PathBuf, PipelineEditError> {
463        self.workspace_root()
464            .map(Path::to_path_buf)
465            .ok_or(PipelineEditError::NoWorkspaceRoot)
466    }
467
468    fn refresh_pipeline_configs(&mut self, root: &Path) -> Result<(), PipelineEditError> {
469        self.set_pipeline_configs(pipeline_store::load_pipeline_configs_strict(root)?);
470        Ok(())
471    }
472
473    /// Provenance bridge with error translation: the disk write has
474    /// already landed when this runs, so a failure here is surfaced as
475    /// `Provenance` (edit live, audit record missing) rather than
476    /// rolling anything back.
477    fn pipeline_provenance(
478        &self,
479        mem: &str,
480        kind: &str,
481        edits: &[(String, Option<Vec<u8>>)],
482        note: Option<&str>,
483        verb: &str,
484    ) -> Result<(), PipelineEditError> {
485        self.record_pipeline_edit_provenance(mem, kind, edits, note, verb)
486            .map_err(|e| PipelineEditError::Provenance(e.to_string()))
487    }
488
489    /// The destination schema a binding write into `mem` is checked
490    /// against — the pin as displayed plus the loaded schema — or `None`
491    /// when this engine mounts no such mem or it carries no schema.
492    pub fn destination_schema_for(
493        &self,
494        mem: &str,
495    ) -> Option<(String, std::sync::Arc<memstead_schema::Schema>, Vec<String>)> {
496        let pin = self.schema_pin(mem)?.as_display();
497        let schema = self.schema_for(mem)?;
498        let known = crate::ingest::intent::known_relationship_names(self);
499        Some((pin, schema, known))
500    }
501
502    /// Create a binding from a JSON [`BindingPatch`] applied to the default
503    /// scaffold: the caller may supply any author-editable field, including
504    /// the inline `sources` and a full `operations` block; an absent block
505    /// scaffolds the default `build` (discovery / loop / batch 20). See
506    /// [`add_binding_json`] for the refusals (duplicate, missing
507    /// `destination_mem`, in-record validation).
508    pub fn add_projection_json(
509        &mut self,
510        mem: &str,
511        name: &str,
512        projection_json: &str,
513        note: Option<&str>,
514    ) -> Result<(), PipelineEditError> {
515        let root = self.pipeline_edit_root()?;
516        let binding = add_binding_json_against(
517            &root,
518            mem,
519            name,
520            projection_json,
521            self.destination_schema_for(mem)
522                .as_ref()
523                .map(|(p, s, k)| (p.as_str(), &**s, k.as_slice())),
524        )?;
525        self.record_binding_edit(mem, name, &binding, &root, note, "add")
526    }
527
528    /// Patch a binding from a JSON [`BindingPatch`] — absent fields are
529    /// preserved (tail preservation, extended to every field); explicit
530    /// `null` clears `intent` / `rules` / `prune`; a present `sources` or
531    /// `operations` block replaces that whole block; `version` stays
532    /// engine-managed. See [`update_binding_json`] for the refusals
533    /// (not-found, in-record validation).
534    pub fn update_projection_json(
535        &mut self,
536        mem: &str,
537        name: &str,
538        projection_json: &str,
539        note: Option<&str>,
540    ) -> Result<(), PipelineEditError> {
541        let root = self.pipeline_edit_root()?;
542        let binding = update_binding_json_against(
543            &root,
544            mem,
545            name,
546            projection_json,
547            self.destination_schema_for(mem)
548                .as_ref()
549                .map(|(p, s, k)| (p.as_str(), &**s, k.as_slice())),
550        )?;
551        self.record_binding_edit(mem, name, &binding, &root, note, "update")
552    }
553
554    /// Delete a binding and refresh the snapshot. See [`delete_binding`].
555    pub fn delete_projection(
556        &mut self,
557        mem: &str,
558        name: &str,
559        note: Option<&str>,
560    ) -> Result<(), PipelineEditError> {
561        let root = self.pipeline_edit_root()?;
562        delete_binding(&root, mem, name)?;
563        self.pipeline_provenance(
564            mem,
565            "projections",
566            &[(name.to_string(), None)],
567            note,
568            "delete",
569        )?;
570        self.refresh_pipeline_configs(&root)
571    }
572
573    /// Rename a binding and refresh the snapshot. See [`rename_binding`].
574    pub fn rename_projection(
575        &mut self,
576        mem: &str,
577        old: &str,
578        new: &str,
579        note: Option<&str>,
580    ) -> Result<(), PipelineEditError> {
581        let root = self.pipeline_edit_root()?;
582        rename_binding(&root, mem, old, new)?;
583        // Mirror the rename as remove-old + upsert-new in one commit.
584        // The in-memory snapshot still holds the record under its old
585        // name here (refresh runs after), and a rename changes the
586        // name only — the config bytes are those of the old record.
587        let bytes = self
588            .pipeline_configs()
589            .bindings
590            .iter()
591            .find(|r| r.mem == mem && r.name == old)
592            .map(|r| serde_json::to_vec_pretty(&r.config))
593            .transpose()
594            .map_err(|e| PipelineEditError::InvalidJson {
595                primitive: "config",
596                message: e.to_string(),
597            })?;
598        self.pipeline_provenance(
599            mem,
600            "projections",
601            &[(old.to_string(), None), (new.to_string(), bytes)],
602            note,
603            "rename",
604        )?;
605        self.refresh_pipeline_configs(&root)
606    }
607
608    /// Shared provenance + refresh tail for the binding edit path: the disk
609    /// write has already landed in the free function; record the edit's
610    /// mirror commit and refresh the in-memory snapshot.
611    fn record_binding_edit(
612        &mut self,
613        mem: &str,
614        name: &str,
615        binding: &Binding,
616        root: &Path,
617        note: Option<&str>,
618        verb: &str,
619    ) -> Result<(), PipelineEditError> {
620        let bytes =
621            serde_json::to_vec_pretty(binding).map_err(|e| PipelineEditError::InvalidJson {
622                primitive: "config",
623                message: e.to_string(),
624            })?;
625        self.pipeline_provenance(
626            mem,
627            "projections",
628            &[(name.to_string(), Some(bytes))],
629            note,
630            verb,
631        )?;
632        self.refresh_pipeline_configs(root)
633    }
634}
635
636/// Deserialize a pipeline shape from JSON, mapping a parse failure to a
637/// typed [`PipelineEditError::InvalidJson`] naming the shape.
638fn parse_json<T: serde::de::DeserializeOwned>(
639    json: &str,
640    primitive: &'static str,
641) -> Result<T, PipelineEditError> {
642    serde_json::from_str(json).map_err(|e| PipelineEditError::InvalidJson {
643        primitive,
644        message: e.to_string(),
645    })
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651    use crate::binding::SyncOperation;
652    use tempfile::TempDir;
653
654    /// The base payload with one inline codebase source.
655    const BASE_PAYLOAD: &str = r#"{
656        "intent": "i",
657        "sources": [{
658            "name": "f",
659            "type": "codebase",
660            "pointer": "../src",
661            "scope": [{ "path": "**/*.rs", "mode": "allow" }]
662        }],
663        "reference_mems": [],
664        "destination_mem": "v",
665        "rules": { "routing": "r" }
666    }"#;
667
668    /// The full record used by the update tests: build+sync+verify over the
669    /// codebase source, deny_paths, curated coverage, rules, prune.
670    fn full_binding_payload() -> &'static str {
671        r#"{
672          "intent": "i",
673          "sources": [{
674              "name": "f",
675              "type": "codebase",
676              "pointer": "../src",
677              "scope": [{ "path": "**/*.rs", "mode": "allow" }]
678          }],
679          "reference_mems": ["r"],
680          "destination_mem": "v",
681          "deny_paths": ["dev/**"],
682          "coverage_semantics": "curated",
683          "rules": { "routing": "r" },
684          "prune": {},
685          "operations": {
686            "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
687            "sync": { "trigger": "manual", "batch_size": 20 },
688            "verify": { "trigger": "manual", "batch_size": 20 }
689          }
690        }"#
691    }
692
693    /// A payload creates a binding scaffolded with the default build block;
694    /// the inline source is written as given.
695    #[test]
696    fn add_binding_json_scaffolds_default_build() {
697        let tmp = TempDir::new().unwrap();
698        let root = tmp.path();
699        let b = add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
700        assert_eq!(b.version, BINDING_VERSION);
701        let build = b.operations.build.as_ref().unwrap();
702        assert_eq!(build.mode, BuildMode::Discovery);
703        assert_eq!(build.batch_size, 20);
704        assert!(b.operations.sync.is_none() && b.operations.verify.is_none());
705        assert_eq!(b.rules, Some(serde_json::json!({ "routing": "r" })));
706        assert_eq!(b.sources.len(), 1);
707        assert_eq!(b.sources[0].name, "f");
708        assert_eq!(pipeline_store::read_binding(root, "v", "p").unwrap(), b);
709    }
710
711    /// A payload declaring the full record — operations block, deny_paths,
712    /// coverage, prune — is written as given (the scaffold is only a fallback).
713    #[test]
714    fn add_binding_json_accepts_the_full_record() {
715        let tmp = TempDir::new().unwrap();
716        let root = tmp.path();
717        let b = add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
718        assert_eq!(
719            b.operations.build.as_ref().unwrap().mode,
720            BuildMode::Discovery
721        );
722        assert_eq!(b.operations.sync.as_ref().unwrap().batch_size, 20);
723        assert!(b.operations.verify.is_some());
724        assert_eq!(b.deny_paths, vec!["dev/**"]);
725        assert_eq!(b.coverage_semantics, Some(CoverageSemantics::Curated));
726        assert!(b.prune.is_some(), "the prune block is written as given");
727    }
728
729    #[test]
730    fn add_binding_json_refuses_duplicate() {
731        let tmp = TempDir::new().unwrap();
732        let root = tmp.path();
733        add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
734        let err = add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap_err();
735        assert!(
736            matches!(err, PipelineEditError::AlreadyExists { .. }),
737            "got {err:?}"
738        );
739    }
740
741    #[test]
742    fn add_binding_json_requires_destination_mem() {
743        let tmp = TempDir::new().unwrap();
744        let err = add_binding_json(tmp.path(), "v", "p", r#"{"intent":"i"}"#).unwrap_err();
745        match err {
746            PipelineEditError::InvalidJson { message, .. } => {
747                assert!(message.contains("destination_mem"), "got: {message}")
748            }
749            other => panic!("expected InvalidJson, got {other:?}"),
750        }
751    }
752
753    /// REFUSAL: a malformed source (duplicate name)
754    /// blocks a create with a typed validation error; nothing lands on disk.
755    #[test]
756    fn add_binding_json_refuses_duplicate_source_names() {
757        let tmp = TempDir::new().unwrap();
758        let root = tmp.path();
759        let err = add_binding_json(
760            root,
761            "v",
762            "p",
763            r#"{
764              "sources": [
765                { "name": "dup", "type": "codebase", "pointer": "../a" },
766                { "name": "dup", "type": "codebase", "pointer": "../b" }
767              ],
768              "destination_mem": "v"
769            }"#,
770        )
771        .unwrap_err();
772        match err {
773            PipelineEditError::Capability { refusals, .. } => {
774                assert!(
775                    refusals.iter().any(|r| matches!(
776                        r,
777                        CapabilityError::DuplicateSourceName { name } if name == "dup"
778                    )),
779                    "expected DuplicateSourceName, got {refusals:?}"
780                );
781            }
782            other => panic!("expected Capability, got {other:?}"),
783        }
784        assert!(!root.join(".memstead/projections/v/p.json").exists());
785    }
786
787    /// The capability matrix at the edit seam: declaring sync over a web
788    /// (change-signal-less) source refuses at add time with the matrix's
789    /// typed message.
790    #[test]
791    fn add_binding_json_refuses_capability_violation() {
792        let tmp = TempDir::new().unwrap();
793        let root = tmp.path();
794        let err = add_binding_json(
795            root,
796            "v",
797            "p",
798            r#"{
799              "sources": [{ "name": "wf", "type": "web", "pointer": "https://example.com" }],
800              "destination_mem": "v",
801              "operations": {
802                "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
803                "sync": { "trigger": "manual", "batch_size": 20 }
804              }
805            }"#,
806        )
807        .unwrap_err();
808        match &err {
809            PipelineEditError::Capability { refusals, .. } => {
810                assert!(
811                    refusals.iter().any(|r| matches!(
812                        r,
813                        CapabilityError::OperationOutOfScope { operation, .. } if *operation == "sync"
814                    )),
815                    "expected an OperationOutOfScope(sync) refusal, got {refusals:?}"
816                );
817            }
818            other => panic!("expected Capability, got {other:?}"),
819        }
820        assert!(pipeline_store::read_binding(root, "v", "p").is_err());
821    }
822
823    /// Patch semantics: a single-field patch preserves every sibling field —
824    /// the tail-preservation property, extended to the full record.
825    #[test]
826    fn update_binding_json_patch_preserves_untouched_fields() {
827        let tmp = TempDir::new().unwrap();
828        let root = tmp.path();
829        let before = add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
830        let after = update_binding_json(root, "v", "p", r#"{"intent":"new"}"#).unwrap();
831        assert_eq!(after.intent.as_deref(), Some("new"));
832        assert_eq!(after.version, before.version);
833        assert_eq!(after.sources, before.sources);
834        assert_eq!(after.reference_mems, before.reference_mems);
835        assert_eq!(after.destination_mem, before.destination_mem);
836        assert_eq!(after.deny_paths, before.deny_paths);
837        assert_eq!(after.coverage_semantics, before.coverage_semantics);
838        assert_eq!(after.rules, before.rules);
839        assert_eq!(after.prune, before.prune);
840        assert_eq!(after.operations, before.operations);
841    }
842
843    /// Explicit `null` clears the natively-optional fields; absence preserves
844    /// them.
845    #[test]
846    fn update_binding_json_null_clears_and_absence_preserves() {
847        let tmp = TempDir::new().unwrap();
848        let root = tmp.path();
849        add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
850
851        // Absent rules/prune/intent → preserved.
852        let untouched = update_binding_json(root, "v", "p", r#"{"deny_paths":[]}"#).unwrap();
853        assert!(untouched.rules.is_some() && untouched.prune.is_some());
854        assert_eq!(untouched.intent.as_deref(), Some("i"));
855        assert!(untouched.deny_paths.is_empty());
856
857        // Explicit null → cleared.
858        let cleared =
859            update_binding_json(root, "v", "p", r#"{"rules": null, "prune": null}"#).unwrap();
860        assert!(cleared.rules.is_none() && cleared.prune.is_none());
861        assert_eq!(cleared.intent.as_deref(), Some("i"), "intent untouched");
862        assert_eq!(
863            pipeline_store::read_binding(root, "v", "p").unwrap(),
864            cleared
865        );
866    }
867
868    /// A present `operations` block replaces the whole block: ops absent from
869    /// the supplied block are removed (legal — refusal happens at run time).
870    /// A present `sources` block likewise replaces the whole source list.
871    #[test]
872    fn update_binding_json_replaces_whole_blocks() {
873        let tmp = TempDir::new().unwrap();
874        let root = tmp.path();
875        add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
876        let after = update_binding_json(
877            root,
878            "v",
879            "p",
880            r#"{"operations": { "build": { "mode": "discovery", "trigger": "manual", "batch_size": 9 } }}"#,
881        )
882        .unwrap();
883        assert_eq!(after.operations.build.as_ref().unwrap().batch_size, 9);
884        assert!(
885            after.operations.sync.is_none(),
886            "sync removed with the block"
887        );
888        assert!(
889            after.operations.verify.is_none(),
890            "verify removed with the block"
891        );
892        assert_eq!(after.rules, Some(serde_json::json!({ "routing": "r" })));
893
894        let after = update_binding_json(
895            root,
896            "v",
897            "p",
898            r#"{"sources": [{ "name": "g", "type": "filesystem", "pointer": "../docs" }]}"#,
899        )
900        .unwrap();
901        assert_eq!(after.sources.len(), 1);
902        assert_eq!(after.sources[0].name, "g");
903    }
904
905    /// The update seam refuses an *introduced* capability violation, and the
906    /// stored record stays byte-identical.
907    #[test]
908    fn update_binding_json_refuses_introduced_capability_violation() {
909        let tmp = TempDir::new().unwrap();
910        let root = tmp.path();
911        let before = add_binding_json(
912            root,
913            "v",
914            "p",
915            r#"{
916              "sources": [{ "name": "wf", "type": "web", "pointer": "https://example.com" }],
917              "destination_mem": "v"
918            }"#,
919        )
920        .unwrap();
921        let err = update_binding_json(
922            root,
923            "v",
924            "p",
925            r#"{"operations": {
926              "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
927              "sync": { "trigger": "manual", "batch_size": 20 }
928            }}"#,
929        )
930        .unwrap_err();
931        assert!(
932            matches!(err, PipelineEditError::Capability { .. }),
933            "got {err:?}"
934        );
935        assert_eq!(
936            pipeline_store::read_binding(root, "v", "p").unwrap(),
937            before,
938            "record unchanged on refusal"
939        );
940    }
941
942    /// A refusal the stored record already produces never blocks an unrelated
943    /// edit — pre-existing config is not this edit's to answer for.
944    #[test]
945    fn update_binding_json_allows_edit_despite_preexisting_refusal() {
946        let tmp = TempDir::new().unwrap();
947        let root = tmp.path();
948        // Bypass validation: a sync-over-web binding already on disk (the
949        // store layer is dumb on purpose).
950        let broken = Binding {
951            version: BINDING_VERSION,
952            intent: None,
953            sources: vec![Source {
954                name: "wf".to_string(),
955                medium_type: crate::pipeline::MediumType::Web,
956                pointer: "https://example.com".to_string(),
957                change_detection: None,
958                scope: vec![],
959                engagement: None,
960                preparation: None,
961            }],
962            reference_mems: vec![],
963            destination_mem: "v".to_string(),
964            deny_paths: vec![],
965            coverage_semantics: None,
966            rules: None,
967            prune: None,
968            operations: Operations {
969                build: Some(BuildOperation {
970                    mode: BuildMode::Discovery,
971                    trigger: IngestTrigger::Loop,
972                    batch_size: 20,
973                    post_actions: None,
974                }),
975                sync: Some(SyncOperation {
976                    trigger: IngestTrigger::Manual,
977                    batch_size: 20,
978                }),
979                verify: None,
980            },
981        };
982        pipeline_store::write_binding(root, "v", "p", &broken).unwrap();
983
984        let after = update_binding_json(root, "v", "p", r#"{"intent":"fixed"}"#).unwrap();
985        assert_eq!(after.intent.as_deref(), Some("fixed"));
986        assert!(
987            after.operations.sync.is_some(),
988            "pre-existing sync survives"
989        );
990
991        // But a patch introducing a NEW refusal (duplicate source names) blocks.
992        let err = update_binding_json(
993            root,
994            "v",
995            "p",
996            r#"{"sources": [
997                { "name": "dup", "type": "web", "pointer": "https://a" },
998                { "name": "dup", "type": "web", "pointer": "https://b" }
999            ]}"#,
1000        )
1001        .unwrap_err();
1002        assert!(
1003            matches!(err, PipelineEditError::Capability { .. }),
1004            "got {err:?}"
1005        );
1006    }
1007
1008    #[test]
1009    fn update_binding_json_refuses_missing_record() {
1010        let tmp = TempDir::new().unwrap();
1011        let err = update_binding_json(tmp.path(), "v", "p", r#"{"intent":"x"}"#).unwrap_err();
1012        assert!(
1013            matches!(err, PipelineEditError::NotFound { .. }),
1014            "got {err:?}"
1015        );
1016    }
1017
1018    /// Unknown additive keys are tolerated and `version` is engine-managed —
1019    /// a payload carrying either never fails, never moves the version.
1020    #[test]
1021    fn update_binding_json_ignores_unknown_keys_and_version() {
1022        let tmp = TempDir::new().unwrap();
1023        let root = tmp.path();
1024        add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
1025        let after = update_binding_json(
1026            root,
1027            "v",
1028            "p",
1029            r#"{"version": 99, "future_key": { "x": 1 }, "intent": "i2"}"#,
1030        )
1031        .unwrap();
1032        assert_eq!(
1033            after.version, BINDING_VERSION,
1034            "version stays engine-managed"
1035        );
1036        assert_eq!(after.intent.as_deref(), Some("i2"));
1037    }
1038
1039    #[test]
1040    fn delete_binding_removes_the_record() {
1041        let tmp = TempDir::new().unwrap();
1042        let root = tmp.path();
1043        add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
1044        delete_binding(root, "v", "p").unwrap();
1045        assert!(!root.join(".memstead/projections/v/p.json").exists());
1046        let err = delete_binding(root, "v", "p").unwrap_err();
1047        assert!(
1048            matches!(err, PipelineEditError::NotFound { .. }),
1049            "got {err:?}"
1050        );
1051    }
1052
1053    #[test]
1054    fn rename_binding_moves_the_record() {
1055        let tmp = TempDir::new().unwrap();
1056        let root = tmp.path();
1057        let created = add_binding_json(root, "v", "old", BASE_PAYLOAD).unwrap();
1058        rename_binding(root, "v", "old", "new").unwrap();
1059        assert!(!root.join(".memstead/projections/v/old.json").exists());
1060        assert_eq!(
1061            pipeline_store::read_binding(root, "v", "new").unwrap(),
1062            created
1063        );
1064    }
1065
1066    #[test]
1067    fn rename_binding_refuses_existing_target_and_missing_source() {
1068        let tmp = TempDir::new().unwrap();
1069        let root = tmp.path();
1070        add_binding_json(root, "v", "a", BASE_PAYLOAD).unwrap();
1071        add_binding_json(root, "v", "b", BASE_PAYLOAD).unwrap();
1072        let err = rename_binding(root, "v", "a", "b").unwrap_err();
1073        assert!(
1074            matches!(err, PipelineEditError::RenameTargetExists { .. }),
1075            "got {err:?}"
1076        );
1077        let err = rename_binding(root, "v", "missing", "c").unwrap_err();
1078        assert!(
1079            matches!(err, PipelineEditError::NotFound { .. }),
1080            "got {err:?}"
1081        );
1082        // No-op rename is fine.
1083        rename_binding(root, "v", "a", "a").unwrap();
1084    }
1085
1086    /// REFUSAL: editing a store that holds a
1087    /// retired-format (pre-v2) file surfaces the loader's typed refusal —
1088    /// the edit layer never writes over a legacy store.
1089    #[test]
1090    fn editing_a_pre_v2_store_refuses_as_legacy() {
1091        let tmp = TempDir::new().unwrap();
1092        let root = tmp.path();
1093        let dir = root.join(".memstead/projections/v");
1094        std::fs::create_dir_all(&dir).unwrap();
1095        std::fs::write(
1096            dir.join("p.json"),
1097            br#"{"version": 1, "source_facets": ["f"], "destination_mem": "v", "operations": {}}"#,
1098        )
1099        .unwrap();
1100        let err = add_binding_json(root, "v", "q", BASE_PAYLOAD).unwrap_err();
1101        match err {
1102            PipelineEditError::Store(StoreError::LegacyProjectionStore { .. }) => {}
1103            other => panic!("expected LegacyProjectionStore, got {other:?}"),
1104        }
1105    }
1106}