memstead-base 0.26.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! `toml_edit`-backed writer for `.memstead/workspace.toml`.
//!
//! Backs the `memstead workspace allow-create / revoke-create / allow-delete /
//! revoke-delete / grant-cross-link / revoke-cross-link / set-mutations`
//! subcommand family. Every operation is a load → mutate → write triple;
//! `toml_edit` preserves operator-authored comments and formatting on
//! sections the CLI doesn't touch (cross-mem forward-reference
//! rationale, ingest-namespace pairings, operator-mode bypass semantics,
//! pattern-grammar examples).
//!
//! Errors carry symbolic codes (`WORKSPACE_NOT_INITIALISED`,
//! `RULE_ALREADY_EXISTS`, `RULE_NOT_FOUND`, `BEFORE_PATTERN_NOT_FOUND`,
//! `CROSS_LINK_ALREADY_GRANTED`, `CROSS_LINK_NOT_GRANTED`,
//! `CROSS_LINK_CONFLICT`, `INVALID_TOML`) so the CLI's typed exit envelope
//! lifts them as `code` in the `--json` payload. The CLI layer maps the
//! enum variants onto `CliError` / `ExitKind`.

use std::fs;
use std::path::{Path, PathBuf};

use toml_edit::{Array, ArrayOfTables, DocumentMut, Item, Table, Value};

/// Errors returned by the writer.
///
/// The idempotency cases (`RuleAlreadyExists`, `RuleNotFound`,
/// `CrossLinkAlreadyGranted`, `CrossLinkNotGranted`) live on
/// [`WorkspaceEditWarning`] rather than here — re-grant / re-revoke /
/// re-add / re-remove return success-with-warning rather than refusing,
/// letting CLI scripts and MCP agents retry safely without
/// branching on prior state. `CrossLinkConflict` stays an error
/// because it's a real semantic conflict (wildcard vs. specific
/// list), not an idempotency case.
#[derive(Debug)]
pub enum WorkspaceEditError {
    /// `.memstead/workspace.toml` missing or unreadable. The workspace
    /// must be initialised before the CLI can edit its config.
    WorkspaceNotInitialised { path: PathBuf },
    /// Existing file failed to parse as TOML.
    InvalidToml { path: PathBuf, message: String },
    /// `add_create_rule` with `--before <p>` where `<p>` isn't an
    /// existing pattern in the section.
    BeforePatternNotFound {
        section: &'static str,
        pattern: String,
    },
    /// `grant_cross_link` with `*` against an existing specific list,
    /// or with a specific target against an existing `*`. Operators
    /// pick a single shape per `from`-mem.
    CrossLinkConflict { from: String, message: String },
    /// `add_create_rule` called for a pattern that already exists but
    /// with a **different** schema set. Refused rather than silently
    /// no-op'd: changing a pattern's schema pins is a security-relevant
    /// policy change, so it must be explicit (revoke the rule, then
    /// re-add with the new schemas) — never a silent success echoing a
    /// change that did not land. The genuine no-op (identical schemas)
    /// stays [`WorkspaceEditWarning::RuleAlreadyPresent`].
    RuleExistsSchemasDiffer {
        section: &'static str,
        pattern: String,
        stored: Vec<String>,
        requested: Vec<String>,
    },
    /// IO failure writing the file back.
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

/// Idempotency notices emitted by the writer when a call lands on
/// a state the caller intended (re-grant of an existing grant,
/// re-revoke of an absent grant, etc.). Surfacing these as warnings
/// rather than errors lets agents and scripts retry without branching
/// on prior state.
#[derive(Debug, Clone)]
pub enum WorkspaceEditWarning {
    /// `add_create_rule` / `add_delete_rule` called with a pattern
    /// that already has a matching entry. File unchanged.
    RuleAlreadyPresent {
        section: &'static str,
        pattern: String,
    },
    /// `remove_create_rule` / `remove_delete_rule` called with a
    /// pattern that has no matching entry. File unchanged.
    RuleNotFoundNoop {
        section: &'static str,
        pattern: String,
    },
    /// `grant_cross_link` called with a `(from, to)` pair already
    /// permitted (target already in the allowlist, or `*` already
    /// set). File unchanged.
    GrantAlreadyPresent { from: String, to: String },
    /// `revoke_cross_link` called with a `(from, to)` pair that
    /// isn't currently permitted. File unchanged.
    GrantNotFound { from: String, to: String },
    /// `grant_cross_link` named a `to` target that isn't a registered
    /// mem (and isn't the `*` wildcard). The grant still persists —
    /// the forward-reference workflow (grant before the target mem
    /// exists) is legitimate — but a likely typo is surfaced.
    CrossLinkTargetUnregistered { to: String },
    /// `grant_cross_link` named `to == from` — a self-grant. Intra-mem
    /// links never traverse the cross-link gate, so the grant is a
    /// no-op. It still persists; the meaninglessness is surfaced.
    CrossLinkSelfGrantNoop { mem: String },
    /// `revoke_cross_link` removed a grant that existing edges were
    /// relying on. The edges are NOT removed — a policy edit must not
    /// delete user data — but they are now in a state the default-deny
    /// write gate would refuse to create, so they are named at the moment
    /// the operator can act on them cheapest rather than left for a later
    /// gate run.
    ///
    /// Rides the warning channel deliberately: every revoke surface
    /// already renders these, so the CLI operator, the HTTP client and the
    /// web app get the same account without three separate renderings.
    CrossLinkRevokeOrphanedEdges { edges: Vec<String> },
}

impl WorkspaceEditWarning {
    /// Stable UPPER_SNAKE_CASE code surfaced as the CLI's stderr
    /// notice and as the MCP wrapper's warning envelope.
    pub fn code(&self) -> &'static str {
        match self {
            Self::RuleAlreadyPresent { .. } => "RULE_ALREADY_PRESENT",
            Self::RuleNotFoundNoop { .. } => "RULE_NOT_FOUND_NOOP",
            Self::GrantAlreadyPresent { .. } => "GRANT_ALREADY_PRESENT",
            Self::GrantNotFound { .. } => "GRANT_NOT_FOUND",
            Self::CrossLinkTargetUnregistered { .. } => "CROSS_LINK_TARGET_UNREGISTERED",
            Self::CrossLinkSelfGrantNoop { .. } => "CROSS_LINK_SELF_GRANT_NOOP",
            Self::CrossLinkRevokeOrphanedEdges { .. } => "CROSS_LINK_REVOKE_ORPHANED_EDGES",
        }
    }
}

