1use 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#[derive(Debug, thiserror::Error)]
43pub enum PipelineEditError {
44 #[error("engine has no workspace root — pipeline edits require a workspace-backed engine")]
48 NoWorkspaceRoot,
49 #[error("pipeline edit landed, but recording provenance failed: {0}")]
55 Provenance(String),
56 #[error("{primitive} '{key}' already exists")]
58 AlreadyExists {
59 primitive: &'static str,
60 key: String,
61 },
62 #[error("{primitive} '{key}' does not exist")]
64 NotFound {
65 primitive: &'static str,
66 key: String,
67 },
68 #[error("rename target {primitive} '{key}' already exists")]
70 RenameTargetExists {
71 primitive: &'static str,
72 key: String,
73 },
74 #[error("invalid {primitive} JSON: {message}")]
77 InvalidJson {
78 primitive: &'static str,
79 message: String,
80 },
81 #[error(
88 "binding '{key}' edit refused by validation: {}",
89 format_refusals(refusals)
90 )]
91 Capability {
92 key: String,
93 refusals: Vec<CapabilityError>,
94 },
95 #[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 #[error(transparent)]
110 Store(#[from] StoreError),
111}
112
113pub type DestinationSchema<'a> = Option<(&'a str, &'a memstead_schema::Schema, &'a [String])>;
119
120fn 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::binding_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
154fn 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#[derive(Debug, Default, Deserialize)]
185pub struct BindingPatch {
186 #[serde(default, deserialize_with = "patch_field")]
188 pub intent: Option<Option<String>>,
189 #[serde(default)]
191 pub sources: Option<Vec<Source>>,
192 #[serde(default)]
194 pub reference_mems: Option<Vec<String>>,
195 #[serde(default)]
198 pub destination_mem: Option<String>,
199 #[serde(default)]
201 pub deny_paths: Option<Vec<String>>,
202 #[serde(default)]
208 pub coverage_semantics: Option<CoverageSemantics>,
209 #[serde(default, deserialize_with = "patch_field")]
211 pub rules: Option<Option<serde_json::Value>>,
212 #[serde(default, deserialize_with = "patch_field")]
214 pub prune: Option<Option<PruneConfig>>,
215 #[serde(default)]
217 pub operations: Option<Operations>,
218}
219
220impl BindingPatch {
221 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
254fn 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 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
283pub 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
300pub 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
338pub 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
361pub 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 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
408pub 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
424pub 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
453fn binding_edit_bytes(binding: &Binding) -> Result<Vec<u8>, PipelineEditError> {
455 serde_json::to_vec_pretty(binding).map_err(|e| PipelineEditError::InvalidJson {
456 primitive: "config",
457 message: e.to_string(),
458 })
459}
460
461impl Engine {
470 fn pipeline_edit_root(&self) -> Result<std::path::PathBuf, PipelineEditError> {
471 self.workspace_root()
472 .map(Path::to_path_buf)
473 .ok_or(PipelineEditError::NoWorkspaceRoot)
474 }
475
476 fn refresh_pipeline_configs(&mut self, root: &Path) -> Result<(), PipelineEditError> {
477 self.set_pipeline_configs(pipeline_store::load_pipeline_configs_strict(root)?);
478 Ok(())
479 }
480
481 fn pipeline_provenance(
486 &self,
487 mem: &str,
488 kind: &str,
489 edits: &[(String, Option<Vec<u8>>)],
490 note: Option<&str>,
491 verb: &str,
492 ) -> Result<(), PipelineEditError> {
493 self.record_pipeline_edit_provenance(mem, kind, edits, note, verb)
494 .map_err(|e| PipelineEditError::Provenance(e.to_string()))
495 }
496
497 pub fn destination_schema_for(
501 &self,
502 mem: &str,
503 ) -> Option<(String, std::sync::Arc<memstead_schema::Schema>, Vec<String>)> {
504 let pin = self.schema_pin(mem)?.as_display();
505 let schema = self.schema_for(mem)?;
506 let known = crate::binding_intent::known_relationship_names(self);
507 Some((pin, schema, known))
508 }
509
510 pub fn add_projection_json(
517 &mut self,
518 mem: &str,
519 name: &str,
520 projection_json: &str,
521 note: Option<&str>,
522 ) -> Result<Binding, PipelineEditError> {
523 let root = self.pipeline_edit_root()?;
524 let binding = add_binding_json_against(
525 &root,
526 mem,
527 name,
528 projection_json,
529 self.destination_schema_for(mem)
530 .as_ref()
531 .map(|(p, s, k)| (p.as_str(), &**s, k.as_slice())),
532 )?;
533 self.record_binding_edit(mem, name, &binding, &root, note, "add")?;
534 Ok(binding)
535 }
536
537 pub fn write_projection_record(
550 &mut self,
551 mem: &str,
552 name: &str,
553 binding: &Binding,
554 verb: &str,
555 note: Option<&str>,
556 ) -> Result<(), PipelineEditError> {
557 let root = self.pipeline_edit_root()?;
558 pipeline_store::write_binding(&root, mem, name, binding)?;
559 let bytes = binding_edit_bytes(binding)?;
560 self.pipeline_provenance(
561 mem,
562 "projections",
563 &[(name.to_string(), Some(bytes))],
564 note,
565 verb,
566 )?;
567 self.set_pipeline_configs(pipeline_store::load_pipeline_configs(&root)?);
568 Ok(())
569 }
570
571 pub fn update_projection_json(
578 &mut self,
579 mem: &str,
580 name: &str,
581 projection_json: &str,
582 note: Option<&str>,
583 ) -> Result<Binding, PipelineEditError> {
584 let root = self.pipeline_edit_root()?;
585 let binding = update_binding_json_against(
586 &root,
587 mem,
588 name,
589 projection_json,
590 self.destination_schema_for(mem)
591 .as_ref()
592 .map(|(p, s, k)| (p.as_str(), &**s, k.as_slice())),
593 )?;
594 self.record_binding_edit(mem, name, &binding, &root, note, "update")?;
595 Ok(binding)
596 }
597
598 pub fn delete_projection(
600 &mut self,
601 mem: &str,
602 name: &str,
603 note: Option<&str>,
604 ) -> Result<(), PipelineEditError> {
605 let root = self.pipeline_edit_root()?;
606 delete_binding(&root, mem, name)?;
607 self.pipeline_provenance(
608 mem,
609 "projections",
610 &[(name.to_string(), None)],
611 note,
612 "delete",
613 )?;
614 self.refresh_pipeline_configs(&root)
615 }
616
617 pub fn rename_projection(
619 &mut self,
620 mem: &str,
621 old: &str,
622 new: &str,
623 note: Option<&str>,
624 ) -> Result<(), PipelineEditError> {
625 let root = self.pipeline_edit_root()?;
626 rename_binding(&root, mem, old, new)?;
627 let bytes = self
632 .pipeline_configs()
633 .bindings
634 .iter()
635 .find(|r| r.mem == mem && r.name == old)
636 .map(|r| serde_json::to_vec_pretty(&r.config))
637 .transpose()
638 .map_err(|e| PipelineEditError::InvalidJson {
639 primitive: "config",
640 message: e.to_string(),
641 })?;
642 self.pipeline_provenance(
643 mem,
644 "projections",
645 &[(old.to_string(), None), (new.to_string(), bytes)],
646 note,
647 "rename",
648 )?;
649 self.refresh_pipeline_configs(&root)
650 }
651
652 fn record_binding_edit(
656 &mut self,
657 mem: &str,
658 name: &str,
659 binding: &Binding,
660 root: &Path,
661 note: Option<&str>,
662 verb: &str,
663 ) -> Result<(), PipelineEditError> {
664 let bytes = binding_edit_bytes(binding)?;
665 self.pipeline_provenance(
666 mem,
667 "projections",
668 &[(name.to_string(), Some(bytes))],
669 note,
670 verb,
671 )?;
672 self.refresh_pipeline_configs(root)
673 }
674}
675
676fn parse_json<T: serde::de::DeserializeOwned>(
679 json: &str,
680 primitive: &'static str,
681) -> Result<T, PipelineEditError> {
682 serde_json::from_str(json).map_err(|e| PipelineEditError::InvalidJson {
683 primitive,
684 message: e.to_string(),
685 })
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691 use crate::binding::SyncOperation;
692 use tempfile::TempDir;
693
694 const BASE_PAYLOAD: &str = r#"{
696 "intent": "i",
697 "sources": [{
698 "name": "f",
699 "type": "codebase",
700 "pointer": "../src",
701 "scope": [{ "path": "**/*.rs", "mode": "allow" }]
702 }],
703 "reference_mems": [],
704 "destination_mem": "v",
705 "rules": { "routing": "r" }
706 }"#;
707
708 fn full_binding_payload() -> &'static str {
711 r#"{
712 "intent": "i",
713 "sources": [{
714 "name": "f",
715 "type": "codebase",
716 "pointer": "../src",
717 "scope": [{ "path": "**/*.rs", "mode": "allow" }]
718 }],
719 "reference_mems": ["r"],
720 "destination_mem": "v",
721 "deny_paths": ["dev/**"],
722 "coverage_semantics": "curated",
723 "rules": { "routing": "r" },
724 "prune": {},
725 "operations": {
726 "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
727 "sync": { "trigger": "manual", "batch_size": 20 },
728 "verify": { "trigger": "manual", "batch_size": 20 }
729 }
730 }"#
731 }
732
733 #[test]
736 fn add_binding_json_scaffolds_default_build() {
737 let tmp = TempDir::new().unwrap();
738 let root = tmp.path();
739 let b = add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
740 assert_eq!(b.version, BINDING_VERSION);
741 let build = b.operations.build.as_ref().unwrap();
742 assert_eq!(build.mode, BuildMode::Discovery);
743 assert_eq!(build.batch_size, 20);
744 assert!(b.operations.sync.is_none() && b.operations.verify.is_none());
745 assert_eq!(b.rules, Some(serde_json::json!({ "routing": "r" })));
746 assert_eq!(b.sources.len(), 1);
747 assert_eq!(b.sources[0].name, "f");
748 assert_eq!(pipeline_store::read_binding(root, "v", "p").unwrap(), b);
749 }
750
751 #[test]
754 fn add_binding_json_accepts_the_full_record() {
755 let tmp = TempDir::new().unwrap();
756 let root = tmp.path();
757 let b = add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
758 assert_eq!(
759 b.operations.build.as_ref().unwrap().mode,
760 BuildMode::Discovery
761 );
762 assert_eq!(b.operations.sync.as_ref().unwrap().batch_size, 20);
763 assert!(b.operations.verify.is_some());
764 assert_eq!(b.deny_paths, vec!["dev/**"]);
765 assert_eq!(b.coverage_semantics, Some(CoverageSemantics::Curated));
766 assert!(b.prune.is_some(), "the prune block is written as given");
767 }
768
769 #[test]
770 fn add_binding_json_refuses_duplicate() {
771 let tmp = TempDir::new().unwrap();
772 let root = tmp.path();
773 add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
774 let err = add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap_err();
775 assert!(
776 matches!(err, PipelineEditError::AlreadyExists { .. }),
777 "got {err:?}"
778 );
779 }
780
781 #[test]
782 fn add_binding_json_requires_destination_mem() {
783 let tmp = TempDir::new().unwrap();
784 let err = add_binding_json(tmp.path(), "v", "p", r#"{"intent":"i"}"#).unwrap_err();
785 match err {
786 PipelineEditError::InvalidJson { message, .. } => {
787 assert!(message.contains("destination_mem"), "got: {message}")
788 }
789 other => panic!("expected InvalidJson, got {other:?}"),
790 }
791 }
792
793 #[test]
796 fn add_binding_json_refuses_duplicate_source_names() {
797 let tmp = TempDir::new().unwrap();
798 let root = tmp.path();
799 let err = add_binding_json(
800 root,
801 "v",
802 "p",
803 r#"{
804 "sources": [
805 { "name": "dup", "type": "codebase", "pointer": "../a" },
806 { "name": "dup", "type": "codebase", "pointer": "../b" }
807 ],
808 "destination_mem": "v"
809 }"#,
810 )
811 .unwrap_err();
812 match err {
813 PipelineEditError::Capability { refusals, .. } => {
814 assert!(
815 refusals.iter().any(|r| matches!(
816 r,
817 CapabilityError::DuplicateSourceName { name } if name == "dup"
818 )),
819 "expected DuplicateSourceName, got {refusals:?}"
820 );
821 }
822 other => panic!("expected Capability, got {other:?}"),
823 }
824 assert!(!root.join(".memstead/projections/v/p.json").exists());
825 }
826
827 #[test]
831 fn add_binding_json_refuses_capability_violation() {
832 let tmp = TempDir::new().unwrap();
833 let root = tmp.path();
834 let err = add_binding_json(
835 root,
836 "v",
837 "p",
838 r#"{
839 "sources": [{ "name": "wf", "type": "web", "pointer": "https://example.com" }],
840 "destination_mem": "v",
841 "operations": {
842 "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
843 "sync": { "trigger": "manual", "batch_size": 20 }
844 }
845 }"#,
846 )
847 .unwrap_err();
848 match &err {
849 PipelineEditError::Capability { refusals, .. } => {
850 assert!(
851 refusals.iter().any(|r| matches!(
852 r,
853 CapabilityError::OperationOutOfScope { operation, .. } if *operation == "sync"
854 )),
855 "expected an OperationOutOfScope(sync) refusal, got {refusals:?}"
856 );
857 }
858 other => panic!("expected Capability, got {other:?}"),
859 }
860 assert!(pipeline_store::read_binding(root, "v", "p").is_err());
861 }
862
863 #[test]
866 fn update_binding_json_patch_preserves_untouched_fields() {
867 let tmp = TempDir::new().unwrap();
868 let root = tmp.path();
869 let before = add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
870 let after = update_binding_json(root, "v", "p", r#"{"intent":"new"}"#).unwrap();
871 assert_eq!(after.intent.as_deref(), Some("new"));
872 assert_eq!(after.version, before.version);
873 assert_eq!(after.sources, before.sources);
874 assert_eq!(after.reference_mems, before.reference_mems);
875 assert_eq!(after.destination_mem, before.destination_mem);
876 assert_eq!(after.deny_paths, before.deny_paths);
877 assert_eq!(after.coverage_semantics, before.coverage_semantics);
878 assert_eq!(after.rules, before.rules);
879 assert_eq!(after.prune, before.prune);
880 assert_eq!(after.operations, before.operations);
881 }
882
883 #[test]
886 fn update_binding_json_null_clears_and_absence_preserves() {
887 let tmp = TempDir::new().unwrap();
888 let root = tmp.path();
889 add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
890
891 let untouched = update_binding_json(root, "v", "p", r#"{"deny_paths":[]}"#).unwrap();
893 assert!(untouched.rules.is_some() && untouched.prune.is_some());
894 assert_eq!(untouched.intent.as_deref(), Some("i"));
895 assert!(untouched.deny_paths.is_empty());
896
897 let cleared =
899 update_binding_json(root, "v", "p", r#"{"rules": null, "prune": null}"#).unwrap();
900 assert!(cleared.rules.is_none() && cleared.prune.is_none());
901 assert_eq!(cleared.intent.as_deref(), Some("i"), "intent untouched");
902 assert_eq!(
903 pipeline_store::read_binding(root, "v", "p").unwrap(),
904 cleared
905 );
906 }
907
908 #[test]
912 fn update_binding_json_replaces_whole_blocks() {
913 let tmp = TempDir::new().unwrap();
914 let root = tmp.path();
915 add_binding_json(root, "v", "p", full_binding_payload()).unwrap();
916 let after = update_binding_json(
917 root,
918 "v",
919 "p",
920 r#"{"operations": { "build": { "mode": "discovery", "trigger": "manual", "batch_size": 9 } }}"#,
921 )
922 .unwrap();
923 assert_eq!(after.operations.build.as_ref().unwrap().batch_size, 9);
924 assert!(
925 after.operations.sync.is_none(),
926 "sync removed with the block"
927 );
928 assert!(
929 after.operations.verify.is_none(),
930 "verify removed with the block"
931 );
932 assert_eq!(after.rules, Some(serde_json::json!({ "routing": "r" })));
933
934 let after = update_binding_json(
935 root,
936 "v",
937 "p",
938 r#"{"sources": [{ "name": "g", "type": "filesystem", "pointer": "../docs" }]}"#,
939 )
940 .unwrap();
941 assert_eq!(after.sources.len(), 1);
942 assert_eq!(after.sources[0].name, "g");
943 }
944
945 #[test]
948 fn update_binding_json_refuses_introduced_capability_violation() {
949 let tmp = TempDir::new().unwrap();
950 let root = tmp.path();
951 let before = add_binding_json(
952 root,
953 "v",
954 "p",
955 r#"{
956 "sources": [{ "name": "wf", "type": "web", "pointer": "https://example.com" }],
957 "destination_mem": "v"
958 }"#,
959 )
960 .unwrap();
961 let err = update_binding_json(
962 root,
963 "v",
964 "p",
965 r#"{"operations": {
966 "build": { "mode": "discovery", "trigger": "loop", "batch_size": 20 },
967 "sync": { "trigger": "manual", "batch_size": 20 }
968 }}"#,
969 )
970 .unwrap_err();
971 assert!(
972 matches!(err, PipelineEditError::Capability { .. }),
973 "got {err:?}"
974 );
975 assert_eq!(
976 pipeline_store::read_binding(root, "v", "p").unwrap(),
977 before,
978 "record unchanged on refusal"
979 );
980 }
981
982 #[test]
985 fn update_binding_json_allows_edit_despite_preexisting_refusal() {
986 let tmp = TempDir::new().unwrap();
987 let root = tmp.path();
988 let broken = Binding {
991 version: BINDING_VERSION,
992 intent: None,
993 sources: vec![Source {
994 name: "wf".to_string(),
995 medium_type: crate::pipeline::MediumType::Web,
996 pointer: "https://example.com".to_string(),
997 change_detection: None,
998 scope: vec![],
999 engagement: None,
1000 preparation: None,
1001 }],
1002 reference_mems: vec![],
1003 destination_mem: "v".to_string(),
1004 deny_paths: vec![],
1005 coverage_semantics: None,
1006 rules: None,
1007 prune: None,
1008 operations: Operations {
1009 build: Some(BuildOperation {
1010 mode: BuildMode::Discovery,
1011 trigger: IngestTrigger::Loop,
1012 batch_size: 20,
1013 post_actions: None,
1014 }),
1015 sync: Some(SyncOperation {
1016 trigger: IngestTrigger::Manual,
1017 batch_size: 20,
1018 }),
1019 verify: None,
1020 },
1021 };
1022 pipeline_store::write_binding(root, "v", "p", &broken).unwrap();
1023
1024 let after = update_binding_json(root, "v", "p", r#"{"intent":"fixed"}"#).unwrap();
1025 assert_eq!(after.intent.as_deref(), Some("fixed"));
1026 assert!(
1027 after.operations.sync.is_some(),
1028 "pre-existing sync survives"
1029 );
1030
1031 let err = update_binding_json(
1033 root,
1034 "v",
1035 "p",
1036 r#"{"sources": [
1037 { "name": "dup", "type": "web", "pointer": "https://a" },
1038 { "name": "dup", "type": "web", "pointer": "https://b" }
1039 ]}"#,
1040 )
1041 .unwrap_err();
1042 assert!(
1043 matches!(err, PipelineEditError::Capability { .. }),
1044 "got {err:?}"
1045 );
1046 }
1047
1048 #[test]
1049 fn update_binding_json_refuses_missing_record() {
1050 let tmp = TempDir::new().unwrap();
1051 let err = update_binding_json(tmp.path(), "v", "p", r#"{"intent":"x"}"#).unwrap_err();
1052 assert!(
1053 matches!(err, PipelineEditError::NotFound { .. }),
1054 "got {err:?}"
1055 );
1056 }
1057
1058 #[test]
1061 fn update_binding_json_ignores_unknown_keys_and_version() {
1062 let tmp = TempDir::new().unwrap();
1063 let root = tmp.path();
1064 add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
1065 let after = update_binding_json(
1066 root,
1067 "v",
1068 "p",
1069 r#"{"version": 99, "future_key": { "x": 1 }, "intent": "i2"}"#,
1070 )
1071 .unwrap();
1072 assert_eq!(
1073 after.version, BINDING_VERSION,
1074 "version stays engine-managed"
1075 );
1076 assert_eq!(after.intent.as_deref(), Some("i2"));
1077 }
1078
1079 #[test]
1080 fn delete_binding_removes_the_record() {
1081 let tmp = TempDir::new().unwrap();
1082 let root = tmp.path();
1083 add_binding_json(root, "v", "p", BASE_PAYLOAD).unwrap();
1084 delete_binding(root, "v", "p").unwrap();
1085 assert!(!root.join(".memstead/projections/v/p.json").exists());
1086 let err = delete_binding(root, "v", "p").unwrap_err();
1087 assert!(
1088 matches!(err, PipelineEditError::NotFound { .. }),
1089 "got {err:?}"
1090 );
1091 }
1092
1093 #[test]
1094 fn rename_binding_moves_the_record() {
1095 let tmp = TempDir::new().unwrap();
1096 let root = tmp.path();
1097 let created = add_binding_json(root, "v", "old", BASE_PAYLOAD).unwrap();
1098 rename_binding(root, "v", "old", "new").unwrap();
1099 assert!(!root.join(".memstead/projections/v/old.json").exists());
1100 assert_eq!(
1101 pipeline_store::read_binding(root, "v", "new").unwrap(),
1102 created
1103 );
1104 }
1105
1106 #[test]
1107 fn rename_binding_refuses_existing_target_and_missing_source() {
1108 let tmp = TempDir::new().unwrap();
1109 let root = tmp.path();
1110 add_binding_json(root, "v", "a", BASE_PAYLOAD).unwrap();
1111 add_binding_json(root, "v", "b", BASE_PAYLOAD).unwrap();
1112 let err = rename_binding(root, "v", "a", "b").unwrap_err();
1113 assert!(
1114 matches!(err, PipelineEditError::RenameTargetExists { .. }),
1115 "got {err:?}"
1116 );
1117 let err = rename_binding(root, "v", "missing", "c").unwrap_err();
1118 assert!(
1119 matches!(err, PipelineEditError::NotFound { .. }),
1120 "got {err:?}"
1121 );
1122 rename_binding(root, "v", "a", "a").unwrap();
1124 }
1125
1126 #[test]
1130 fn editing_a_pre_v2_store_refuses_as_legacy() {
1131 let tmp = TempDir::new().unwrap();
1132 let root = tmp.path();
1133 let dir = root.join(".memstead/projections/v");
1134 std::fs::create_dir_all(&dir).unwrap();
1135 std::fs::write(
1136 dir.join("p.json"),
1137 br#"{"version": 1, "source_facets": ["f"], "destination_mem": "v", "operations": {}}"#,
1138 )
1139 .unwrap();
1140 let err = add_binding_json(root, "v", "q", BASE_PAYLOAD).unwrap_err();
1141 match err {
1142 PipelineEditError::Store(StoreError::LegacyProjectionStore { .. }) => {}
1143 other => panic!("expected LegacyProjectionStore, got {other:?}"),
1144 }
1145 }
1146}