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