impl std::fmt::Display for WorkspaceEditWarning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RuleAlreadyPresent { section, pattern } => write!(
                f,
                "`[[{section}]]` already contains an entry for pattern `{pattern}` — file unchanged"
            ),
            Self::RuleNotFoundNoop { section, pattern } => write!(
                f,
                "`[[{section}]]` has no entry for pattern `{pattern}` — file unchanged"
            ),
            Self::GrantAlreadyPresent { from, to } => write!(
                f,
                "`[cross_mem_links]` already grants {from} → {to} — file unchanged"
            ),
            Self::GrantNotFound { from, to } => write!(
                f,
                "`[cross_mem_links]` does not grant {from} → {to} — file unchanged"
            ),
            Self::CrossLinkTargetUnregistered { to } => write!(
                f,
                "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"
            ),
            Self::CrossLinkSelfGrantNoop { mem } => write!(
                f,
                "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"
            ),
            Self::CrossLinkRevokeOrphanedEdges { edges } => write!(
                f,
                "{} 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)",
                edges.len(),
                edges.join(", ")
            ),
        }
    }
}

impl std::fmt::Display for WorkspaceEditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WorkspaceNotInitialised { path, .. } => write!(
                f,
                "no `.memstead/workspace.toml` at {} — run `memstead mem-repo init` or `memstead init` first",
                path.display()
            ),
            Self::InvalidToml { path, message } => {
                write!(f, "{}: failed to parse TOML — {message}", path.display())
            }
            Self::BeforePatternNotFound { section, pattern } => write!(
                f,
                "`--before {pattern}` did not match any existing `[[{section}]]` entry"
            ),
            Self::CrossLinkConflict { from, message } => write!(
                f,
                "`[cross_mem_links]` rejects edit for `{from}`: {message}"
            ),
            Self::RuleExistsSchemasDiffer {
                section,
                pattern,
                stored,
                requested,
            } => write!(
                f,
                "`[[{section}]]` already has a rule for pattern `{pattern}` pinned to schemas [{}], \
                 which differs from the requested [{}] — refusing to silently change the schema pins. \
                 To change them, revoke the rule first (`revoke_create {pattern}`) then re-add it with the new schemas",
                stored.join(", "),
                requested.join(", "),
            ),
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
        }
    }
}

