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