Skip to main content

memstead_base/engine/mutation/
delete.rs

1//! `Engine::delete_entity` — remove an entity from a mount's backend
2//! and the in-memory store.
3
4use std::path::Path;
5
6use crate::entity::EntityId;
7use crate::ops::WarningHint;
8use crate::provenance::{Provenance, ProvenanceKind};
9use crate::vcs::{Actor, ClientId, CommitContext};
10use crate::workspace::MountCapability;
11
12use super::super::{DeleteEntityArgs, DeleteEntityOutcome, Engine, EngineError, ReferrerInfo};
13use super::{gc_orphan_stubs, make_stub};
14
15/// The would-be delete outcome for an entity, derived purely from the
16/// in-memory graph (no mutation). `write_referrers` are the Write-Mem
17/// sources that block a delete (`HAS_INCOMING_REFS`); `readonly_referrers`
18/// are ReadOnly-mount sources that instead trigger the residual-stub
19/// demotion. Both empty ⇒ a clean removal. Shared by [`Engine::delete_entity`]
20/// (the real guard) and the CLI `delete --dry-run` preview so the preview's
21/// verdict cannot drift from the real outcome.
22#[derive(Debug, Clone)]
23pub struct DeleteReferrers {
24    pub write_referrers: Vec<ReferrerInfo>,
25    pub readonly_referrers: Vec<EntityId>,
26}
27
28impl DeleteReferrers {
29    /// Whether the real delete would refuse with `HAS_INCOMING_REFS`.
30    pub fn would_refuse(&self) -> bool {
31        !self.write_referrers.is_empty()
32    }
33}
34
35impl Engine {
36    /// Classify an entity's incoming referrers by the source mount's
37    /// capability — the read-only core of the delete guard. Write-Mem
38    /// referrers block the delete; ReadOnly referrers trigger the
39    /// residual-stub demotion. Per-source dedup collapses an N-edge
40    /// source into one [`ReferrerInfo`] carrying every rel-type. A
41    /// referrer in an unmounted mem is treated as Write
42    /// (safe-by-default: refuse rather than silently demote).
43    ///
44    /// Pure read — no disk, commit, lock, or store mutation. Used by
45    /// [`Self::delete_entity`] and the CLI `delete --dry-run` preview so
46    /// both compute the same verdict from one implementation.
47    pub fn classify_delete_referrers(&self, id: &EntityId) -> DeleteReferrers {
48        let mut write_referrers: Vec<ReferrerInfo> = Vec::new();
49        let mut readonly_referrers: Vec<EntityId> = Vec::new();
50        for edge in self.store.incoming(id) {
51            let from_mem = edge.from.mem().to_string();
52            let cap = self
53                .mounts
54                .iter()
55                .find(|m| m.mount.mem == from_mem)
56                .map(|m| m.mount.capability)
57                .unwrap_or(MountCapability::Write);
58            match cap {
59                MountCapability::Write => {
60                    let from_id = edge.from.to_string();
61                    if let Some(existing) =
62                        write_referrers.iter_mut().find(|r| r.from_id == from_id)
63                    {
64                        if !existing.rel_types.contains(&edge.rel_type) {
65                            existing.rel_types.push(edge.rel_type.clone());
66                        }
67                    } else {
68                        write_referrers.push(ReferrerInfo {
69                            from_id,
70                            rel_types: vec![edge.rel_type.clone()],
71                            mem: from_mem,
72                        });
73                    }
74                }
75                MountCapability::ReadOnly => readonly_referrers.push(edge.from.clone()),
76            }
77        }
78        DeleteReferrers {
79            write_referrers,
80            readonly_referrers,
81        }
82    }
83
84    /// Delete an entity from its mount.
85    ///
86    /// Binary semantics — there is no force flag. The engine partitions
87    /// incoming references by the source mem's
88    /// [`MountCapability`]:
89    ///
90    /// - any **Write-Mem** referrers → refuse with typed
91    ///   [`EngineError::HasIncomingRefs`] carrying the structured
92    ///   referrer list;
93    /// - only **ReadOnly-mount** referrers → delete the file +
94    ///   commit, then demote the in-memory entity to a stub at the
95    ///   same id so the surviving incoming edges keep a valid target.
96    ///   A `RESIDUAL_STUB_FOR_READONLY_REFERRERS` warning rides on
97    ///   the outcome;
98    /// - no referrers → clean removal (file + store entry + cascading
99    ///   edges). Orphaned stubs whose last incoming edge was the
100    ///   deleted entity are GC'd.
101    ///
102    /// Optimistic-locking via `args.expected_hash` matches
103    /// `update_entity`. Stubs (no on-disk file) skip the backend
104    /// write and commit but still log provenance.
105    pub fn delete_entity(
106        &mut self,
107        args: DeleteEntityArgs,
108        actor: Actor,
109        client: Option<&ClientId>,
110        note: Option<&str>,
111    ) -> Result<DeleteEntityOutcome, EngineError> {
112        // A short id resolves (or refuses) before anything reads its mem.
113        let mut args = args;
114        let (resolved, short_hint) = self.resolve_entity_id(&args.id)?;
115        args.id = resolved;
116        let id = &args.id;
117        let mem = id.mem().to_string();
118
119        let mount_idx = self
120            .mounts
121            .iter()
122            .position(|m| m.mount.mem == mem)
123            .ok_or_else(|| self.unknown_mem_error(&mem))?;
124        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
125            return Err(EngineError::ReadOnlyMount(mem));
126        }
127
128        // Delete's race guard is `HAS_INCOMING_REFS`, and incoming
129        // edges can originate in ANY mem — so the check is only
130        // truthful over a complete store. A deferred (lazy, unloaded)
131        // mem's referrers would otherwise be invisible and the delete
132        // would silently admit what an eager boot refuses (the third
133        // lazy-mount grade demonstrated exactly that). Full load first;
134        // the drift reload below stays scoped to the target mem.
135        self.ensure_mems_loaded(None);
136
137        // Reload-before-operation: reload if a sibling advanced the
138        // mem ref, so the `expected_hash` compare and the
139        // referrer classification below see current truth. Notice
140        // rides the outcome's `warnings`.
141        let mut drift_warnings: Vec<WarningHint> = short_hint.into_iter().collect();
142        let _write_lock = self.lock_mems_for_write(&[&mem])?;
143        drift_warnings.extend(self.reload_if_stale(Some(&mem)));
144
145        let entity = self
146            .store
147            .get(id)
148            .ok_or_else(|| EngineError::NotFound { id: id.to_string() })?;
149
150        if let Some(expected) = args.expected_hash.as_deref()
151            && entity.content_hash != expected
152        {
153            // Stubs have no `content_hash` to compare against, so the
154            // pre-fix `(current: )` paren misdirected callers toward
155            // hash-recovery via `memstead_entity` (which returns the same
156            // empty hash). Surface `details.is_stub: true` and a
157            // corrective-action message — the actual fix is
158            // `expected_hash: ""`. Non-stub mismatches keep the prior
159            // contract.
160            return Err(EngineError::HashMismatch {
161                id: id.to_string(),
162                current: entity.content_hash.clone(),
163                is_stub: entity.stub,
164            });
165        }
166
167        let file_path = entity.file_path.clone();
168        let entity_is_stub = entity.stub;
169
170        // Partition incoming refs by the source mem's mount capability
171        // (Write-Mem referrers block; ReadOnly trigger the residual-stub
172        // demotion). The classification is shared with the CLI
173        // `delete --dry-run` preview so the two cannot disagree about the
174        // outcome.
175        let DeleteReferrers {
176            write_referrers,
177            readonly_referrers,
178        } = self.classify_delete_referrers(id);
179        if !write_referrers.is_empty() {
180            return Err(EngineError::HasIncomingRefs {
181                id: id.to_string(),
182                referrers: write_referrers,
183            });
184        }
185
186        let demote_to_stub = !readonly_referrers.is_empty();
187        let removed_incoming: Vec<String> =
188            readonly_referrers.iter().map(|id| id.to_string()).collect();
189
190        // Pre-delete edge count so the response carries the correct
191        // value regardless of whether we drop the entity or demote it
192        // to a stub. On the demote path we only retain incoming edges
193        // (outgoing are severed because the source entity is gone),
194        // so the cascade still removes `outgoing` worth of edges.
195        let relations_removed = if demote_to_stub {
196            self.store.outgoing(id).len()
197        } else {
198            self.store.outgoing(id).len() + self.store.incoming(id).len()
199        };
200
201        // Stubs have no on-disk file (empty file_path) and were never
202        // committed as their own grain — the relate that materialised
203        // them committed the source entity's markdown, the stub itself
204        // is in-memory + edge-index only. Routing a stub delete through
205        // `backend.delete_entity` trips `BackendError::Path("mem-
206        // relative path is empty"))`. Skip the backend write + commit
207        // for stubs; provenance still records the explicit drop so
208        // memstead_changes_since consumers see the event.
209        let backend = self.mounts[mount_idx].backend.as_ref();
210        let write_id = if entity_is_stub {
211            String::new()
212        } else {
213            backend.delete_entity(Path::new(&file_path))?;
214            // Remove the entity's anchor row in the SAME commit as the
215            // delete so no orphaned anchor for a deleted entity survives.
216            // A no-op when the entity had no anchors (byte-identical).
217            super::stage_anchors_removal(backend, id)?;
218            let commit_subject = format!("memstead: delete {id}");
219            let ctx = self.commit_context(
220                Some("delete_entity"),
221                actor,
222                client.cloned(),
223                note.map(String::from),
224            );
225            backend.commit(&commit_subject, &ctx)?
226        };
227
228        backend.append_provenance(
229            &Provenance::new(
230                std::time::SystemTime::now(),
231                ProvenanceKind::Delete,
232                Some(id.to_string()),
233                actor,
234                client.cloned(),
235                note.map(String::from),
236            )
237            .with_role(self.current_role)
238            .with_identity(self.current_identity.clone()),
239        )?;
240
241        let mut stamp_warnings: Vec<WarningHint> = Vec::new();
242        if !write_id.is_empty() {
243            self.record_self_write(mount_idx, &write_id);
244            stamp_warnings = self.stamp_mutation_versions(mount_idx);
245        }
246
247        let mut warnings: Vec<WarningHint> = Vec::new();
248        warnings.extend(std::mem::take(&mut stamp_warnings));
249        // Reload-before-operation drift notice, surfaced first.
250        warnings.append(&mut drift_warnings);
251        let orphan_stubs_removed = if demote_to_stub {
252            // Demote: drop outgoing edges (the source is gone), then
253            // upsert a stub at the same id so the surviving incoming
254            // edges from ReadOnly mounts retain a valid target. This
255            // mirrors the state a fresh boot would produce — the
256            // parser would re-emit a `LoadTime` stub at this id from
257            // the surviving ReadOnly wiki-links.
258            self.store.remove_edges_from(id);
259            self.store.upsert(
260                id.clone(),
261                make_stub(
262                    id,
263                    crate::entity::StubKind::Residual {
264                        since_commit: write_id.clone(),
265                        readonly_referrers: readonly_referrers.clone(),
266                    },
267                ),
268            );
269            warnings.push(WarningHint::ResidualStubForReadOnlyReferrers {
270                id: id.clone(),
271                referrers: readonly_referrers,
272            });
273            // Don't GC orphan stubs on the demote path — the entity we
274            // just demoted is itself a stub now and would be flagged
275            // as orphan if we count its surviving incoming edges
276            // wrong. Its incoming edges from ReadOnly are real and
277            // keep it alive; siblings are unaffected.
278            Vec::new()
279        } else {
280            self.store.remove(id);
281            // Sweep stubs whose last referrer was the deleted entity.
282            // Common case: the deleted entity had a relate edge to a
283            // stub target and was the only one holding it in-graph.
284            gc_orphan_stubs(&mut self.store)
285        };
286
287        self.invalidate_communities();
288        // Incremental (flywheel W8/01): the deleted id is removed from
289        // its index whether it left the store or demoted to a Residual
290        // stub (stubs are excluded either way); GC'd orphan stubs were
291        // never indexed.
292        self.maintain_search_indexes(std::slice::from_ref(id));
293
294        // `require_notes` provenance nudge — single engine-level
295        // enforcement point. Gated on a landed commit: a stub delete
296        // skips the backend write (empty `write_id`, nothing to
297        // attribute), so it doesn't demand a note.
298        if !write_id.is_empty()
299            && let Some(w) = self.note_missing_warning("delete_entity", note)
300        {
301            warnings.push(w);
302        }
303
304        Ok(DeleteEntityOutcome {
305            id: id.clone(),
306            file_path,
307            removed_incoming,
308            relations_removed,
309            write_id,
310            orphan_stubs_removed,
311            warnings,
312        })
313    }
314
315    /// Positional + CommitContext wrapper around
316    /// [`Self::delete_entity`]. Bundles `id` + `expected_hash` into
317    /// a [`DeleteEntityArgs`].
318    pub fn delete_entity_with_ctx(
319        &mut self,
320        id: &EntityId,
321        expected_hash: &str,
322        ctx: &CommitContext<'_>,
323    ) -> Result<DeleteEntityOutcome, EngineError> {
324        let args = DeleteEntityArgs {
325            id: id.clone(),
326            expected_hash: Some(expected_hash.to_string()),
327        };
328        self.delete_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
329    }
330}
331
332#[cfg(test)]
333mod tests {
334
335    use tempfile::TempDir;
336
337    use crate::backend::MemBackend;
338    use crate::engine::test_helpers::*;
339    use crate::engine::{
340        CreateEntityArgs, DeleteEntityArgs, Engine, EngineError, RelateEntityArgs,
341    };
342    use crate::ops::WarningHint;
343    use crate::storage::FilesystemBackend;
344
345    /// Seed a folder-backed engine with one anchored entity; return the
346    /// engine and the create outcome.
347    fn engine_with_anchored(
348        tmp: &TempDir,
349        title: &str,
350    ) -> (Engine, crate::engine::CreateEntityOutcome) {
351        let mem_dir = tmp.path().to_path_buf();
352        let writer = FilesystemBackend::new(mem_dir.clone());
353        let mut engine = Engine::from_mounts(vec![(
354            folder_mount("specs", mem_dir),
355            Box::new(writer) as Box<dyn MemBackend>,
356        )])
357        .unwrap();
358        let (actor, client) = cli_actor();
359        let mut args: CreateEntityArgs = empty_create_args("specs", title);
360        args.anchors = vec![crate::anchor::AnchorInput {
361            artifact: Some("src/lib.rs".into()),
362            grain: Some("file".into()),
363            class: Some("anchored".into()),
364            hash: Some("h1".into()),
365            hash_stability: Some("stable".into()),
366            ..Default::default()
367        }];
368        let outcome = engine
369            .create_entity(args, actor, Some(&client), None)
370            .unwrap();
371        (engine, outcome)
372    }
373
374    #[test]
375    fn delete_removes_entity_anchors_no_orphan() {
376        let tmp = TempDir::new().unwrap();
377        let (mut engine, seeded) = engine_with_anchored(&tmp, "Anchored Doomed");
378        assert_eq!(engine.entity_anchors(&seeded.id).len(), 1);
379        let (actor, client) = cli_actor();
380        engine
381            .delete_entity(
382                DeleteEntityArgs {
383                    id: seeded.id.clone(),
384                    expected_hash: Some(seeded.content_hash.clone()),
385                },
386                actor,
387                Some(&client),
388                None,
389            )
390            .unwrap();
391        // The entity's anchor row is gone — no orphaned anchor for a
392        // deleted entity.
393        assert!(engine.entity_anchors(&seeded.id).is_empty());
394        assert!(engine.anchors_referencing_artifact("src/lib.rs").is_empty());
395    }
396
397    /// Criterion 7 (consistency-sweep 03/02): the engine's own delete path
398    /// already stages the anchor removal, so the dangling detector must find
399    /// nothing afterwards. A fix that turned correct engine behaviour into a
400    /// finding would make every delete noisy.
401    #[test]
402    fn delete_through_the_engine_leaves_no_dangling_row() {
403        let tmp = TempDir::new().unwrap();
404        let (mut engine, seeded) = engine_with_anchored(&tmp, "Anchored Doomed");
405        let (actor, client) = cli_actor();
406        engine
407            .delete_entity(
408                DeleteEntityArgs {
409                    id: seeded.id.clone(),
410                    expected_hash: Some(seeded.content_hash.clone()),
411                },
412                actor,
413                Some(&client),
414                None,
415            )
416            .unwrap();
417        let report = engine.verify_mem_anchors("specs").unwrap();
418        assert_eq!(report.unreconciled, None, "the entity end was examined");
419        assert_eq!(
420            report.dangling, 0,
421            "the delete path took the row with it, so there is nothing to report"
422        );
423    }
424
425    /// Criteria 1 and 3 on the standalone surface. The artifact is present and
426    /// its hash matches, which is exactly the case that used to count as
427    /// `resolved` for an entity that no longer exists.
428    #[test]
429    fn a_row_whose_entity_vanished_reads_dangling_not_resolved() {
430        let tmp = TempDir::new().unwrap();
431        let (_engine, seeded) = engine_with_anchored(&tmp, "Anchored Vanishing");
432        // Out of band, which is the whole condition: the engine's own delete
433        // would have taken the sidecar row with it.
434        std::fs::remove_file(tmp.path().join(format!(
435            "{}.md",
436            seeded.id.as_ref().split_once("--").unwrap().1
437        )))
438        .unwrap();
439        let engine = Engine::from_mounts(vec![(
440            folder_mount("specs", tmp.path().to_path_buf()),
441            Box::new(FilesystemBackend::new(tmp.path().to_path_buf())) as Box<dyn MemBackend>,
442        )])
443        .unwrap();
444        drop(seeded);
445        let report = engine.verify_mem_anchors("specs").unwrap();
446        assert_eq!(report.dangling, 1);
447        assert_eq!(
448            report.figure.count_for_assertions(),
449            0,
450            "never evidence of health"
451        );
452        assert_eq!(
453            report.unresolvable, 0,
454            "and never folded into the artifact-end bucket, whose repair is the opposite"
455        );
456        assert_eq!(report.anchors[0].state, "dangling");
457    }
458
459    #[test]
460    fn delete_entity_removes_file_and_store_entry() {
461        let tmp = TempDir::new().unwrap();
462        let (mut engine, seeded) = engine_with_seed(&tmp, "Doomed");
463        let (actor, client) = cli_actor();
464        let outcome = engine
465            .delete_entity(
466                DeleteEntityArgs {
467                    id: seeded.id.clone(),
468                    expected_hash: Some(seeded.content_hash.clone()),
469                },
470                actor,
471                Some(&client),
472                None,
473            )
474            .unwrap();
475        assert_eq!(outcome.id, seeded.id);
476        assert_eq!(outcome.removed_incoming, Vec::<String>::new());
477        // Store no longer carries the entity.
478        assert!(engine.get_entity(&seeded.id).is_none());
479        // On-disk file gone.
480        assert!(!tmp.path().join(&seeded.file_path).exists());
481        // Provenance log records the delete.
482        let log = std::fs::read_to_string(tmp.path().join(".memstead/changes.jsonl")).unwrap();
483        assert!(log.contains("\"kind\":\"delete\""));
484    }
485
486    #[test]
487    fn delete_entity_rejects_hash_mismatch() {
488        let tmp = TempDir::new().unwrap();
489        let (mut engine, seeded) = engine_with_seed(&tmp, "Locked");
490        let (actor, client) = cli_actor();
491        let err = engine
492            .delete_entity(
493                DeleteEntityArgs {
494                    id: seeded.id.clone(),
495                    expected_hash: Some("nope".to_string()),
496                },
497                actor,
498                Some(&client),
499                None,
500            )
501            .unwrap_err();
502        match err {
503            EngineError::HashMismatch {
504                id,
505                current,
506                is_stub,
507            } => {
508                assert_eq!(id, seeded.id.to_string());
509                assert_eq!(current, seeded.content_hash);
510                assert!(!is_stub, "real entity must not flag as stub");
511            }
512            other => panic!("expected HashMismatch, got {other:?}"),
513        }
514    }
515
516    /// Item 04 — a stub delete with a non-empty `expected_hash` used to
517    /// trip the hash-mismatch path with `(current: )` empty paren,
518    /// misdirecting the agent toward `memstead_entity`-based hash recovery.
519    /// The recovery is `expected_hash: ""` — stubs have no content
520    /// hash. The typed envelope now surfaces `is_stub: true` and the
521    /// message names the corrective action directly.
522    #[test]
523    fn delete_entity_on_stub_with_non_empty_hash_surfaces_is_stub_flag() {
524        let tmp = TempDir::new().unwrap();
525        let (mut engine, _seed) = engine_with_seed(&tmp, "Anchor");
526        let (actor, client) = cli_actor();
527        // Materialise a stub via the forward-reference relate path: the
528        // stub keeps its incoming USES edge from the source, but
529        // `delete_entity` checks `expected_hash` BEFORE it partitions
530        // incoming refs, so the bogus-hash mismatch below fires
531        // regardless of the referrer. (The former body-wiki-link-drop
532        // trick no longer leaves an orphan to delete — the update path
533        // now runs the orphan-stub GC sweep alongside relate-remove and
534        // delete.)
535        let stub_id = crate::EntityId::new("specs", "stub-target");
536        let source = engine
537            .create_entity(
538                empty_create_args("specs", "Source With Link"),
539                actor,
540                Some(&client),
541                None,
542            )
543            .unwrap();
544        engine
545            .relate_entity(
546                RelateEntityArgs {
547                    source: source.id.clone(),
548                    expected_hash: Some(source.content_hash.clone()),
549                    rel_type: "USES".to_string(),
550                    target: stub_id.clone(),
551                    remove: false,
552                    description: None,
553                    dry_run: false,
554                },
555                actor,
556                Some(&client),
557                None,
558            )
559            .unwrap();
560        assert!(
561            engine.store().contains(&stub_id),
562            "forward-reference relate must materialise stub"
563        );
564
565        // Stub delete with a non-empty (bogus) expected_hash —
566        // pre-fix the message read `current is ` with an empty trailing
567        // value; now `is_stub: true` and the message names the fix.
568        let err = engine
569            .delete_entity(
570                DeleteEntityArgs {
571                    id: stub_id.clone(),
572                    expected_hash: Some("definitely-non-empty".to_string()),
573                },
574                actor,
575                Some(&client),
576                None,
577            )
578            .unwrap_err();
579        match err {
580            EngineError::HashMismatch {
581                id,
582                current,
583                is_stub,
584            } => {
585                assert_eq!(id, stub_id.to_string());
586                assert!(current.is_empty(), "stub has no content hash");
587                assert!(is_stub, "is_stub must be true on a stub mismatch");
588                let msg = format!(
589                    "{}",
590                    EngineError::HashMismatch {
591                        id,
592                        current,
593                        is_stub
594                    }
595                );
596                assert!(
597                    msg.contains("stub") && msg.contains("expected_hash: \"\""),
598                    "stub message must name the corrective action; got: {msg}",
599                );
600            }
601            other => panic!("expected HashMismatch, got {other:?}"),
602        }
603    }
604
605    /// `memstead_delete id=<stub> expected_hash=""` end-to-end. The pre-fix
606    /// path tripped `BackendError::Path("mem-relative
607    /// path is empty"))` because stubs carry an empty `file_path` and
608    /// the backend's `delete_entity` rejected the empty path. The fix
609    /// routes stub deletes around the backend write — stubs are
610    /// in-memory + edge-index only, never committed as their own grain.
611    #[test]
612    fn delete_entity_on_stub_with_empty_hash_succeeds_via_in_memory_route() {
613        let tmp = TempDir::new().unwrap();
614        let (mut engine, _anchor) = engine_with_seed(&tmp, "Anchor");
615        let (actor, client) = cli_actor();
616
617        // Inject an orphan stub (zero incoming edges) directly into the
618        // store. Organic mutation paths can no longer leave one — the
619        // relate-remove, delete, and update-via-alias-resync sweeps all
620        // GC orphans the moment a stub's last referrer drops — so a
621        // white-box insertion is the only way to set up the "delete a
622        // pre-existing orphan stub" case this test exercises (e.g. a
623        // legacy in-memory artifact).
624        let stub_id = crate::EntityId::new("specs", "ghost-target");
625        engine.store.upsert(
626            stub_id.clone(),
627            super::make_stub(&stub_id, crate::entity::StubKind::ForwardReference),
628        );
629        assert!(
630            engine.store().contains(&stub_id),
631            "injected orphan stub must be in store"
632        );
633
634        let outcome = engine
635            .delete_entity(
636                DeleteEntityArgs {
637                    id: stub_id.clone(),
638                    expected_hash: Some(String::new()),
639                },
640                actor,
641                Some(&client),
642                None,
643            )
644            .expect("stub delete with expected_hash=\"\" must succeed");
645
646        assert_eq!(outcome.id, stub_id);
647        // Backend write was skipped — no commit grain for a stub.
648        assert!(
649            outcome.write_id.is_empty(),
650            "stub deletes skip the backend write; write_id is empty"
651        );
652        // In-memory store no longer carries the stub.
653        assert!(
654            !engine.store().contains(&stub_id),
655            "stub must be gone from the in-memory store"
656        );
657        // Subsequent lookups behave like a normal not-found.
658        assert!(engine.get_entity(&stub_id).is_none());
659        // Provenance log records the delete (the changes feed must see
660        // explicit stub drops just like real deletes).
661        let log = std::fs::read_to_string(tmp.path().join(".memstead/changes.jsonl")).unwrap();
662        assert!(log.contains("\"kind\":\"delete\""));
663    }
664
665    #[test]
666    fn delete_entity_refuses_on_write_mem_referrers_with_typed_payload() {
667        let tmp = TempDir::new().unwrap();
668        let (mut engine, target) = engine_with_seed(&tmp, "Target");
669        let (actor, client) = cli_actor();
670        // Create a second entity that points at `target`.
671        let source = engine
672            .create_entity(
673                empty_create_args("specs", "Source"),
674                actor,
675                Some(&client),
676                None,
677            )
678            .unwrap();
679        engine
680            .relate_entity(
681                RelateEntityArgs {
682                    source: source.id.clone(),
683                    expected_hash: Some(source.content_hash.clone()),
684                    rel_type: "USES".to_string(),
685                    target: target.id.clone(),
686                    remove: false,
687                    description: None,
688                    dry_run: false,
689                },
690                actor,
691                Some(&client),
692                None,
693            )
694            .unwrap();
695
696        // Delete refuses — the engine has no force flag; the agent
697        // removes the offending references first.
698        let err = engine
699            .delete_entity(
700                DeleteEntityArgs {
701                    id: target.id.clone(),
702                    expected_hash: None,
703                },
704                actor,
705                Some(&client),
706                None,
707            )
708            .unwrap_err();
709        match err {
710            EngineError::HasIncomingRefs { id, referrers } => {
711                assert_eq!(id, target.id.to_string());
712                assert_eq!(referrers.len(), 1);
713                let r = &referrers[0];
714                assert_eq!(r.from_id, source.id.to_string());
715                assert_eq!(r.rel_types, vec!["USES".to_string()]);
716                assert_eq!(r.mem, "specs");
717            }
718            other => panic!("expected HasIncomingRefs, got {other:?}"),
719        }
720
721        // The entity is still in the store and the file still on disk —
722        // no partial state from a refused delete.
723        assert!(engine.get_entity(&target.id).is_some());
724        assert!(tmp.path().join(&target.file_path).exists());
725    }
726
727    #[test]
728    fn delete_entity_returns_write_id_and_relations_removed() {
729        let tmp = TempDir::new().unwrap();
730        let (mut engine, target) = engine_with_seed(&tmp, "Target");
731        let (actor, client) = cli_actor();
732
733        // Build a small graph: source --USES--> target. Delete `source`
734        // (no incoming refs on it) and observe relations_removed
735        // counts the one outgoing edge.
736        let source = engine
737            .create_entity(
738                empty_create_args("specs", "Source"),
739                actor,
740                Some(&client),
741                None,
742            )
743            .unwrap();
744        let related = engine
745            .relate_entity(
746                RelateEntityArgs {
747                    source: source.id.clone(),
748                    expected_hash: Some(source.content_hash.clone()),
749                    rel_type: "USES".to_string(),
750                    target: target.id.clone(),
751                    remove: false,
752                    description: None,
753                    dry_run: false,
754                },
755                actor,
756                Some(&client),
757                None,
758            )
759            .unwrap();
760
761        let outcome = engine
762            .delete_entity(
763                DeleteEntityArgs {
764                    id: source.id.clone(),
765                    expected_hash: Some(related.content_hash.clone()),
766                },
767                actor,
768                Some(&client),
769                None,
770            )
771            .unwrap();
772
773        // Real write — folder backend produces a synthetic CommitId.
774        assert!(
775            !outcome.write_id.is_empty(),
776            "write_id must be populated on a real delete"
777        );
778        // Zero incoming + one outgoing edge removed.
779        assert_eq!(outcome.relations_removed, 1);
780        // No stubs in this graph; orphan_stubs_removed is empty.
781        assert!(outcome.orphan_stubs_removed.is_empty());
782        // No residual-stub warning — pure clean removal.
783        assert!(outcome.warnings.is_empty());
784    }
785
786    #[test]
787    fn delete_entity_garbage_collects_orphaned_stubs() {
788        let tmp = TempDir::new().unwrap();
789        let (mut engine, source) = engine_with_seed(&tmp, "Source");
790        let (actor, client) = cli_actor();
791        let stub_id = crate::EntityId::new("specs", "ghost-stub");
792
793        // Relate source → stub_id; engine creates the stub since the
794        // target was absent.
795        let related = engine
796            .relate_entity(
797                RelateEntityArgs {
798                    source: source.id.clone(),
799                    expected_hash: Some(source.content_hash.clone()),
800                    rel_type: "USES".to_string(),
801                    target: stub_id.clone(),
802                    remove: false,
803                    description: None,
804                    dry_run: false,
805                },
806                actor,
807                Some(&client),
808                None,
809            )
810            .unwrap();
811        assert!(engine.store().contains(&stub_id), "stub must be in store");
812
813        // Delete `source` — its outgoing edge to `stub_id` was the
814        // stub's only incoming edge, so the GC sweep drops the stub.
815        let outcome = engine
816            .delete_entity(
817                DeleteEntityArgs {
818                    id: source.id.clone(),
819                    expected_hash: Some(related.content_hash.clone()),
820                },
821                actor,
822                Some(&client),
823                None,
824            )
825            .unwrap();
826
827        assert_eq!(outcome.orphan_stubs_removed, vec![stub_id.clone()]);
828        assert!(
829            !engine.store().contains(&stub_id),
830            "GC must drop the orphaned stub"
831        );
832    }
833
834    /// ReadOnly-only referrer path: the entity has no Write-Mem
835    /// referrers but is referenced from a ReadOnly archive. Delete
836    /// removes the file and demotes the entity in-memory to a stub at
837    /// the same id, preserving the incoming edges from the archive
838    /// and surfacing a `RESIDUAL_STUB_FOR_READONLY_REFERRERS` warning.
839    /// The post-mutation in-memory state matches what a fresh boot
840    /// would produce: the parser would re-emit a stub at this id from
841    /// the surviving wiki-link in the archive's markdown.
842    #[test]
843    fn delete_entity_demotes_to_stub_when_only_readonly_referrers_remain() {
844        use crate::engine::test_helpers::{archive_mount, build_archive};
845        use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
846
847        let tmp = TempDir::new().unwrap();
848        let writable_dir = tmp.path().join("writable");
849        std::fs::create_dir_all(&writable_dir).unwrap();
850        let writer = FilesystemBackend::new(writable_dir.clone());
851
852        // Build an archive that declares an explicit cross-mem
853        // relation into the writable mem. Under the alias model
854        // edges originate from `## Relationships` only — the body
855        // wiki-link aliases the declared relation.
856        let archive_md = "---\ntype: spec\ncreated_date: 2026-01-15\nlast_modified: 2026-04-12\nlevel: M0\n---\n# Archived Source\n\n## Identity\n\nLinks to [[specs:target]].\n\n## Purpose\n\nFixture for residual-stub demotion.\n\n## Relationships\n\n- **REFERENCES**: [[specs:target]]\n";
857        let archive_path = build_archive(
858            tmp.path(),
859            "archive",
860            &[("archived-source.md", archive_md.as_bytes())],
861        );
862
863        let folder_mount = Mount {
864            mem: "specs".to_string(),
865            schema: Some(crate::engine::test_helpers::pin("default")),
866            storage: MountStorage::Folder {
867                path: writable_dir.clone(),
868            },
869            capability: MountCapability::Write,
870            lifecycle: MountLifecycle::Eager,
871            cross_linkable: true,
872            migration_target: None,
873        };
874        let archive_reader = crate::storage::ArchiveBackend::new(archive_path.clone());
875        let mut engine = Engine::from_mounts(vec![
876            (folder_mount, Box::new(writer) as Box<dyn MemBackend>),
877            (
878                archive_mount("archive", archive_path.clone()),
879                Box::new(archive_reader) as Box<dyn MemBackend>,
880            ),
881        ])
882        .unwrap();
883
884        let (actor, client) = cli_actor();
885        let target = engine
886            .create_entity(
887                empty_create_args("specs", "Target"),
888                actor,
889                Some(&client),
890                None,
891            )
892            .unwrap();
893
894        // Sanity: the archive's wiki-link surfaces as an incoming
895        // edge on `specs--target`.
896        let archived_source_id = crate::EntityId::new("archive", "archived-source");
897        assert!(
898            engine.store().contains(&archived_source_id),
899            "archive entity must load into the store"
900        );
901        let incoming_pre: Vec<_> = engine
902            .store()
903            .incoming(&target.id)
904            .iter()
905            .map(|e| e.from.clone())
906            .collect();
907        assert!(
908            incoming_pre.contains(&archived_source_id),
909            "archive wiki-link must produce an incoming edge on target; got {incoming_pre:?}"
910        );
911
912        // Delete: only-ReadOnly referrer → file removed, entity
913        // demoted to a stub, warning surfaces, incoming edge survives.
914        let outcome = engine
915            .delete_entity(
916                DeleteEntityArgs {
917                    id: target.id.clone(),
918                    expected_hash: Some(target.content_hash.clone()),
919                },
920                actor,
921                Some(&client),
922                None,
923            )
924            .unwrap();
925
926        // File is gone from the writable mem.
927        assert!(!writable_dir.join(&target.file_path).exists());
928        // Entity in the store is now a stub at the same id.
929        let demoted = engine
930            .get_entity(&target.id)
931            .expect("residual stub must remain in store");
932        assert!(demoted.stub, "demoted entity must be flagged as stub");
933        assert!(demoted.entity_type.is_empty());
934        // Typed provenance: the residual stub records its origin so
935        // an agent reading via `memstead_entity` later sees the diagnostic
936        // context the mutation-time warning carried.
937        match &demoted.stub_kind {
938            Some(crate::entity::StubKind::Residual {
939                since_commit: _,
940                readonly_referrers,
941            }) => {
942                assert_eq!(
943                    readonly_referrers,
944                    &vec![archived_source_id.clone()],
945                    "Residual.readonly_referrers must snapshot the surviving referrers at mutation time"
946                );
947            }
948            other => panic!("demoted stub must be tagged Residual; got {other:?}"),
949        }
950        // Incoming edge from archive survives.
951        let incoming_post: Vec<_> = engine
952            .store()
953            .incoming(&target.id)
954            .iter()
955            .map(|e| e.from.clone())
956            .collect();
957        assert!(
958            incoming_post.contains(&archived_source_id),
959            "archive incoming edge must survive demotion"
960        );
961        // Warning carries the surviving referrer.
962        let referrers = outcome
963            .warnings
964            .iter()
965            .find_map(|w| match w {
966                WarningHint::ResidualStubForReadOnlyReferrers { referrers, .. } => {
967                    Some(referrers.clone())
968                }
969                _ => None,
970            })
971            .expect("ResidualStubForReadOnlyReferrers warning must surface");
972        assert_eq!(referrers, vec![archived_source_id]);
973        assert_eq!(outcome.removed_incoming.len(), 1);
974    }
975
976    // ---- Engine::relate_entity --------------------------------------
977}