impl std::error::Error for WorkspaceEditError {}

impl WorkspaceEditError {
    /// Stable symbolic code used by the CLI exit envelope.
    pub fn code(&self) -> &'static str {
        match self {
            Self::WorkspaceNotInitialised { .. } => "WORKSPACE_NOT_INITIALISED",
            Self::InvalidToml { .. } => "INVALID_TOML",
            Self::BeforePatternNotFound { .. } => "BEFORE_PATTERN_NOT_FOUND",
            Self::CrossLinkConflict { .. } => "CROSS_LINK_CONFLICT",
            Self::RuleExistsSchemasDiffer { .. } => "RULE_EXISTS_SCHEMAS_DIFFER",
            Self::Io { .. } => "IO_ERROR",
        }
    }
}

/// Path of the workspace config file relative to the workspace root.
pub fn workspace_toml_path(workspace_root: &Path) -> PathBuf {
    workspace_root
        .join(crate::WORKSPACE_STORE_DIR)
        .join("workspace.toml")
}

fn load(workspace_root: &Path) -> Result<(PathBuf, DocumentMut), WorkspaceEditError> {
    let path = workspace_toml_path(workspace_root);
    let text = fs::read_to_string(&path).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            WorkspaceEditError::WorkspaceNotInitialised { path: path.clone() }
        } else {
            WorkspaceEditError::Io {
                path: path.clone(),
                source,
            }
        }
    })?;
    let doc: DocumentMut =
        text.parse()
            .map_err(|e: toml_edit::TomlError| WorkspaceEditError::InvalidToml {
                path: path.clone(),
                message: e.to_string(),
            })?;
    Ok((path, doc))
}

fn save(path: &Path, doc: &DocumentMut) -> Result<(), WorkspaceEditError> {
    fs::write(path, doc.to_string()).map_err(|source| WorkspaceEditError::Io {
        path: path.to_path_buf(),
        source,
    })
}

/// Either-or shape mirroring `[cross_mem_links]` semantics on disk:
/// `<from> = "*"` (wildcard) or `<from> = ["a", "b"]` (allowlist). The
/// CLI exposes both via `--target *` and `--target <name>` on
/// `grant-cross-link`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CrossLinkTarget {
    /// `*` — every current writable target is permitted.
    Wildcard,
    /// One named target. Multiple grants accumulate into the
    /// underlying `<from> = ["a", "b", ...]` list on disk.
    Named(String),
}

impl CrossLinkTarget {
    /// Parse a CLI-supplied target token. `*` maps to the wildcard
    /// shape; anything else maps to the named shape verbatim. The
    /// caller validates name shape elsewhere (the engine's existing
    /// mem-name validation runs on load).
    pub fn parse(raw: &str) -> Self {
        if raw == "*" {
            Self::Wildcard
        } else {
            Self::Named(raw.to_string())
        }
    }
}

