1use std::fs;
12use std::path::{Path, PathBuf};
13
14use memstead_schema::TypeDefinition;
15
16use super::Entity;
17use super::generator::generate_markdown;
18
19pub fn unterminated_fence(entity: &Entity) -> Option<String> {
23 entity.sections.iter().find_map(|(k, v)| {
24 crate::markdown::closing_fence_if_unterminated(v.trim()).map(|fence| {
25 WriteError::UnterminatedFence {
26 id: entity.id.to_string(),
27 section: k.clone(),
28 fence,
29 }
30 .to_string()
31 })
32 })
33}
34
35pub fn write_entity(
39 entity: &Entity,
40 mem_dir: &Path,
41 schema: &TypeDefinition,
42) -> Result<PathBuf, WriteError> {
43 if entity.file_path.is_empty() {
44 return Err(WriteError::NoFilePath(entity.id.to_string()));
45 }
46
47 let full_path = mem_dir.join(&entity.file_path);
48
49 let resolved = full_path
51 .canonicalize()
52 .unwrap_or_else(|_| full_path.clone());
53 let resolved_root = mem_dir
54 .canonicalize()
55 .unwrap_or_else(|_| mem_dir.to_path_buf());
56 if !resolved.starts_with(&resolved_root) && full_path != mem_dir.join(&entity.file_path) {
57 return Err(WriteError::PathTraversal(entity.file_path.clone()));
58 }
59
60 if let Some(parent) = full_path.parent() {
62 fs::create_dir_all(parent)?;
63 }
64
65 if let Some((section, fence)) = entity.sections.iter().find_map(|(k, v)| {
73 crate::markdown::closing_fence_if_unterminated(v.trim()).map(|f| (k.clone(), f))
74 }) {
75 return Err(WriteError::UnterminatedFence {
76 id: entity.id.to_string(),
77 section,
78 fence,
79 });
80 }
81
82 let content = generate_markdown(entity, schema);
84 fs::write(&full_path, content)?;
85
86 Ok(full_path)
87}
88
89#[derive(Debug, thiserror::Error)]
90pub enum WriteError {
91 #[error("io error: {0}")]
92 Io(#[from] std::io::Error),
93 #[error("path traversal detected: {0}")]
94 PathTraversal(String),
95 #[error("entity has no file_path: {0}")]
96 NoFilePath(String),
97 #[error(
102 "entity '{id}' section '{section}' ends inside an unterminated `{fence}` code fence — \
103 regenerating the file would bury the sections it absorbed. Repair it through the \
104 engine first: replace section '{section}' with a corrected body."
105 )]
106 UnterminatedFence {
107 id: String,
108 section: String,
109 fence: String,
110 },
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 use crate::entity::{EntityId, MetadataValue};
117 use indexmap::IndexMap;
118 use memstead_schema::{builtin_names, type_by_name};
119 use tempfile::TempDir;
120
121 fn make_test_entity(name: &str) -> Entity {
122 let mut metadata = IndexMap::new();
123 metadata.insert("level".to_string(), MetadataValue::String("M0".to_string()));
124 metadata.insert(
125 "created_date".to_string(),
126 MetadataValue::String("2026-01-15".to_string()),
127 );
128 metadata.insert(
129 "last_modified".to_string(),
130 MetadataValue::String("2026-04-12".to_string()),
131 );
132 metadata.insert(
133 "type".to_string(),
134 MetadataValue::String("spec".to_string()),
135 );
136
137 let mut sections = IndexMap::new();
138 sections.insert("identity".to_string(), "Test identity.".to_string());
139 sections.insert("purpose".to_string(), "Test purpose.".to_string());
140
141 Entity {
142 id: EntityId::new("specs", name),
143 title: name.to_string(),
144 entity_type: "spec".to_string(),
145 mem: "specs".to_string(),
146 file_path: format!("{name}.md"),
147 metadata,
148 sections,
149 relationships: Vec::new(),
150 content_hash: String::new(),
151 stub: false,
152 stub_kind: None,
153 heading_spans: std::collections::HashMap::new(),
154 raw_section_headings: Vec::new(),
155 }
156 }
157
158 fn make_concept_entity(name: &str) -> Entity {
159 let mut metadata = IndexMap::new();
160 metadata.insert(
161 "maturity".to_string(),
162 MetadataValue::String("emerging".to_string()),
163 );
164 metadata.insert(
165 "abstraction_level".to_string(),
166 MetadataValue::String("concrete".to_string()),
167 );
168 metadata.insert(
169 "created_date".to_string(),
170 MetadataValue::String("2026-01-15".to_string()),
171 );
172 metadata.insert(
173 "last_modified".to_string(),
174 MetadataValue::String("2026-04-12".to_string()),
175 );
176 metadata.insert(
177 "type".to_string(),
178 MetadataValue::String("concept".to_string()),
179 );
180
181 let mut sections = IndexMap::new();
182 sections.insert(
183 "definition".to_string(),
184 "A precise mental model of X.".to_string(),
185 );
186 sections.insert(
187 "explanation".to_string(),
188 "How X operates in practice.".to_string(),
189 );
190 sections.insert("boundaries".to_string(), "Not Y, not Z.".to_string());
191 sections.insert(
192 "significance".to_string(),
193 "Foundational for understanding W.".to_string(),
194 );
195
196 Entity {
197 id: EntityId::new("concepts", name),
198 title: name.to_string(),
199 entity_type: "concept".to_string(),
200 mem: "concepts".to_string(),
201 file_path: format!("{name}.md"),
202 metadata,
203 sections,
204 relationships: Vec::new(),
205 content_hash: String::new(),
206 stub: false,
207 stub_kind: None,
208 heading_spans: std::collections::HashMap::new(),
209 raw_section_headings: Vec::new(),
210 }
211 }
212
213 #[test]
214 fn write_entity_creates_file() {
215 let dir = TempDir::new().unwrap();
216 let schema = type_by_name(builtin_names::SPEC).unwrap();
217 let entity = make_test_entity("test-entity");
218
219 let path = write_entity(&entity, dir.path(), &schema).unwrap();
220 assert!(path.exists());
221
222 let content = fs::read_to_string(&path).unwrap();
223 assert!(content.contains("# test-entity"));
224 }
225
226 #[test]
227 fn write_entity_concept_uses_schema_headings_and_order() {
228 let dir = TempDir::new().unwrap();
229 let schema = type_by_name(builtin_names::CONCEPT).unwrap();
230 let entity = make_concept_entity("clarity");
231
232 let path = write_entity(&entity, dir.path(), &schema).unwrap();
233 let content = fs::read_to_string(&path).unwrap();
234
235 assert!(content.contains("## Definition"));
237 assert!(content.contains("## Explanation"));
238 assert!(content.contains("## Boundaries"));
239 assert!(content.contains("## Significance"));
240 assert!(!content.contains("## Identity"));
241 assert!(!content.contains("## Purpose"));
242
243 let def_pos = content.find("## Definition").unwrap();
246 let exp_pos = content.find("## Explanation").unwrap();
247 let bnd_pos = content.find("## Boundaries").unwrap();
248 let sig_pos = content.find("## Significance").unwrap();
249 assert!(def_pos < exp_pos);
250 assert!(exp_pos < bnd_pos);
251 assert!(bnd_pos < sig_pos);
252
253 assert!(content.contains("type: concept"));
255 assert!(content.contains("maturity: emerging"));
256 }
257
258 #[test]
259 fn write_entity_creates_parent_dirs() {
260 let dir = TempDir::new().unwrap();
261 let schema = type_by_name(builtin_names::SPEC).unwrap();
262 let mut entity = make_test_entity("child");
263 entity.file_path = "parent/child.md".to_string();
264
265 let path = write_entity(&entity, dir.path(), &schema).unwrap();
266 assert!(path.exists());
267 assert!(dir.path().join("parent").exists());
268 }
269
270 #[test]
276 fn an_open_fence_is_declined_rather_than_frozen_on_export() {
277 let tmp = TempDir::new().unwrap();
278 let mut entity = make_test_entity("fenced");
279 entity.sections.insert(
280 "identity".to_string(),
281 "intro\n\n```rust\nfn main() {}".to_string(),
282 );
283 let schema = type_by_name(builtin_names::SPEC).unwrap();
284 let err = write_entity(&entity, tmp.path(), schema.as_ref())
285 .expect_err("regenerating this file would bury the absorbed sections");
286 match err {
287 WriteError::UnterminatedFence {
288 ref section,
289 ref fence,
290 ..
291 } => {
292 assert_eq!(section, "identity");
293 assert_eq!(fence, "```");
294 }
295 other => panic!("expected UnterminatedFence, got {other:?}"),
296 }
297 assert!(!tmp.path().join(&entity.file_path).exists());
299 }
300}