Skip to main content

memstead_base/
workspace_config_edit.rs

1//! `toml_edit`-backed writer for `.memstead/workspace.toml`.
2//!
3//! Backs the `memstead workspace allow-create / revoke-create / allow-delete /
4//! revoke-delete / grant-cross-link / revoke-cross-link / set-mutations`
5//! subcommand family. Every operation is a load → mutate → write triple;
6//! `toml_edit` preserves operator-authored comments and formatting on
7//! sections the CLI doesn't touch (cross-mem forward-reference
8//! rationale, ingest-namespace pairings, operator-mode bypass semantics,
9//! pattern-grammar examples).
10//!
11//! Errors carry symbolic codes (`WORKSPACE_NOT_INITIALISED`,
12//! `RULE_ALREADY_EXISTS`, `RULE_NOT_FOUND`, `BEFORE_PATTERN_NOT_FOUND`,
13//! `CROSS_LINK_ALREADY_GRANTED`, `CROSS_LINK_NOT_GRANTED`,
14//! `CROSS_LINK_CONFLICT`, `INVALID_TOML`) so the CLI's typed exit envelope
15//! lifts them as `code` in the `--json` payload. The CLI layer maps the
16//! enum variants onto `CliError` / `ExitKind`.
17
18use std::fs;
19use std::path::{Path, PathBuf};
20
21use toml_edit::{Array, ArrayOfTables, DocumentMut, Item, Table, Value};
22
23/// Errors returned by the writer.
24///
25/// The idempotency cases (`RuleAlreadyExists`, `RuleNotFound`,
26/// `CrossLinkAlreadyGranted`, `CrossLinkNotGranted`) live on
27/// [`WorkspaceEditWarning`] rather than here — re-grant / re-revoke /
28/// re-add / re-remove return success-with-warning rather than refusing,
29/// letting CLI scripts and MCP agents retry safely without
30/// branching on prior state. `CrossLinkConflict` stays an error
31/// because it's a real semantic conflict (wildcard vs. specific
32/// list), not an idempotency case.
33#[derive(Debug)]
34pub enum WorkspaceEditError {
35    /// `.memstead/workspace.toml` missing or unreadable. The workspace
36    /// must be initialised before the CLI can edit its config.
37    WorkspaceNotInitialised { path: PathBuf },
38    /// Existing file failed to parse as TOML.
39    InvalidToml { path: PathBuf, message: String },
40    /// `add_create_rule` with `--before <p>` where `<p>` isn't an
41    /// existing pattern in the section.
42    BeforePatternNotFound {
43        section: &'static str,
44        pattern: String,
45    },
46    /// `grant_cross_link` with `*` against an existing specific list,
47    /// or with a specific target against an existing `*`. Operators
48    /// pick a single shape per `from`-mem.
49    CrossLinkConflict { from: String, message: String },
50    /// `add_create_rule` called for a pattern that already exists but
51    /// with a **different** schema set. Refused rather than silently
52    /// no-op'd: changing a pattern's schema pins is a security-relevant
53    /// policy change, so it must be explicit (revoke the rule, then
54    /// re-add with the new schemas) — never a silent success echoing a
55    /// change that did not land. The genuine no-op (identical schemas)
56    /// stays [`WorkspaceEditWarning::RuleAlreadyPresent`].
57    RuleExistsSchemasDiffer {
58        section: &'static str,
59        pattern: String,
60        stored: Vec<String>,
61        requested: Vec<String>,
62    },
63    /// IO failure writing the file back.
64    Io {
65        path: PathBuf,
66        source: std::io::Error,
67    },
68}
69
70/// Idempotency notices emitted by the writer when a call lands on
71/// a state the caller intended (re-grant of an existing grant,
72/// re-revoke of an absent grant, etc.). Surfacing these as warnings
73/// rather than errors lets agents and scripts retry without branching
74/// on prior state.
75#[derive(Debug, Clone)]
76pub enum WorkspaceEditWarning {
77    /// `add_create_rule` / `add_delete_rule` called with a pattern
78    /// that already has a matching entry. File unchanged.
79    RuleAlreadyPresent {
80        section: &'static str,
81        pattern: String,
82    },
83    /// `remove_create_rule` / `remove_delete_rule` called with a
84    /// pattern that has no matching entry. File unchanged.
85    RuleNotFoundNoop {
86        section: &'static str,
87        pattern: String,
88    },
89    /// `grant_cross_link` called with a `(from, to)` pair already
90    /// permitted (target already in the allowlist, or `*` already
91    /// set). File unchanged.
92    GrantAlreadyPresent { from: String, to: String },
93    /// `revoke_cross_link` called with a `(from, to)` pair that
94    /// isn't currently permitted. File unchanged.
95    GrantNotFound { from: String, to: String },
96    /// `grant_cross_link` named a `to` target that isn't a registered
97    /// mem (and isn't the `*` wildcard). The grant still persists —
98    /// the forward-reference workflow (grant before the target mem
99    /// exists) is legitimate — but a likely typo is surfaced.
100    CrossLinkTargetUnregistered { to: String },
101    /// `grant_cross_link` named `to == from` — a self-grant. Intra-mem
102    /// links never traverse the cross-link gate, so the grant is a
103    /// no-op. It still persists; the meaninglessness is surfaced.
104    CrossLinkSelfGrantNoop { mem: String },
105    /// `revoke_cross_link` removed a grant that existing edges were
106    /// relying on. The edges are NOT removed — a policy edit must not
107    /// delete user data — but they are now in a state the default-deny
108    /// write gate would refuse to create, so they are named at the moment
109    /// the operator can act on them cheapest rather than left for a later
110    /// gate run.
111    ///
112    /// Rides the warning channel deliberately: every revoke surface
113    /// already renders these, so the CLI operator, the HTTP client and the
114    /// web app get the same account without three separate renderings.
115    CrossLinkRevokeOrphanedEdges { edges: Vec<String> },
116}
117
118impl WorkspaceEditWarning {
119    /// Stable UPPER_SNAKE_CASE code surfaced as the CLI's stderr
120    /// notice and as the MCP wrapper's warning envelope.
121    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    /// Stable symbolic code used by the CLI exit envelope.
212    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
224/// Path of the workspace config file relative to the workspace root.
225pub 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/// Either-or shape mirroring `[cross_mem_links]` semantics on disk:
260/// `<from> = "*"` (wildcard) or `<from> = ["a", "b"]` (allowlist). The
261/// CLI exposes both via `--target *` and `--target <name>` on
262/// `grant-cross-link`.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub enum CrossLinkTarget {
265    /// `*` — every current writable target is permitted.
266    Wildcard,
267    /// One named target. Multiple grants accumulate into the
268    /// underlying `<from> = ["a", "b", ...]` list on disk.
269    Named(String),
270}
271
272impl CrossLinkTarget {
273    /// Parse a CLI-supplied target token. `*` maps to the wildcard
274    /// shape; anything else maps to the named shape verbatim. The
275    /// caller validates name shape elsewhere (the engine's existing
276    /// mem-name validation runs on load).
277    pub fn parse(raw: &str) -> Self {
278        if raw == "*" {
279            Self::Wildcard
280        } else {
281            Self::Named(raw.to_string())
282        }
283    }
284}
285
286/// `memstead workspace allow-create <pattern> --schema <pin>[,…] [--cross-link …]
287/// [--before <pattern>]` — append a `[[mem_management.create]]` rule.
288/// Default ordering is append (lowest priority); `before` flags lift it
289/// above the named pattern.
290pub 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        // Pattern already present. Compare the stored schema set against
302        // the requested one: identical → clean idempotent no-op; a
303        // *difference* must not silently no-op (and must not echo a
304        // change that did not land), so refuse with an actionable typed
305        // error pointing at the revoke-then-readd recovery.
306        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        // `ArrayOfTables` has no `insert(idx, table)`; emulate it by
340        // detaching every entry from `idx` onward, pushing the new
341        // table, then pushing the detached entries back.
342        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
360/// `memstead workspace revoke-create <pattern>` — remove a
361/// `[[mem_management.create]]` rule by pattern.
362pub 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
382/// `memstead workspace allow-delete <pattern>` — append a
383/// `[[mem_management.delete]]` rule.
384pub 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
403/// `memstead workspace revoke-delete <pattern>` — remove a
404/// `[[mem_management.delete]]` rule by pattern.
405pub 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
425/// `memstead workspace grant-cross-link <from> <to>` — add `to` to the
426/// allowlist for `from` in `[cross_mem_links]`. `to == "*"` sets the
427/// wildcard shape; named targets accumulate into a list.
428pub fn grant_cross_link(
429    workspace_root: &Path,
430    from: &str,
431    to: &CrossLinkTarget,
432    known_mems: &[String],
433) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
434    // Diligence (matching the sibling `revoke_cross_link`'s warn-on-
435    // anomaly behaviour): warn — never block — on a self-grant or an
436    // unregistered named target. The grant still persists so the
437    // forward-reference workflow (grant before the target mem exists)
438    // stays open. The `*` wildcard is a legitimate non-mem token and
439    // is not validated against the registered set.
440    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
507/// `memstead workspace revoke-cross-link <from> <to>` — remove `to` from
508/// the allowlist for `from`. When the underlying list becomes empty,
509/// the `<from>` key is dropped entirely; `*` is matched as a literal.
510pub 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
559/// `memstead workspace set-mutations --require-notes <bool>` — set the
560/// `[mutations] require_notes` field. Creates the section on demand.
561pub 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
571/// Scrub `.memstead/workspace.toml` of the now-dangling `[cross_mem_links]`
572/// grants naming `mem_name` so the workspace no longer references a
573/// mem the engine just destructively deleted. The
574/// `[[mem_management.create]]` / `[[mem_management.delete]]`
575/// allowlist rules are deliberately left intact.
576///
577/// Two passes, both on the in-memory `DocumentMut` before one final
578/// save:
579///   1. `[cross_mem_links]` — drop the key `mem_name` if present
580///      (the deleted mem as `from`).
581///   2. `[cross_mem_links]` — remove `mem_name` from every other
582///      key's allowlist `Array`. When an allowlist becomes empty,
583///      drop the key entirely (mirrors `revoke_cross_link`).
584///
585/// What is NOT scrubbed, and why: the `[[mem_management.create]]` /
586/// `[[mem_management.delete]]` rules are forward-looking *permissions
587/// for a name*, not references to the deleted *instance*. A cross-link
588/// grant `test → other` names the gone instance and genuinely dangles,
589/// so it is scrubbed; a `[[mem_management.create]]` rule for `other`
590/// means "an agent may bring a mem named `other` into existence" and
591/// stays true after the delete. Scrubbing it would silently revoke a
592/// guarded-config permission as a side effect of an instance op, and
593/// force a fresh `allow-create` before the next `mem init other` —
594/// exactly the re-attach friction `unregister` avoids by preserving
595/// policy. So `delete` is idempotent w.r.t. a later re-create.
596///
597/// Silent no-op cases (returns `Ok(())` without touching the file):
598/// - `.memstead/workspace.toml` missing — pre-init workspaces (tests, ad-hoc
599///   consumers) have no policy state to scrub. The caller (delete
600///   orchestrator) already wrote nothing, so there's nothing to undo.
601/// - `.memstead/workspace.toml` unparseable — surfaces as `InvalidToml`.
602///
603/// IO failures surface as `WorkspaceEditError::Io`; the caller's outer
604/// engine-error type wraps that.
605pub 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            // Pre-init or operator-edited away — nothing to scrub.
614            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        // The deleted mem's own key — every grant `mem_name
636        // → <anything>` is dropped wholesale.
637        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        // Peer entries referencing the deleted mem as a grant
664        // target — drop the entry from the array; collapse empty
665        // arrays.
666        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    // The `[[mem_management.create]]` / `[[mem_management.delete]]`
695    // allowlist rules are deliberately NOT scrubbed — see this
696    // function's doc-comment for why deleting an instance must not
697    // revoke the forward-looking permission to (re-)create a mem of
698    // the same name.
699
700    if !scrubbed.is_empty() {
701        save(&path, &doc)?;
702    }
703    Ok(scrubbed)
704}
705
706/// One scrubbed entry returned from [`scrub_policy_for_deleted_mem`].
707/// The `memstead_mem_delete` response surfaces these so an agent sees
708/// every policy side effect in one round-trip. Only dangling
709/// `[cross_mem_links]` grants are scrubbed; the
710/// `[[mem_management.*]]` allowlist rules are preserved, so this enum
711/// carries the one scrubbed shape.
712#[derive(Debug, Clone, PartialEq, Eq)]
713pub enum ScrubbedEntry {
714    /// `[cross_mem_links]` grant naming the deleted mem on
715    /// either side.
716    CrossLink {
717        /// Source mem — the grant's table key.
718        from: String,
719        /// Target mem — array element or wildcard `"*"`.
720        to: String,
721    },
722}
723
724// --- internal helpers ---------------------------------------------------
725
726/// Rename every occurrence of mem `old` in the workspace's
727/// `[cross_mem_links]` table — as a granting key and inside named
728/// allowlist arrays — to `new`. The mem-rename counterpart of the
729/// grant/revoke pair: a pure key/value rewrite with none of their
730/// conflict semantics. A missing `workspace.toml` or absent
731/// `[cross_mem_links]` table is a no-op (nothing names the mem).
732/// Returns whether anything changed on disk.
733pub 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    // Value rewrite: any named allowlist entry equal to `old`.
749    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    // Key rewrite: `old` as a granting mem. toml_edit has no key
769    // rename; remove + reinsert preserves the value.
770    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
822/// Read the `schemas` string list off the rule at `idx` in `section`.
823/// Missing or malformed `schemas` reads as an empty list.
824fn 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
837/// Set-equality over two schema-pin lists (order- and duplicate-
838/// insensitive). A rule pinned to `[a, b]` re-added as `[b, a]` is the
839/// same allowlist, so it stays a clean no-op rather than a refusal.
840fn 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;