/// `memstead workspace allow-create <pattern> --schema <pin>[,…] [--cross-link …]
/// [--before <pattern>]` — append a `[[mem_management.create]]` rule.
/// Default ordering is append (lowest priority); `before` flags lift it
/// above the named pattern.
pub fn add_create_rule(
    workspace_root: &Path,
    pattern: &str,
    schemas: &[String],
    default_cross_links: Option<&[CrossLinkTarget]>,
    before: Option<&str>,
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let section = ensure_array_of_tables(&mut doc, "mem_management", "create");

    if let Some(idx) = find_pattern_index(section, pattern) {
        // Pattern already present. Compare the stored schema set against
        // the requested one: identical → clean idempotent no-op; a
        // *difference* must not silently no-op (and must not echo a
        // change that did not land), so refuse with an actionable typed
        // error pointing at the revoke-then-readd recovery.
        let stored = read_rule_schemas(section, idx);
        if schema_sets_equal(&stored, schemas) {
            return Ok(vec![WorkspaceEditWarning::RuleAlreadyPresent {
                section: "mem_management.create",
                pattern: pattern.to_string(),
            }]);
        }
        return Err(WorkspaceEditError::RuleExistsSchemasDiffer {
            section: "mem_management.create",
            pattern: pattern.to_string(),
            stored,
            requested: schemas.to_vec(),
        });
    }

    let mut table = Table::new();
    table["pattern"] = Item::Value(Value::from(pattern));
    let mut arr = Array::new();
    for s in schemas {
        arr.push(s.as_str());
    }
    table["schemas"] = Item::Value(Value::Array(arr));
    if let Some(cross_links) = default_cross_links {
        table["default_cross_links"] = cross_link_value_item(cross_links);
    }

    if let Some(before_pattern) = before {
        let idx = find_pattern_index(section, before_pattern).ok_or_else(|| {
            WorkspaceEditError::BeforePatternNotFound {
                section: "mem_management.create",
                pattern: before_pattern.to_string(),
            }
        })?;
        // `ArrayOfTables` has no `insert(idx, table)`; emulate it by
        // detaching every entry from `idx` onward, pushing the new
        // table, then pushing the detached entries back.
        let mut tail = Vec::with_capacity(section.len() - idx);
        while section.len() > idx {
            let last = section.get(section.len() - 1).cloned().unwrap();
            tail.push(last);
            section.remove(section.len() - 1);
        }
        section.push(table);
        for entry in tail.into_iter().rev() {
            section.push(entry);
        }
    } else {
        section.push(table);
    }

    save(&path, &doc)?;
    Ok(Vec::new())
}

/// `memstead workspace revoke-create <pattern>` — remove a
/// `[[mem_management.create]]` rule by pattern.
pub fn remove_create_rule(
    workspace_root: &Path,
    pattern: &str,
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let section = ensure_array_of_tables(&mut doc, "mem_management", "create");
    let idx = match find_pattern_index(section, pattern) {
        Some(i) => i,
        None => {
            return Ok(vec![WorkspaceEditWarning::RuleNotFoundNoop {
                section: "mem_management.create",
                pattern: pattern.to_string(),
            }]);
        }
    };
    section.remove(idx);
    save(&path, &doc)?;
    Ok(Vec::new())
}

/// `memstead workspace allow-delete <pattern>` — append a
/// `[[mem_management.delete]]` rule.
pub fn add_delete_rule(
    workspace_root: &Path,
    pattern: &str,
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let section = ensure_array_of_tables(&mut doc, "mem_management", "delete");
    if find_pattern_index(section, pattern).is_some() {
        return Ok(vec![WorkspaceEditWarning::RuleAlreadyPresent {
            section: "mem_management.delete",
            pattern: pattern.to_string(),
        }]);
    }
    let mut table = Table::new();
    table["pattern"] = Item::Value(Value::from(pattern));
    section.push(table);
    save(&path, &doc)?;
    Ok(Vec::new())
}

/// `memstead workspace revoke-delete <pattern>` — remove a
/// `[[mem_management.delete]]` rule by pattern.
pub fn remove_delete_rule(
    workspace_root: &Path,
    pattern: &str,
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let section = ensure_array_of_tables(&mut doc, "mem_management", "delete");
    let idx = match find_pattern_index(section, pattern) {
        Some(i) => i,
        None => {
            return Ok(vec![WorkspaceEditWarning::RuleNotFoundNoop {
                section: "mem_management.delete",
                pattern: pattern.to_string(),
            }]);
        }
    };
    section.remove(idx);
    save(&path, &doc)?;
    Ok(Vec::new())
}

