Skip to main content

memstead_base/engine/mutation/
parse_recovery.rs

1//! `Engine::apply_parse_recovery` — bulk-fix path that consumes the
2//! `ParsedRelationRecovery` payload on every writable-origin
3//! `PARSED_RELATION_INVALID` warning and applies the recovery action
4//! in a single operator-initiated call.
5//!
6//! The recovery action `remove_explicit_relation` means: drop the
7//! parse-time-dropped row from the source entity's markdown. The
8//! drop is already reflected in the in-memory `entity.relationships`
9//! (the parse-time validator strips the bad row at boot / reload /
10//! attach), so re-rendering and re-writing the source entity is
11//! enough — the renderer emits `## Relationships` from
12//! `entity.relationships`, so the stale row disappears.
13//!
14//! Multiple drops from the same source entity collapse to one
15//! re-render: `entity.relationships` already excludes every dropped
16//! row, so a single re-write fixes them all. The report still lists
17//! one entry per warning so consumers see exactly which drops were
18//! recovered.
19
20use indexmap::IndexMap;
21
22use crate::entity::EntityId;
23use crate::ops::{ParseRecoveryEntry, ParseRecoveryReport, WarningHint};
24use crate::vcs::{Actor, ClientId};
25
26use super::super::{Engine, EngineError, UpdateEntityArgs};
27
28impl Engine {
29    /// Walk `load_warnings`, dispatch the `remove_explicit_relation`
30    /// recovery for every writable-origin `PARSED_RELATION_INVALID`,
31    /// and report each entry on the response. Read-only-origin
32    /// warnings cannot be acted on (the engine has no write access
33    /// to their source markdown) and surface as
34    /// `outcome: "skipped"` with `reason: "readonly_mount"`.
35    ///
36    /// Failure model: per-entry failures land on the response as
37    /// `outcome: "failed"` with the underlying engine error code in
38    /// `reason`. The bulk-fix continues past per-entry failures so a
39    /// single bad source doesn't strand the rest of the batch. Only
40    /// engine-level errors (reload failure, broken workspace state)
41    /// abort the call and propagate via `Err`.
42    ///
43    /// Idempotency: after the per-source re-renders land, the method
44    /// runs `reload_each_writable_mem` so subsequent calls to
45    /// `health` / `load_warnings` reflect the post-recovery state.
46    /// Re-running on an already-clean workspace returns an empty
47    /// `entries` list with no commits.
48    pub fn apply_parse_recovery(
49        &mut self,
50        actor: Actor,
51        client: Option<&ClientId>,
52        note: Option<&str>,
53    ) -> Result<ParseRecoveryReport, EngineError> {
54        // Snapshot every `PARSED_RELATION_INVALID` warning. We
55        // iterate the snapshot, not `self.load_warnings`, so the
56        // mid-loop `update_entity` calls (which do not touch
57        // `load_warnings`) can't introduce ordering surprises.
58        struct Drop {
59            entity_id: EntityId,
60            rel_type: String,
61            target: EntityId,
62            origin: String,
63        }
64        let drops: Vec<Drop> = self
65            .load_warnings()
66            .iter()
67            .filter_map(|w| match w {
68                WarningHint::ParsedRelationInvalid {
69                    entity_id,
70                    rel_type,
71                    target,
72                    origin,
73                    ..
74                } => Some(Drop {
75                    entity_id: entity_id.clone(),
76                    rel_type: rel_type.clone(),
77                    target: target.clone(),
78                    origin: origin.clone(),
79                }),
80                _ => None,
81            })
82            .collect();
83
84        // Group writable drops by source-entity id so each source is
85        // re-rendered at most once. Iteration over the IndexMap
86        // preserves the order the warnings appeared in.
87        let mut writable_by_source: IndexMap<EntityId, Vec<usize>> = IndexMap::new();
88        let mut readonly_indices: Vec<usize> = Vec::new();
89        for (idx, drop) in drops.iter().enumerate() {
90            if drop.origin == "writable" {
91                writable_by_source
92                    .entry(drop.entity_id.clone())
93                    .or_default()
94                    .push(idx);
95            } else {
96                readonly_indices.push(idx);
97            }
98        }
99
100        let mut entries: Vec<ParseRecoveryEntry> = Vec::with_capacity(drops.len());
101        // Per-drop result slot — populated as the per-source attempts
102        // land. Keyed by the snapshot index so the final `entries`
103        // vec preserves the warning order.
104        let mut result_per_drop: Vec<Option<(String, Option<String>)>> = vec![None; drops.len()];
105
106        for idx in &readonly_indices {
107            result_per_drop[*idx] = Some((
108                ParseRecoveryEntry::OUTCOME_SKIPPED.to_string(),
109                Some(ParseRecoveryEntry::REASON_READONLY_MOUNT.to_string()),
110            ));
111        }
112
113        let mut last_commit_sha = String::new();
114        for (source_id, drop_indices) in writable_by_source {
115            let outcome = self.rewrite_for_parse_recovery(&source_id, actor, client, note);
116            match outcome {
117                Ok(commit_sha) => {
118                    if !commit_sha.is_empty() {
119                        last_commit_sha = commit_sha;
120                    }
121                    for idx in drop_indices {
122                        result_per_drop[idx] =
123                            Some((ParseRecoveryEntry::OUTCOME_REMOVED.to_string(), None));
124                    }
125                }
126                Err(err) => {
127                    let code = err.code().to_string();
128                    for idx in drop_indices {
129                        result_per_drop[idx] = Some((
130                            ParseRecoveryEntry::OUTCOME_FAILED.to_string(),
131                            Some(code.clone()),
132                        ));
133                    }
134                }
135            }
136        }
137
138        // Materialise entries in the original warning order.
139        for (idx, drop) in drops.into_iter().enumerate() {
140            let (outcome, reason) = result_per_drop[idx]
141                .take()
142                .expect("every drop should have been classified");
143            entries.push(ParseRecoveryEntry {
144                entity_id: drop.entity_id,
145                rel_type: drop.rel_type,
146                target: drop.target,
147                outcome,
148                reason,
149            });
150        }
151
152        // Reload writable mems so `load_warnings` reflects the
153        // post-recovery state — drops that re-rendered cleanly drop
154        // out; drops that failed (or read-only ones that were always
155        // out of scope) survive.
156        if !entries.is_empty() {
157            self.reload_each_writable_mem()?;
158        }
159
160        Ok(ParseRecoveryReport {
161            entries,
162            commit_sha: last_commit_sha,
163        })
164    }
165
166    /// Re-render the source entity and write it back to disk. Calls
167    /// `update_entity` seeding the first section's current body as a
168    /// rewrite anchor — section content stays identical, but the
169    /// full re-render flushes the parse-time relation drops out of
170    /// the auto-managed `## Relationships` section. Returns the
171    /// resulting `commit_sha` on success.
172    ///
173    /// Section-anchor seeding (instead of an empty payload) keeps
174    /// this internal rewrite path on the public `update_entity`
175    /// surface — the agent-boundary `EMPTY_UPDATE` guard refuses
176    /// empty payloads, and re-using the same guard avoids splitting the engine's
177    /// validation surface for one internal caller. Picking the
178    /// first section is safe because real entities always carry at
179    /// least one schema-required section (a stub would have tripped
180    /// the `StubNotUpdatable` guard before reaching here).
181    fn rewrite_for_parse_recovery(
182        &mut self,
183        source_id: &EntityId,
184        actor: Actor,
185        client: Option<&ClientId>,
186        note: Option<&str>,
187    ) -> Result<String, EngineError> {
188        let entity = self
189            .store()
190            .get(source_id)
191            .ok_or_else(|| EngineError::NotFound {
192                id: source_id.to_string(),
193            })?;
194        let expected_hash = entity.content_hash.clone();
195        let mut sections: IndexMap<String, String> = IndexMap::new();
196        if let Some((key, body)) = entity.sections.iter().next() {
197            sections.insert(key.clone(), body.clone());
198        }
199        let args = UpdateEntityArgs {
200            anchors: Vec::new(),
201            id: source_id.clone(),
202            expected_hash: Some(expected_hash),
203            sections,
204            append_sections: IndexMap::new(),
205            patch_sections: IndexMap::new(),
206            metadata: IndexMap::new(),
207            metadata_unset: Vec::new(),
208            dry_run: false,
209            declare_relations: Vec::new(),
210            relations_unset: Vec::new(),
211        };
212        let outcome = self.update_entity(args, actor, client, note)?;
213        Ok(outcome.commit_sha)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use tempfile::TempDir;
220
221    use crate::backend::MemBackend;
222    use crate::engine::Engine;
223    use crate::engine::test_helpers::{
224        archive_mount, build_archive, cli_actor, folder_mount, write_schema_files_with_default_type,
225    };
226    use crate::ops::{ParseRecoveryEntry, WarningHint};
227    use crate::storage::{ArchiveBackend, FilesystemMemWriter};
228    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
229
230    use memstead_schema::SchemaRef;
231
232    /// Two writable parse-time drops on the same source collapse to
233    /// one re-render. Both entries land on the response as
234    /// `removed`; the on-disk markdown no longer carries the bad
235    /// rows; `load_warnings` is empty after the call.
236    #[test]
237    fn apply_parse_recovery_clears_writable_drops_in_one_call() {
238        let tmp = TempDir::new().unwrap();
239        let mem_dir = tmp.path().to_path_buf();
240        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget body.\n";
241        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource body.\n\n## Relationships\n\n- **MADE_UP_TYPE_A**: [[specs--target]]\n- **MADE_UP_TYPE_B**: [[specs--target]]\n";
242        std::fs::write(mem_dir.join("target.md"), target).unwrap();
243        std::fs::write(mem_dir.join("source.md"), source).unwrap();
244
245        let writer = FilesystemMemWriter::new(mem_dir.clone());
246        let mut engine = Engine::from_mounts(vec![(
247            folder_mount("specs", mem_dir.clone()),
248            Box::new(writer) as Box<dyn MemBackend>,
249        )])
250        .unwrap();
251
252        let pre: Vec<_> = engine
253            .load_warnings()
254            .iter()
255            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
256            .collect();
257        assert_eq!(pre.len(), 2, "expected two parse-time drops, got {pre:?}");
258
259        let (actor, client) = cli_actor();
260        let report = engine
261            .apply_parse_recovery(actor, Some(&client), Some("recovery"))
262            .expect("recovery succeeds");
263
264        assert_eq!(report.entries.len(), 2);
265        for entry in &report.entries {
266            assert_eq!(
267                entry.outcome,
268                ParseRecoveryEntry::OUTCOME_REMOVED,
269                "expected both writable drops removed, got {entry:?}",
270            );
271            assert!(entry.reason.is_none());
272        }
273        assert!(!report.commit_sha.is_empty(), "recovery must commit");
274
275        let post: Vec<_> = engine
276            .load_warnings()
277            .iter()
278            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
279            .collect();
280        assert!(post.is_empty(), "drops must be cleared, got {post:?}");
281
282        let cleaned = std::fs::read_to_string(mem_dir.join("source.md")).unwrap();
283        assert!(
284            !cleaned.contains("MADE_UP_TYPE_A"),
285            "cleaned source: {cleaned}"
286        );
287        assert!(
288            !cleaned.contains("MADE_UP_TYPE_B"),
289            "cleaned source: {cleaned}"
290        );
291    }
292
293    /// Recover leg (criterion 5): `apply_parse_recovery` re-renders the
294    /// source entity but leaves its anchors sidecar bit-intact — the
295    /// re-render is an anchorless update, which never stages the sidecar.
296    #[test]
297    fn apply_parse_recovery_leaves_anchors_bit_intact() {
298        let tmp = TempDir::new().unwrap();
299        let mem_dir = tmp.path().to_path_buf();
300        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget body.\n";
301        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource body.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
302        std::fs::write(mem_dir.join("target.md"), target).unwrap();
303        std::fs::write(mem_dir.join("source.md"), source).unwrap();
304
305        // Seed an anchors sidecar for the source entity directly on disk (the
306        // recovery path must not touch it).
307        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
308        let sidecar_path = mem_dir.join(".memstead").join("anchors.json");
309        let sidecar = br#"{"version":1,"entities":{"specs--source":[{"artifact":"src/lib.rs","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
310        std::fs::write(&sidecar_path, sidecar).unwrap();
311        let before = std::fs::read(&sidecar_path).unwrap();
312
313        let writer = FilesystemMemWriter::new(mem_dir.clone());
314        let mut engine = Engine::from_mounts(vec![(
315            folder_mount("specs", mem_dir.clone()),
316            Box::new(writer) as Box<dyn MemBackend>,
317        )])
318        .unwrap();
319
320        let (actor, client) = cli_actor();
321        let report = engine
322            .apply_parse_recovery(actor, Some(&client), Some("recovery"))
323            .expect("recovery succeeds");
324        assert_eq!(report.entries.len(), 1);
325        assert_eq!(
326            report.entries[0].outcome,
327            ParseRecoveryEntry::OUTCOME_REMOVED
328        );
329
330        // The sidecar file is byte-identical, and the anchor still resolves.
331        let after = std::fs::read(&sidecar_path).unwrap();
332        assert_eq!(before, after, "recovery must leave anchors bit-intact");
333        let anchors = engine.entity_anchors(&crate::EntityId::new("specs", "source"));
334        assert_eq!(anchors.len(), 1);
335        assert_eq!(anchors[0].artifact, "src/lib.rs");
336    }
337
338    /// Read-only-origin drops are reported as `skipped` with
339    /// `reason: "readonly_mount"`. The engine cannot rewrite an
340    /// archive, so the warning survives the call.
341    #[test]
342    fn apply_parse_recovery_skips_readonly_origin_drops() {
343        let tmp = TempDir::new().unwrap();
344        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget.\n";
345        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource.\n\n## Relationships\n\n- **MADE_UP**: [[external--target]]\n";
346        let archive_path = build_archive(
347            tmp.path(),
348            "ext",
349            &[
350                ("target.md", target.as_bytes()),
351                ("source.md", source.as_bytes()),
352            ],
353        );
354
355        let mut engine = Engine::from_mounts(vec![(
356            archive_mount("external", archive_path.clone()),
357            Box::new(ArchiveBackend::new(archive_path)),
358        )])
359        .unwrap();
360
361        let (actor, client) = cli_actor();
362        let report = engine
363            .apply_parse_recovery(actor, Some(&client), None)
364            .expect("recovery succeeds");
365
366        assert_eq!(report.entries.len(), 1);
367        let entry = &report.entries[0];
368        assert_eq!(entry.outcome, ParseRecoveryEntry::OUTCOME_SKIPPED);
369        assert_eq!(
370            entry.reason.as_deref(),
371            Some(ParseRecoveryEntry::REASON_READONLY_MOUNT),
372        );
373        assert!(
374            report.commit_sha.is_empty(),
375            "readonly path commits nothing"
376        );
377
378        let post: Vec<_> = engine
379            .load_warnings()
380            .iter()
381            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
382            .collect();
383        assert_eq!(post.len(), 1, "readonly drop must persist, got {post:?}");
384    }
385
386    /// Re-running on an already-clean workspace returns an empty
387    /// entries list and produces no commits.
388    #[test]
389    fn apply_parse_recovery_is_idempotent_after_clean_state() {
390        let tmp = TempDir::new().unwrap();
391        let mem_dir = tmp.path().to_path_buf();
392        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget.\n";
393        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
394        std::fs::write(mem_dir.join("target.md"), target).unwrap();
395        std::fs::write(mem_dir.join("source.md"), source).unwrap();
396
397        let writer = FilesystemMemWriter::new(mem_dir.clone());
398        let mut engine = Engine::from_mounts(vec![(
399            folder_mount("specs", mem_dir),
400            Box::new(writer) as Box<dyn MemBackend>,
401        )])
402        .unwrap();
403
404        let (actor, client) = cli_actor();
405        let first = engine
406            .apply_parse_recovery(actor, Some(&client), None)
407            .expect("first recovery succeeds");
408        assert_eq!(first.entries.len(), 1);
409        assert_eq!(
410            first.entries[0].outcome,
411            ParseRecoveryEntry::OUTCOME_REMOVED
412        );
413        assert!(!first.commit_sha.is_empty());
414
415        let second = engine
416            .apply_parse_recovery(actor, Some(&client), None)
417            .expect("second recovery succeeds");
418        assert!(
419            second.entries.is_empty(),
420            "second call must be no-op, got {:?}",
421            second.entries
422        );
423        assert!(second.commit_sha.is_empty());
424    }
425
426    /// Mixed writable + readonly drops land in a single report.
427    #[test]
428    fn apply_parse_recovery_reports_per_warning_across_origins() {
429        let tmp = TempDir::new().unwrap();
430
431        let writable_dir = tmp.path().join("writable");
432        std::fs::create_dir_all(&writable_dir).unwrap();
433        let w_target = "---\ntype: spec\n---\n# WT\n\n## Identity\n\nwt\n";
434        let w_source = "---\ntype: spec\n---\n# WS\n\n## Identity\n\nws\n\n## Relationships\n\n- **MADE_UP_A**: [[specs--target]]\n- **MADE_UP_B**: [[specs--target]]\n";
435        std::fs::write(writable_dir.join("target.md"), w_target).unwrap();
436        std::fs::write(writable_dir.join("source.md"), w_source).unwrap();
437
438        let r_target = "---\ntype: spec\n---\n# RT\n\n## Identity\n\nrt\n";
439        let r_source = "---\ntype: spec\n---\n# RS\n\n## Identity\n\nrs\n\n## Relationships\n\n- **MADE_UP_RO**: [[external--target]]\n";
440        let archive_path = build_archive(
441            tmp.path(),
442            "ext",
443            &[
444                ("target.md", r_target.as_bytes()),
445                ("source.md", r_source.as_bytes()),
446            ],
447        );
448
449        let writer = FilesystemMemWriter::new(writable_dir.clone());
450        let mut engine = Engine::from_mounts(vec![
451            (
452                folder_mount("specs", writable_dir),
453                Box::new(writer) as Box<dyn MemBackend>,
454            ),
455            (
456                archive_mount("external", archive_path.clone()),
457                Box::new(ArchiveBackend::new(archive_path)),
458            ),
459        ])
460        .unwrap();
461
462        let (actor, client) = cli_actor();
463        let report = engine
464            .apply_parse_recovery(actor, Some(&client), None)
465            .expect("recovery succeeds");
466
467        assert_eq!(report.entries.len(), 3);
468        let removed: Vec<_> = report
469            .entries
470            .iter()
471            .filter(|e| e.outcome == ParseRecoveryEntry::OUTCOME_REMOVED)
472            .collect();
473        let skipped: Vec<_> = report
474            .entries
475            .iter()
476            .filter(|e| e.outcome == ParseRecoveryEntry::OUTCOME_SKIPPED)
477            .collect();
478        assert_eq!(removed.len(), 2);
479        assert_eq!(skipped.len(), 1);
480        assert_eq!(
481            skipped[0].reason.as_deref(),
482            Some(ParseRecoveryEntry::REASON_READONLY_MOUNT),
483        );
484        assert!(!report.commit_sha.is_empty());
485    }
486
487    /// A drop whose source still has an unresolved body wiki-link to
488    /// the dropped target lands as `failed` with
489    /// `WIKILINK_WITHOUT_RELATION`. The strict validator refuses to
490    /// leave a body wiki-link unbacked by any relation; the
491    /// operator's recovery is to also remove the body reference.
492    #[test]
493    fn apply_parse_recovery_reports_failed_for_unbacked_body_link() {
494        let tmp = TempDir::new().unwrap();
495        let schemas_dir = tmp.path().join("schemas");
496        std::fs::create_dir_all(&schemas_dir).unwrap();
497        let manifest = r#"name: link-test
498version: 0.1.0
499description: schema for wikilink-blocker test
500when_to_use: tests
501types:
502  - doc
503relationships:
504  mode: strict
505  definitions:
506    - name: MENTIONS
507      description: doc references doc
508      default_weight: 1.0
509    - name: _default
510      description: fallback
511      default_weight: 1.0
512community:
513  resolution: 1.0
514  seed: 42
515"#;
516        write_schema_files_with_default_type(&schemas_dir, "link-test", manifest, &["doc"]);
517
518        let mem_dir = tmp.path().join("mem");
519        std::fs::create_dir_all(&mem_dir).unwrap();
520        let target = "---\ntype: doc\n---\n# Target\n\n## Body\n\nbody\n";
521        let source = "---\ntype: doc\n---\n# Source\n\n## Body\n\nrefer to [[specs--target]] here\n\n## Relationships\n\n- **BADTYPE**: [[specs--target]]\n";
522        std::fs::write(mem_dir.join("target.md"), target).unwrap();
523        std::fs::write(mem_dir.join("source.md"), source).unwrap();
524
525        let writer = FilesystemMemWriter::new(mem_dir.clone());
526        let pin = SchemaRef::new("link-test", semver::Version::new(0, 1, 0));
527        let mount = Mount {
528            mem: "specs".to_string(),
529            schema: Some(pin),
530            storage: MountStorage::Folder {
531                path: mem_dir.clone(),
532            },
533            capability: MountCapability::Write,
534            lifecycle: MountLifecycle::Eager,
535            cross_linkable: true,
536            migration_target: None,
537        };
538        let mut engine = Engine::from_mounts_with_schemas_dir(
539            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
540            Some(&schemas_dir),
541        )
542        .unwrap();
543
544        let (actor, client) = cli_actor();
545        let report = engine
546            .apply_parse_recovery(actor, Some(&client), None)
547            .expect("recovery returns Ok even when entries fail");
548
549        assert_eq!(report.entries.len(), 1);
550        let entry = &report.entries[0];
551        assert_eq!(entry.outcome, ParseRecoveryEntry::OUTCOME_FAILED);
552        assert_eq!(
553            entry.reason.as_deref(),
554            Some("WIKILINK_WITHOUT_RELATION"),
555            "expected the strict validator's typed code, got {:?}",
556            entry.reason,
557        );
558        let unchanged = std::fs::read_to_string(mem_dir.join("source.md")).unwrap();
559        assert!(
560            unchanged.contains("BADTYPE"),
561            "source must be unchanged on failure"
562        );
563
564        let post: Vec<_> = engine
565            .load_warnings()
566            .iter()
567            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
568            .collect();
569        assert_eq!(post.len(), 1, "failed drop must persist, got {post:?}");
570    }
571}