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            id: source_id.clone(),
201            expected_hash: Some(expected_hash),
202            sections,
203            append_sections: IndexMap::new(),
204            patch_sections: IndexMap::new(),
205            metadata: IndexMap::new(),
206            metadata_unset: Vec::new(),
207            dry_run: false,
208            declare_relations: Vec::new(),
209            relations_unset: Vec::new(),
210        };
211        let outcome = self.update_entity(args, actor, client, note)?;
212        Ok(outcome.commit_sha)
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use tempfile::TempDir;
219
220    use crate::backend::MemBackend;
221    use crate::engine::Engine;
222    use crate::engine::test_helpers::{
223        archive_mount, build_archive, cli_actor, folder_mount, write_schema_files_with_default_type,
224    };
225    use crate::ops::{ParseRecoveryEntry, WarningHint};
226    use crate::storage::{ArchiveBackend, FilesystemMemWriter};
227    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
228
229    use memstead_schema::SchemaRef;
230
231    /// Two writable parse-time drops on the same source collapse to
232    /// one re-render. Both entries land on the response as
233    /// `removed`; the on-disk markdown no longer carries the bad
234    /// rows; `load_warnings` is empty after the call.
235    #[test]
236    fn apply_parse_recovery_clears_writable_drops_in_one_call() {
237        let tmp = TempDir::new().unwrap();
238        let mem_dir = tmp.path().to_path_buf();
239        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget body.\n";
240        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";
241        std::fs::write(mem_dir.join("target.md"), target).unwrap();
242        std::fs::write(mem_dir.join("source.md"), source).unwrap();
243
244        let writer = FilesystemMemWriter::new(mem_dir.clone());
245        let mut engine = Engine::from_mounts(vec![(
246            folder_mount("specs", mem_dir.clone()),
247            Box::new(writer) as Box<dyn MemBackend>,
248        )])
249        .unwrap();
250
251        let pre: Vec<_> = engine
252            .load_warnings()
253            .iter()
254            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
255            .collect();
256        assert_eq!(pre.len(), 2, "expected two parse-time drops, got {pre:?}");
257
258        let (actor, client) = cli_actor();
259        let report = engine
260            .apply_parse_recovery(actor, Some(&client), Some("recovery"))
261            .expect("recovery succeeds");
262
263        assert_eq!(report.entries.len(), 2);
264        for entry in &report.entries {
265            assert_eq!(
266                entry.outcome,
267                ParseRecoveryEntry::OUTCOME_REMOVED,
268                "expected both writable drops removed, got {entry:?}",
269            );
270            assert!(entry.reason.is_none());
271        }
272        assert!(!report.commit_sha.is_empty(), "recovery must commit");
273
274        let post: Vec<_> = engine
275            .load_warnings()
276            .iter()
277            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
278            .collect();
279        assert!(post.is_empty(), "drops must be cleared, got {post:?}");
280
281        let cleaned = std::fs::read_to_string(mem_dir.join("source.md")).unwrap();
282        assert!(
283            !cleaned.contains("MADE_UP_TYPE_A"),
284            "cleaned source: {cleaned}"
285        );
286        assert!(
287            !cleaned.contains("MADE_UP_TYPE_B"),
288            "cleaned source: {cleaned}"
289        );
290    }
291
292    /// Read-only-origin drops are reported as `skipped` with
293    /// `reason: "readonly_mount"`. The engine cannot rewrite an
294    /// archive, so the warning survives the call.
295    #[test]
296    fn apply_parse_recovery_skips_readonly_origin_drops() {
297        let tmp = TempDir::new().unwrap();
298        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget.\n";
299        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource.\n\n## Relationships\n\n- **MADE_UP**: [[external--target]]\n";
300        let archive_path = build_archive(
301            tmp.path(),
302            "ext",
303            &[
304                ("target.md", target.as_bytes()),
305                ("source.md", source.as_bytes()),
306            ],
307        );
308
309        let mut engine = Engine::from_mounts(vec![(
310            archive_mount("external", archive_path.clone()),
311            Box::new(ArchiveBackend::new(archive_path)),
312        )])
313        .unwrap();
314
315        let (actor, client) = cli_actor();
316        let report = engine
317            .apply_parse_recovery(actor, Some(&client), None)
318            .expect("recovery succeeds");
319
320        assert_eq!(report.entries.len(), 1);
321        let entry = &report.entries[0];
322        assert_eq!(entry.outcome, ParseRecoveryEntry::OUTCOME_SKIPPED);
323        assert_eq!(
324            entry.reason.as_deref(),
325            Some(ParseRecoveryEntry::REASON_READONLY_MOUNT),
326        );
327        assert!(
328            report.commit_sha.is_empty(),
329            "readonly path commits nothing"
330        );
331
332        let post: Vec<_> = engine
333            .load_warnings()
334            .iter()
335            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
336            .collect();
337        assert_eq!(post.len(), 1, "readonly drop must persist, got {post:?}");
338    }
339
340    /// Re-running on an already-clean workspace returns an empty
341    /// entries list and produces no commits.
342    #[test]
343    fn apply_parse_recovery_is_idempotent_after_clean_state() {
344        let tmp = TempDir::new().unwrap();
345        let mem_dir = tmp.path().to_path_buf();
346        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nTarget.\n";
347        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nSource.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
348        std::fs::write(mem_dir.join("target.md"), target).unwrap();
349        std::fs::write(mem_dir.join("source.md"), source).unwrap();
350
351        let writer = FilesystemMemWriter::new(mem_dir.clone());
352        let mut engine = Engine::from_mounts(vec![(
353            folder_mount("specs", mem_dir),
354            Box::new(writer) as Box<dyn MemBackend>,
355        )])
356        .unwrap();
357
358        let (actor, client) = cli_actor();
359        let first = engine
360            .apply_parse_recovery(actor, Some(&client), None)
361            .expect("first recovery succeeds");
362        assert_eq!(first.entries.len(), 1);
363        assert_eq!(
364            first.entries[0].outcome,
365            ParseRecoveryEntry::OUTCOME_REMOVED
366        );
367        assert!(!first.commit_sha.is_empty());
368
369        let second = engine
370            .apply_parse_recovery(actor, Some(&client), None)
371            .expect("second recovery succeeds");
372        assert!(
373            second.entries.is_empty(),
374            "second call must be no-op, got {:?}",
375            second.entries
376        );
377        assert!(second.commit_sha.is_empty());
378    }
379
380    /// Mixed writable + readonly drops land in a single report.
381    #[test]
382    fn apply_parse_recovery_reports_per_warning_across_origins() {
383        let tmp = TempDir::new().unwrap();
384
385        let writable_dir = tmp.path().join("writable");
386        std::fs::create_dir_all(&writable_dir).unwrap();
387        let w_target = "---\ntype: spec\n---\n# WT\n\n## Identity\n\nwt\n";
388        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";
389        std::fs::write(writable_dir.join("target.md"), w_target).unwrap();
390        std::fs::write(writable_dir.join("source.md"), w_source).unwrap();
391
392        let r_target = "---\ntype: spec\n---\n# RT\n\n## Identity\n\nrt\n";
393        let r_source = "---\ntype: spec\n---\n# RS\n\n## Identity\n\nrs\n\n## Relationships\n\n- **MADE_UP_RO**: [[external--target]]\n";
394        let archive_path = build_archive(
395            tmp.path(),
396            "ext",
397            &[
398                ("target.md", r_target.as_bytes()),
399                ("source.md", r_source.as_bytes()),
400            ],
401        );
402
403        let writer = FilesystemMemWriter::new(writable_dir.clone());
404        let mut engine = Engine::from_mounts(vec![
405            (
406                folder_mount("specs", writable_dir),
407                Box::new(writer) as Box<dyn MemBackend>,
408            ),
409            (
410                archive_mount("external", archive_path.clone()),
411                Box::new(ArchiveBackend::new(archive_path)),
412            ),
413        ])
414        .unwrap();
415
416        let (actor, client) = cli_actor();
417        let report = engine
418            .apply_parse_recovery(actor, Some(&client), None)
419            .expect("recovery succeeds");
420
421        assert_eq!(report.entries.len(), 3);
422        let removed: Vec<_> = report
423            .entries
424            .iter()
425            .filter(|e| e.outcome == ParseRecoveryEntry::OUTCOME_REMOVED)
426            .collect();
427        let skipped: Vec<_> = report
428            .entries
429            .iter()
430            .filter(|e| e.outcome == ParseRecoveryEntry::OUTCOME_SKIPPED)
431            .collect();
432        assert_eq!(removed.len(), 2);
433        assert_eq!(skipped.len(), 1);
434        assert_eq!(
435            skipped[0].reason.as_deref(),
436            Some(ParseRecoveryEntry::REASON_READONLY_MOUNT),
437        );
438        assert!(!report.commit_sha.is_empty());
439    }
440
441    /// A drop whose source still has an unresolved body wiki-link to
442    /// the dropped target lands as `failed` with
443    /// `WIKILINK_WITHOUT_RELATION`. The strict validator refuses to
444    /// leave a body wiki-link unbacked by any relation; the
445    /// operator's recovery is to also remove the body reference.
446    #[test]
447    fn apply_parse_recovery_reports_failed_for_unbacked_body_link() {
448        let tmp = TempDir::new().unwrap();
449        let schemas_dir = tmp.path().join("schemas");
450        std::fs::create_dir_all(&schemas_dir).unwrap();
451        let manifest = r#"name: link-test
452version: 0.1.0
453description: schema for wikilink-blocker test
454when_to_use: tests
455types:
456  - doc
457relationships:
458  mode: strict
459  definitions:
460    - name: MENTIONS
461      description: doc references doc
462      default_weight: 1.0
463    - name: _default
464      description: fallback
465      default_weight: 1.0
466community:
467  resolution: 1.0
468  seed: 42
469"#;
470        write_schema_files_with_default_type(&schemas_dir, "link-test", manifest, &["doc"]);
471
472        let mem_dir = tmp.path().join("mem");
473        std::fs::create_dir_all(&mem_dir).unwrap();
474        let target = "---\ntype: doc\n---\n# Target\n\n## Body\n\nbody\n";
475        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";
476        std::fs::write(mem_dir.join("target.md"), target).unwrap();
477        std::fs::write(mem_dir.join("source.md"), source).unwrap();
478
479        let writer = FilesystemMemWriter::new(mem_dir.clone());
480        let pin = SchemaRef::new("link-test", semver::Version::new(0, 1, 0));
481        let mount = Mount {
482            mem: "specs".to_string(),
483            schema: Some(pin),
484            storage: MountStorage::Folder {
485                path: mem_dir.clone(),
486            },
487            capability: MountCapability::Write,
488            lifecycle: MountLifecycle::Eager,
489            cross_linkable: true,
490            migration_target: None,
491        };
492        let mut engine = Engine::from_mounts_with_schemas_dir(
493            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
494            Some(&schemas_dir),
495        )
496        .unwrap();
497
498        let (actor, client) = cli_actor();
499        let report = engine
500            .apply_parse_recovery(actor, Some(&client), None)
501            .expect("recovery returns Ok even when entries fail");
502
503        assert_eq!(report.entries.len(), 1);
504        let entry = &report.entries[0];
505        assert_eq!(entry.outcome, ParseRecoveryEntry::OUTCOME_FAILED);
506        assert_eq!(
507            entry.reason.as_deref(),
508            Some("WIKILINK_WITHOUT_RELATION"),
509            "expected the strict validator's typed code, got {:?}",
510            entry.reason,
511        );
512        let unchanged = std::fs::read_to_string(mem_dir.join("source.md")).unwrap();
513        assert!(
514            unchanged.contains("BADTYPE"),
515            "source must be unchanged on failure"
516        );
517
518        let post: Vec<_> = engine
519            .load_warnings()
520            .iter()
521            .filter(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }))
522            .collect();
523        assert_eq!(post.len(), 1, "failed drop must persist, got {post:?}");
524    }
525}