/// `memstead workspace grant-cross-link <from> <to>` — add `to` to the
/// allowlist for `from` in `[cross_mem_links]`. `to == "*"` sets the
/// wildcard shape; named targets accumulate into a list.
pub fn grant_cross_link(
    workspace_root: &Path,
    from: &str,
    to: &CrossLinkTarget,
    known_mems: &[String],
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    // Diligence (matching the sibling `revoke_cross_link`'s warn-on-
    // anomaly behaviour): warn — never block — on a self-grant or an
    // unregistered named target. The grant still persists so the
    // forward-reference workflow (grant before the target mem exists)
    // stays open. The `*` wildcard is a legitimate non-mem token and
    // is not validated against the registered set.
    let mut warnings: Vec<WorkspaceEditWarning> = Vec::new();
    if let CrossLinkTarget::Named(name) = to {
        if name == from {
            warnings.push(WorkspaceEditWarning::CrossLinkSelfGrantNoop {
                mem: from.to_string(),
            });
        } else if !known_mems.iter().any(|v| v == name) {
            warnings.push(WorkspaceEditWarning::CrossLinkTargetUnregistered { to: name.clone() });
        }
    }

    let (path, mut doc) = load(workspace_root)?;
    let table = ensure_table(&mut doc, "cross_mem_links");
    match (table.get(from), to) {
        (None, CrossLinkTarget::Wildcard) => {
            table.insert(from, Item::Value(Value::from("*")));
        }
        (None, CrossLinkTarget::Named(name)) => {
            let mut arr = Array::new();
            arr.push(name.as_str());
            table.insert(from, Item::Value(Value::Array(arr)));
        }
        (Some(Item::Value(Value::String(s))), CrossLinkTarget::Wildcard) if s.value() == "*" => {
            warnings.push(WorkspaceEditWarning::GrantAlreadyPresent {
                from: from.to_string(),
                to: "*".to_string(),
            });
            return Ok(warnings);
        }
        (Some(Item::Value(Value::String(_))), _) => {
            return Err(WorkspaceEditError::CrossLinkConflict {
                from: from.to_string(),
                message: "wildcard `*` already set — revoke `*` before granting a named target"
                    .to_string(),
            });
        }
        (Some(Item::Value(Value::Array(_))), CrossLinkTarget::Wildcard) => {
            return Err(WorkspaceEditError::CrossLinkConflict {
                from: from.to_string(),
                message: "specific allowlist already set — revoke every entry before granting `*`"
                    .to_string(),
            });
        }
        (Some(Item::Value(Value::Array(arr))), CrossLinkTarget::Named(name)) => {
            if array_contains(arr, name) {
                warnings.push(WorkspaceEditWarning::GrantAlreadyPresent {
                    from: from.to_string(),
                    to: name.clone(),
                });
                return Ok(warnings);
            }
            let mut arr = arr.clone();
            arr.push(name.as_str());
            table.insert(from, Item::Value(Value::Array(arr)));
        }
        (Some(_), _) => {
            return Err(WorkspaceEditError::CrossLinkConflict {
                from: from.to_string(),
                message: "existing value is neither a string nor an array — fix by hand"
                    .to_string(),
            });
        }
    }
    save(&path, &doc)?;
    Ok(warnings)
}

