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