1use std::fs;
19use std::path::{Path, PathBuf};
20
21use toml_edit::{Array, ArrayOfTables, DocumentMut, Item, Table, Value};
22
23#[derive(Debug)]
34pub enum WorkspaceEditError {
35 WorkspaceNotInitialised { path: PathBuf },
38 InvalidToml { path: PathBuf, message: String },
40 BeforePatternNotFound {
43 section: &'static str,
44 pattern: String,
45 },
46 CrossLinkConflict { from: String, message: String },
50 RuleExistsSchemasDiffer {
58 section: &'static str,
59 pattern: String,
60 stored: Vec<String>,
61 requested: Vec<String>,
62 },
63 Io {
65 path: PathBuf,
66 source: std::io::Error,
67 },
68}
69
70#[derive(Debug, Clone)]
76pub enum WorkspaceEditWarning {
77 RuleAlreadyPresent {
80 section: &'static str,
81 pattern: String,
82 },
83 RuleNotFoundNoop {
86 section: &'static str,
87 pattern: String,
88 },
89 GrantAlreadyPresent { from: String, to: String },
93 GrantNotFound { from: String, to: String },
96 CrossLinkTargetUnregistered { to: String },
101 CrossLinkSelfGrantNoop { mem: String },
105 CrossLinkRevokeOrphanedEdges { edges: Vec<String> },
116}
117
118impl WorkspaceEditWarning {
119 pub fn code(&self) -> &'static str {
122 match self {
123 Self::RuleAlreadyPresent { .. } => "RULE_ALREADY_PRESENT",
124 Self::RuleNotFoundNoop { .. } => "RULE_NOT_FOUND_NOOP",
125 Self::GrantAlreadyPresent { .. } => "GRANT_ALREADY_PRESENT",
126 Self::GrantNotFound { .. } => "GRANT_NOT_FOUND",
127 Self::CrossLinkTargetUnregistered { .. } => "CROSS_LINK_TARGET_UNREGISTERED",
128 Self::CrossLinkSelfGrantNoop { .. } => "CROSS_LINK_SELF_GRANT_NOOP",
129 Self::CrossLinkRevokeOrphanedEdges { .. } => "CROSS_LINK_REVOKE_ORPHANED_EDGES",
130 }
131 }
132}
133
134impl std::fmt::Display for WorkspaceEditWarning {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 match self {
137 Self::RuleAlreadyPresent { section, pattern } => write!(
138 f,
139 "`[[{section}]]` already contains an entry for pattern `{pattern}` — file unchanged"
140 ),
141 Self::RuleNotFoundNoop { section, pattern } => write!(
142 f,
143 "`[[{section}]]` has no entry for pattern `{pattern}` — file unchanged"
144 ),
145 Self::GrantAlreadyPresent { from, to } => write!(
146 f,
147 "`[cross_mem_links]` already grants {from} → {to} — file unchanged"
148 ),
149 Self::GrantNotFound { from, to } => write!(
150 f,
151 "`[cross_mem_links]` does not grant {from} → {to} — file unchanged"
152 ),
153 Self::CrossLinkTargetUnregistered { to } => write!(
154 f,
155 "cross-link target `{to}` is not a registered mem — the grant is persisted (forward-reference is allowed) but will validate no relate until `{to}` exists"
156 ),
157 Self::CrossLinkSelfGrantNoop { mem } => write!(
158 f,
159 "self-grant `{mem} → {mem}` is a no-op — intra-mem links never traverse the cross-link gate; the grant is persisted but has no effect"
160 ),
161 Self::CrossLinkRevokeOrphanedEdges { edges } => write!(
162 f,
163 "{} existing edge(s) are now without a grant and are NOT removed: {}. Each refuses `memstead health --include integrity --strict` until it is granted again or removed (`memstead relate ... --remove`, which needs no grant)",
164 edges.len(),
165 edges.join(", ")
166 ),
167 }
168 }
169}
170
171impl std::fmt::Display for WorkspaceEditError {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 match self {
174 Self::WorkspaceNotInitialised { path, .. } => write!(
175 f,
176 "no `.memstead/workspace.toml` at {} — run `memstead mem-repo init` or `memstead init` first",
177 path.display()
178 ),
179 Self::InvalidToml { path, message } => {
180 write!(f, "{}: failed to parse TOML — {message}", path.display())
181 }
182 Self::BeforePatternNotFound { section, pattern } => write!(
183 f,
184 "`--before {pattern}` did not match any existing `[[{section}]]` entry"
185 ),
186 Self::CrossLinkConflict { from, message } => write!(
187 f,
188 "`[cross_mem_links]` rejects edit for `{from}`: {message}"
189 ),
190 Self::RuleExistsSchemasDiffer {
191 section,
192 pattern,
193 stored,
194 requested,
195 } => write!(
196 f,
197 "`[[{section}]]` already has a rule for pattern `{pattern}` pinned to schemas [{}], \
198 which differs from the requested [{}] — refusing to silently change the schema pins. \
199 To change them, revoke the rule first (`revoke_create {pattern}`) then re-add it with the new schemas",
200 stored.join(", "),
201 requested.join(", "),
202 ),
203 Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
204 }
205 }
206}
207
208impl std::error::Error for WorkspaceEditError {}
209
210impl WorkspaceEditError {
211 pub fn code(&self) -> &'static str {
213 match self {
214 Self::WorkspaceNotInitialised { .. } => "WORKSPACE_NOT_INITIALISED",
215 Self::InvalidToml { .. } => "INVALID_TOML",
216 Self::BeforePatternNotFound { .. } => "BEFORE_PATTERN_NOT_FOUND",
217 Self::CrossLinkConflict { .. } => "CROSS_LINK_CONFLICT",
218 Self::RuleExistsSchemasDiffer { .. } => "RULE_EXISTS_SCHEMAS_DIFFER",
219 Self::Io { .. } => "IO_ERROR",
220 }
221 }
222}
223
224pub fn workspace_toml_path(workspace_root: &Path) -> PathBuf {
226 workspace_root
227 .join(crate::WORKSPACE_STORE_DIR)
228 .join("workspace.toml")
229}
230
231fn load(workspace_root: &Path) -> Result<(PathBuf, DocumentMut), WorkspaceEditError> {
232 let path = workspace_toml_path(workspace_root);
233 let text = fs::read_to_string(&path).map_err(|source| {
234 if source.kind() == std::io::ErrorKind::NotFound {
235 WorkspaceEditError::WorkspaceNotInitialised { path: path.clone() }
236 } else {
237 WorkspaceEditError::Io {
238 path: path.clone(),
239 source,
240 }
241 }
242 })?;
243 let doc: DocumentMut =
244 text.parse()
245 .map_err(|e: toml_edit::TomlError| WorkspaceEditError::InvalidToml {
246 path: path.clone(),
247 message: e.to_string(),
248 })?;
249 Ok((path, doc))
250}
251
252fn save(path: &Path, doc: &DocumentMut) -> Result<(), WorkspaceEditError> {
253 fs::write(path, doc.to_string()).map_err(|source| WorkspaceEditError::Io {
254 path: path.to_path_buf(),
255 source,
256 })
257}
258
259#[derive(Debug, Clone, PartialEq, Eq)]
264pub enum CrossLinkTarget {
265 Wildcard,
267 Named(String),
270}
271
272impl CrossLinkTarget {
273 pub fn parse(raw: &str) -> Self {
278 if raw == "*" {
279 Self::Wildcard
280 } else {
281 Self::Named(raw.to_string())
282 }
283 }
284}
285
286pub fn add_create_rule(
291 workspace_root: &Path,
292 pattern: &str,
293 schemas: &[String],
294 default_cross_links: Option<&[CrossLinkTarget]>,
295 before: Option<&str>,
296) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
297 let (path, mut doc) = load(workspace_root)?;
298 let section = ensure_array_of_tables(&mut doc, "mem_management", "create");
299
300 if let Some(idx) = find_pattern_index(section, pattern) {
301 let stored = read_rule_schemas(section, idx);
307 if schema_sets_equal(&stored, schemas) {
308 return Ok(vec![WorkspaceEditWarning::RuleAlreadyPresent {
309 section: "mem_management.create",
310 pattern: pattern.to_string(),
311 }]);
312 }
313 return Err(WorkspaceEditError::RuleExistsSchemasDiffer {
314 section: "mem_management.create",
315 pattern: pattern.to_string(),
316 stored,
317 requested: schemas.to_vec(),
318 });
319 }
320
321 let mut table = Table::new();
322 table["pattern"] = Item::Value(Value::from(pattern));
323 let mut arr = Array::new();
324 for s in schemas {
325 arr.push(s.as_str());
326 }
327 table["schemas"] = Item::Value(Value::Array(arr));
328 if let Some(cross_links) = default_cross_links {
329 table["default_cross_links"] = cross_link_value_item(cross_links);
330 }
331
332 if let Some(before_pattern) = before {
333 let idx = find_pattern_index(section, before_pattern).ok_or_else(|| {
334 WorkspaceEditError::BeforePatternNotFound {
335 section: "mem_management.create",
336 pattern: before_pattern.to_string(),
337 }
338 })?;
339 let mut tail = Vec::with_capacity(section.len() - idx);
343 while section.len() > idx {
344 let last = section.get(section.len() - 1).cloned().unwrap();
345 tail.push(last);
346 section.remove(section.len() - 1);
347 }
348 section.push(table);
349 for entry in tail.into_iter().rev() {
350 section.push(entry);
351 }
352 } else {
353 section.push(table);
354 }
355
356 save(&path, &doc)?;
357 Ok(Vec::new())
358}
359
360pub fn remove_create_rule(
363 workspace_root: &Path,
364 pattern: &str,
365) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
366 let (path, mut doc) = load(workspace_root)?;
367 let section = ensure_array_of_tables(&mut doc, "mem_management", "create");
368 let idx = match find_pattern_index(section, pattern) {
369 Some(i) => i,
370 None => {
371 return Ok(vec![WorkspaceEditWarning::RuleNotFoundNoop {
372 section: "mem_management.create",
373 pattern: pattern.to_string(),
374 }]);
375 }
376 };
377 section.remove(idx);
378 save(&path, &doc)?;
379 Ok(Vec::new())
380}
381
382pub fn add_delete_rule(
385 workspace_root: &Path,
386 pattern: &str,
387) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
388 let (path, mut doc) = load(workspace_root)?;
389 let section = ensure_array_of_tables(&mut doc, "mem_management", "delete");
390 if find_pattern_index(section, pattern).is_some() {
391 return Ok(vec![WorkspaceEditWarning::RuleAlreadyPresent {
392 section: "mem_management.delete",
393 pattern: pattern.to_string(),
394 }]);
395 }
396 let mut table = Table::new();
397 table["pattern"] = Item::Value(Value::from(pattern));
398 section.push(table);
399 save(&path, &doc)?;
400 Ok(Vec::new())
401}
402
403pub fn remove_delete_rule(
406 workspace_root: &Path,
407 pattern: &str,
408) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
409 let (path, mut doc) = load(workspace_root)?;
410 let section = ensure_array_of_tables(&mut doc, "mem_management", "delete");
411 let idx = match find_pattern_index(section, pattern) {
412 Some(i) => i,
413 None => {
414 return Ok(vec![WorkspaceEditWarning::RuleNotFoundNoop {
415 section: "mem_management.delete",
416 pattern: pattern.to_string(),
417 }]);
418 }
419 };
420 section.remove(idx);
421 save(&path, &doc)?;
422 Ok(Vec::new())
423}
424
425pub fn grant_cross_link(
429 workspace_root: &Path,
430 from: &str,
431 to: &CrossLinkTarget,
432 known_mems: &[String],
433) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
434 let mut warnings: Vec<WorkspaceEditWarning> = Vec::new();
441 if let CrossLinkTarget::Named(name) = to {
442 if name == from {
443 warnings.push(WorkspaceEditWarning::CrossLinkSelfGrantNoop {
444 mem: from.to_string(),
445 });
446 } else if !known_mems.iter().any(|v| v == name) {
447 warnings.push(WorkspaceEditWarning::CrossLinkTargetUnregistered { to: name.clone() });
448 }
449 }
450
451 let (path, mut doc) = load(workspace_root)?;
452 let table = ensure_table(&mut doc, "cross_mem_links");
453 match (table.get(from), to) {
454 (None, CrossLinkTarget::Wildcard) => {
455 table.insert(from, Item::Value(Value::from("*")));
456 }
457 (None, CrossLinkTarget::Named(name)) => {
458 let mut arr = Array::new();
459 arr.push(name.as_str());
460 table.insert(from, Item::Value(Value::Array(arr)));
461 }
462 (Some(Item::Value(Value::String(s))), CrossLinkTarget::Wildcard) if s.value() == "*" => {
463 warnings.push(WorkspaceEditWarning::GrantAlreadyPresent {
464 from: from.to_string(),
465 to: "*".to_string(),
466 });
467 return Ok(warnings);
468 }
469 (Some(Item::Value(Value::String(_))), _) => {
470 return Err(WorkspaceEditError::CrossLinkConflict {
471 from: from.to_string(),
472 message: "wildcard `*` already set — revoke `*` before granting a named target"
473 .to_string(),
474 });
475 }
476 (Some(Item::Value(Value::Array(_))), CrossLinkTarget::Wildcard) => {
477 return Err(WorkspaceEditError::CrossLinkConflict {
478 from: from.to_string(),
479 message: "specific allowlist already set — revoke every entry before granting `*`"
480 .to_string(),
481 });
482 }
483 (Some(Item::Value(Value::Array(arr))), CrossLinkTarget::Named(name)) => {
484 if array_contains(arr, name) {
485 warnings.push(WorkspaceEditWarning::GrantAlreadyPresent {
486 from: from.to_string(),
487 to: name.clone(),
488 });
489 return Ok(warnings);
490 }
491 let mut arr = arr.clone();
492 arr.push(name.as_str());
493 table.insert(from, Item::Value(Value::Array(arr)));
494 }
495 (Some(_), _) => {
496 return Err(WorkspaceEditError::CrossLinkConflict {
497 from: from.to_string(),
498 message: "existing value is neither a string nor an array — fix by hand"
499 .to_string(),
500 });
501 }
502 }
503 save(&path, &doc)?;
504 Ok(warnings)
505}
506
507pub fn revoke_cross_link(
511 workspace_root: &Path,
512 from: &str,
513 to: &CrossLinkTarget,
514) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
515 let (path, mut doc) = load(workspace_root)?;
516 let table = ensure_table(&mut doc, "cross_mem_links");
517 let removed = match (table.get(from), to) {
518 (None, _) => false,
519 (Some(Item::Value(Value::String(s))), CrossLinkTarget::Wildcard) if s.value() == "*" => {
520 table.remove(from);
521 true
522 }
523 (Some(Item::Value(Value::String(_))), CrossLinkTarget::Named(_)) => false,
524 (Some(Item::Value(Value::String(_))), CrossLinkTarget::Wildcard) => false,
525 (Some(Item::Value(Value::Array(_))), CrossLinkTarget::Wildcard) => false,
526 (Some(Item::Value(Value::Array(arr))), CrossLinkTarget::Named(name)) => {
527 let mut arr = arr.clone();
528 let original_len = arr.len();
529 arr.retain(|v| match v {
530 Value::String(s) => s.value() != name,
531 _ => true,
532 });
533 if arr.len() == original_len {
534 false
535 } else if arr.is_empty() {
536 table.remove(from);
537 true
538 } else {
539 table.insert(from, Item::Value(Value::Array(arr)));
540 true
541 }
542 }
543 (Some(_), _) => false,
544 };
545 if !removed {
546 let target = match to {
547 CrossLinkTarget::Wildcard => "*".to_string(),
548 CrossLinkTarget::Named(s) => s.clone(),
549 };
550 return Ok(vec![WorkspaceEditWarning::GrantNotFound {
551 from: from.to_string(),
552 to: target,
553 }]);
554 }
555 save(&path, &doc)?;
556 Ok(Vec::new())
557}
558
559pub fn set_mutation_require_notes(
562 workspace_root: &Path,
563 value: bool,
564) -> Result<(), WorkspaceEditError> {
565 let (path, mut doc) = load(workspace_root)?;
566 let table = ensure_table(&mut doc, "mutations");
567 table.insert("require_notes", Item::Value(Value::from(value)));
568 save(&path, &doc)
569}
570
571pub fn scrub_policy_for_deleted_mem(
606 workspace_root: &Path,
607 mem_name: &str,
608) -> Result<Vec<ScrubbedEntry>, WorkspaceEditError> {
609 let path = workspace_toml_path(workspace_root);
610 let text = match fs::read_to_string(&path) {
611 Ok(t) => t,
612 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
613 return Ok(Vec::new());
615 }
616 Err(source) => {
617 return Err(WorkspaceEditError::Io {
618 path: path.clone(),
619 source,
620 });
621 }
622 };
623 let mut doc: DocumentMut =
624 text.parse()
625 .map_err(|e: toml_edit::TomlError| WorkspaceEditError::InvalidToml {
626 path: path.clone(),
627 message: e.to_string(),
628 })?;
629
630 let mut scrubbed: Vec<ScrubbedEntry> = Vec::new();
631
632 if let Some(item) = doc.get_mut("cross_mem_links")
633 && let Some(table) = item.as_table_mut()
634 {
635 if let Some(removed) = table.remove(mem_name) {
638 let targets = match removed {
639 Item::Value(Value::Array(arr)) => arr
640 .iter()
641 .filter_map(|v| match v {
642 Value::String(s) => Some(s.value().to_string()),
643 _ => None,
644 })
645 .collect::<Vec<_>>(),
646 Item::Value(Value::String(s)) => vec![s.value().to_string()],
647 _ => Vec::new(),
648 };
649 if targets.is_empty() {
650 scrubbed.push(ScrubbedEntry::CrossLink {
651 from: mem_name.to_string(),
652 to: "*".to_string(),
653 });
654 } else {
655 for to in targets {
656 scrubbed.push(ScrubbedEntry::CrossLink {
657 from: mem_name.to_string(),
658 to,
659 });
660 }
661 }
662 }
663 let keys: Vec<String> = table.iter().map(|(k, _)| k.to_string()).collect();
667 for key in keys {
668 let drop_key = match table.get(&key) {
669 Some(Item::Value(Value::Array(arr))) if array_contains(arr, mem_name) => {
670 let mut arr = arr.clone();
671 arr.retain(|v| match v {
672 Value::String(s) => s.value() != mem_name,
673 _ => true,
674 });
675 scrubbed.push(ScrubbedEntry::CrossLink {
676 from: key.clone(),
677 to: mem_name.to_string(),
678 });
679 if arr.is_empty() {
680 true
681 } else {
682 table.insert(&key, Item::Value(Value::Array(arr)));
683 false
684 }
685 }
686 _ => false,
687 };
688 if drop_key {
689 table.remove(&key);
690 }
691 }
692 }
693
694 if !scrubbed.is_empty() {
701 save(&path, &doc)?;
702 }
703 Ok(scrubbed)
704}
705
706#[derive(Debug, Clone, PartialEq, Eq)]
713pub enum ScrubbedEntry {
714 CrossLink {
717 from: String,
719 to: String,
721 },
722}
723
724pub fn rename_mem_in_cross_links(
734 workspace_root: &Path,
735 old: &str,
736 new: &str,
737) -> Result<bool, WorkspaceEditError> {
738 let (path, mut doc) = match load(workspace_root) {
739 Ok(pair) => pair,
740 Err(WorkspaceEditError::WorkspaceNotInitialised { .. }) => return Ok(false),
741 Err(e) => return Err(e),
742 };
743 let Some(table) = doc.get_mut("cross_mem_links").and_then(Item::as_table_mut) else {
744 return Ok(false);
745 };
746
747 let mut changed = false;
748 for (_key, item) in table.iter_mut() {
750 if let Item::Value(Value::Array(arr)) = item {
751 let mut next = Array::new();
752 let mut arr_changed = false;
753 for v in arr.iter() {
754 match v.as_str() {
755 Some(s) if s == old => {
756 next.push(new);
757 arr_changed = true;
758 }
759 _ => next.push(v.clone()),
760 }
761 }
762 if arr_changed {
763 *item = Item::Value(Value::Array(next));
764 changed = true;
765 }
766 }
767 }
768 if let Some(value) = table.remove(old) {
771 table.insert(new, value);
772 changed = true;
773 }
774
775 if changed {
776 save(&path, &doc)?;
777 }
778 Ok(changed)
779}
780
781fn ensure_table<'a>(doc: &'a mut DocumentMut, name: &str) -> &'a mut Table {
782 if !doc.contains_key(name) {
783 let mut t = Table::new();
784 t.set_implicit(false);
785 doc.insert(name, Item::Table(t));
786 }
787 doc.get_mut(name)
788 .unwrap()
789 .as_table_mut()
790 .expect("ensured table shape")
791}
792
793fn ensure_array_of_tables<'a>(
794 doc: &'a mut DocumentMut,
795 outer: &str,
796 inner: &str,
797) -> &'a mut ArrayOfTables {
798 if !doc.contains_key(outer) {
799 let mut t = Table::new();
800 t.set_implicit(true);
801 doc.insert(outer, Item::Table(t));
802 }
803 let outer_table = doc
804 .get_mut(outer)
805 .and_then(|i| i.as_table_mut())
806 .expect("mem_management must be a table");
807 if !outer_table.contains_key(inner) {
808 outer_table.insert(inner, Item::ArrayOfTables(ArrayOfTables::new()));
809 }
810 outer_table
811 .get_mut(inner)
812 .and_then(|i| i.as_array_of_tables_mut())
813 .expect("ensured array-of-tables shape")
814}
815
816fn find_pattern_index(section: &ArrayOfTables, pattern: &str) -> Option<usize> {
817 section
818 .iter()
819 .position(|t| t.get("pattern").and_then(|i| i.as_str()) == Some(pattern))
820}
821
822fn read_rule_schemas(section: &ArrayOfTables, idx: usize) -> Vec<String> {
825 section
826 .get(idx)
827 .and_then(|t| t.get("schemas"))
828 .and_then(|i| i.as_array())
829 .map(|arr| {
830 arr.iter()
831 .filter_map(|v| v.as_str().map(str::to_string))
832 .collect()
833 })
834 .unwrap_or_default()
835}
836
837fn schema_sets_equal(a: &[String], b: &[String]) -> bool {
841 let mut a: Vec<&str> = a.iter().map(String::as_str).collect();
842 let mut b: Vec<&str> = b.iter().map(String::as_str).collect();
843 a.sort_unstable();
844 a.dedup();
845 b.sort_unstable();
846 b.dedup();
847 a == b
848}
849
850fn cross_link_value_item(targets: &[CrossLinkTarget]) -> Item {
851 if targets
852 .iter()
853 .any(|t| matches!(t, CrossLinkTarget::Wildcard))
854 {
855 Item::Value(Value::from("*"))
856 } else {
857 let mut arr = Array::new();
858 for t in targets {
859 if let CrossLinkTarget::Named(name) = t {
860 arr.push(name.as_str());
861 }
862 }
863 Item::Value(Value::Array(arr))
864 }
865}
866
867fn array_contains(arr: &Array, needle: &str) -> bool {
868 arr.iter().any(|v| match v {
869 Value::String(s) => s.value() == needle,
870 _ => false,
871 })
872}
873
874#[cfg(test)]
875mod tests;