/// `memstead workspace revoke-cross-link <from> <to>` — remove `to` from
/// the allowlist for `from`. When the underlying list becomes empty,
/// the `<from>` key is dropped entirely; `*` is matched as a literal.
pub fn revoke_cross_link(
    workspace_root: &Path,
    from: &str,
    to: &CrossLinkTarget,
) -> Result<Vec<WorkspaceEditWarning>, WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let table = ensure_table(&mut doc, "cross_mem_links");
    let removed = match (table.get(from), to) {
        (None, _) => false,
        (Some(Item::Value(Value::String(s))), CrossLinkTarget::Wildcard) if s.value() == "*" => {
            table.remove(from);
            true
        }
        (Some(Item::Value(Value::String(_))), CrossLinkTarget::Named(_)) => false,
        (Some(Item::Value(Value::String(_))), CrossLinkTarget::Wildcard) => false,
        (Some(Item::Value(Value::Array(_))), CrossLinkTarget::Wildcard) => false,
        (Some(Item::Value(Value::Array(arr))), CrossLinkTarget::Named(name)) => {
            let mut arr = arr.clone();
            let original_len = arr.len();
            arr.retain(|v| match v {
                Value::String(s) => s.value() != name,
                _ => true,
            });
            if arr.len() == original_len {
                false
            } else if arr.is_empty() {
                table.remove(from);
                true
            } else {
                table.insert(from, Item::Value(Value::Array(arr)));
                true
            }
        }
        (Some(_), _) => false,
    };
    if !removed {
        let target = match to {
            CrossLinkTarget::Wildcard => "*".to_string(),
            CrossLinkTarget::Named(s) => s.clone(),
        };
        return Ok(vec![WorkspaceEditWarning::GrantNotFound {
            from: from.to_string(),
            to: target,
        }]);
    }
    save(&path, &doc)?;
    Ok(Vec::new())
}

/// `memstead workspace set-mutations --require-notes <bool>` — set the
/// `[mutations] require_notes` field. Creates the section on demand.
pub fn set_mutation_require_notes(
    workspace_root: &Path,
    value: bool,
) -> Result<(), WorkspaceEditError> {
    let (path, mut doc) = load(workspace_root)?;
    let table = ensure_table(&mut doc, "mutations");
    table.insert("require_notes", Item::Value(Value::from(value)));
    save(&path, &doc)
}

/// Scrub `.memstead/workspace.toml` of the now-dangling `[cross_mem_links]`
/// grants naming `mem_name` so the workspace no longer references a
/// mem the engine just destructively deleted. The
/// `[[mem_management.create]]` / `[[mem_management.delete]]`
/// allowlist rules are deliberately left intact.
///
/// Two passes, both on the in-memory `DocumentMut` before one final
/// save:
///   1. `[cross_mem_links]` — drop the key `mem_name` if present
///      (the deleted mem as `from`).
///   2. `[cross_mem_links]` — remove `mem_name` from every other
///      key's allowlist `Array`. When an allowlist becomes empty,
///      drop the key entirely (mirrors `revoke_cross_link`).
///
/// What is NOT scrubbed, and why: the `[[mem_management.create]]` /
/// `[[mem_management.delete]]` rules are forward-looking *permissions
/// for a name*, not references to the deleted *instance*. A cross-link
/// grant `test → other` names the gone instance and genuinely dangles,
/// so it is scrubbed; a `[[mem_management.create]]` rule for `other`
/// means "an agent may bring a mem named `other` into existence" and
/// stays true after the delete. Scrubbing it would silently revoke a
/// guarded-config permission as a side effect of an instance op, and
/// force a fresh `allow-create` before the next `mem init other` —
/// exactly the re-attach friction `unregister` avoids by preserving
/// policy. So `delete` is idempotent w.r.t. a later re-create.
///
/// Silent no-op cases (returns `Ok(())` without touching the file):
/// - `.memstead/workspace.toml` missing — pre-init workspaces (tests, ad-hoc
///   consumers) have no policy state to scrub. The caller (delete
///   orchestrator) already wrote nothing, so there's nothing to undo.
/// - `.memstead/workspace.toml` unparseable — surfaces as `InvalidToml`.
///
/// IO failures surface as `WorkspaceEditError::Io`; the caller's outer
/// engine-error type wraps that.
pub fn scrub_policy_for_deleted_mem(
    workspace_root: &Path,
    mem_name: &str,
) -> Result<Vec<ScrubbedEntry>, WorkspaceEditError> {
    let path = workspace_toml_path(workspace_root);
    let text = match fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // Pre-init or operator-edited away — nothing to scrub.
            return Ok(Vec::new());
        }
        Err(source) => {
            return Err(WorkspaceEditError::Io {
                path: path.clone(),
                source,
            });
        }
    };
    let mut doc: DocumentMut =
        text.parse()
            .map_err(|e: toml_edit::TomlError| WorkspaceEditError::InvalidToml {
                path: path.clone(),
                message: e.to_string(),
            })?;

    let mut scrubbed: Vec<ScrubbedEntry> = Vec::new();

    if let Some(item) = doc.get_mut("cross_mem_links")
        && let Some(table) = item.as_table_mut()
    {
        // The deleted mem's own key — every grant `mem_name
        // → <anything>` is dropped wholesale.
        if let Some(removed) = table.remove(mem_name) {
            let targets = match removed {
                Item::Value(Value::Array(arr)) => arr
                    .iter()
                    .filter_map(|v| match v {
                        Value::String(s) => Some(s.value().to_string()),
                        _ => None,
                    })
                    .collect::<Vec<_>>(),
                Item::Value(Value::String(s)) => vec![s.value().to_string()],
                _ => Vec::new(),
            };
            if targets.is_empty() {
                scrubbed.push(ScrubbedEntry::CrossLink {
                    from: mem_name.to_string(),
                    to: "*".to_string(),
                });
            } else {
                for to in targets {
                    scrubbed.push(ScrubbedEntry::CrossLink {
                        from: mem_name.to_string(),
                        to,
                    });
                }
            }
        }
        // Peer entries referencing the deleted mem as a grant
        // target — drop the entry from the array; collapse empty
        // arrays.
        let keys: Vec<String> = table.iter().map(|(k, _)| k.to_string()).collect();
        for key in keys {
            let drop_key = match table.get(&key) {
                Some(Item::Value(Value::Array(arr))) if array_contains(arr, mem_name) => {
                    let mut arr = arr.clone();
                    arr.retain(|v| match v {
                        Value::String(s) => s.value() != mem_name,
                        _ => true,
                    });
                    scrubbed.push(ScrubbedEntry::CrossLink {
                        from: key.clone(),
                        to: mem_name.to_string(),
                    });
                    if arr.is_empty() {
                        true
                    } else {
                        table.insert(&key, Item::Value(Value::Array(arr)));
                        false
                    }
                }
                _ => false,
            };
            if drop_key {
                table.remove(&key);
            }
        }
    }

    // The `[[mem_management.create]]` / `[[mem_management.delete]]`
    // allowlist rules are deliberately NOT scrubbed — see this
    // function's doc-comment for why deleting an instance must not
    // revoke the forward-looking permission to (re-)create a mem of
    // the same name.

    if !scrubbed.is_empty() {
        save(&path, &doc)?;
    }
    Ok(scrubbed)
}

/// One scrubbed entry returned from [`scrub_policy_for_deleted_mem`].
/// The `memstead_mem_delete` response surfaces these so an agent sees
/// every policy side effect in one round-trip. Only dangling
/// `[cross_mem_links]` grants are scrubbed; the
/// `[[mem_management.*]]` allowlist rules are preserved, so this enum
/// carries the one scrubbed shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScrubbedEntry {
    /// `[cross_mem_links]` grant naming the deleted mem on
    /// either side.
    CrossLink {
        /// Source mem — the grant's table key.
        from: String,
        /// Target mem — array element or wildcard `"*"`.
        to: String,
    },
}

// --- internal helpers ---------------------------------------------------

/// Rename every occurrence of mem `old` in the workspace's
/// `[cross_mem_links]` table — as a granting key and inside named
/// allowlist arrays — to `new`. The mem-rename counterpart of the
/// grant/revoke pair: a pure key/value rewrite with none of their
/// conflict semantics. A missing `workspace.toml` or absent
/// `[cross_mem_links]` table is a no-op (nothing names the mem).
/// Returns whether anything changed on disk.
pub fn rename_mem_in_cross_links(
    workspace_root: &Path,
    old: &str,
    new: &str,
) -> Result<bool, WorkspaceEditError> {
    let (path, mut doc) = match load(workspace_root) {
        Ok(pair) => pair,
        Err(WorkspaceEditError::WorkspaceNotInitialised { .. }) => return Ok(false),
        Err(e) => return Err(e),
    };
    let Some(table) = doc.get_mut("cross_mem_links").and_then(Item::as_table_mut) else {
        return Ok(false);
    };

    let mut changed = false;
    // Value rewrite: any named allowlist entry equal to `old`.
    for (_key, item) in table.iter_mut() {
        if let Item::Value(Value::Array(arr)) = item {
            let mut next = Array::new();
            let mut arr_changed = false;
            for v in arr.iter() {
                match v.as_str() {
                    Some(s) if s == old => {
                        next.push(new);
                        arr_changed = true;
                    }
                    _ => next.push(v.clone()),
                }
            }
            if arr_changed {
                *item = Item::Value(Value::Array(next));
                changed = true;
            }
        }
    }
    // Key rewrite: `old` as a granting mem. toml_edit has no key
    // rename; remove + reinsert preserves the value.
    if let Some(value) = table.remove(old) {
        table.insert(new, value);
        changed = true;
    }

    if changed {
        save(&path, &doc)?;
    }
    Ok(changed)
}

fn ensure_table<'a>(doc: &'a mut DocumentMut, name: &str) -> &'a mut Table {
    if !doc.contains_key(name) {
        let mut t = Table::new();
        t.set_implicit(false);
        doc.insert(name, Item::Table(t));
    }
    doc.get_mut(name)
        .unwrap()
        .as_table_mut()
        .expect("ensured table shape")
}

fn ensure_array_of_tables<'a>(
    doc: &'a mut DocumentMut,
    outer: &str,
    inner: &str,
) -> &'a mut ArrayOfTables {
    if !doc.contains_key(outer) {
        let mut t = Table::new();
        t.set_implicit(true);
        doc.insert(outer, Item::Table(t));
    }
    let outer_table = doc
        .get_mut(outer)
        .and_then(|i| i.as_table_mut())
        .expect("mem_management must be a table");
    if !outer_table.contains_key(inner) {
        outer_table.insert(inner, Item::ArrayOfTables(ArrayOfTables::new()));
    }
    outer_table
        .get_mut(inner)
        .and_then(|i| i.as_array_of_tables_mut())
        .expect("ensured array-of-tables shape")
}

fn find_pattern_index(section: &ArrayOfTables, pattern: &str) -> Option<usize> {
    section
        .iter()
        .position(|t| t.get("pattern").and_then(|i| i.as_str()) == Some(pattern))
}

/// Read the `schemas` string list off the rule at `idx` in `section`.
/// Missing or malformed `schemas` reads as an empty list.
fn read_rule_schemas(section: &ArrayOfTables, idx: usize) -> Vec<String> {
    section
        .get(idx)
        .and_then(|t| t.get("schemas"))
        .and_then(|i| i.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// Set-equality over two schema-pin lists (order- and duplicate-
/// insensitive). A rule pinned to `[a, b]` re-added as `[b, a]` is the
/// same allowlist, so it stays a clean no-op rather than a refusal.
fn schema_sets_equal(a: &[String], b: &[String]) -> bool {
    let mut a: Vec<&str> = a.iter().map(String::as_str).collect();
    let mut b: Vec<&str> = b.iter().map(String::as_str).collect();
    a.sort_unstable();
    a.dedup();
    b.sort_unstable();
    b.dedup();
    a == b
}

fn cross_link_value_item(targets: &[CrossLinkTarget]) -> Item {
    if targets
        .iter()
        .any(|t| matches!(t, CrossLinkTarget::Wildcard))
    {
        Item::Value(Value::from("*"))
    } else {
        let mut arr = Array::new();
        for t in targets {
            if let CrossLinkTarget::Named(name) = t {
                arr.push(name.as_str());
            }
        }
        Item::Value(Value::Array(arr))
    }
}

fn array_contains(arr: &Array, needle: &str) -> bool {
    arr.iter().any(|v| match v {
        Value::String(s) => s.value() == needle,
        _ => false,
    })
}

#[cfg(test)]
mod tests;