1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! Compose phase of a create: synthesise the entity the generator
//! renders (inline relations, alias-synthesised relations from body
//! wiki-links), enforce the alias-existence invariant, render the
//! markdown, and judge the composed state — auto-stubbed link targets,
//! declared section formats, required outgoing edges, declared
//! constraints. A dry-run completes here; a real write leaves as the
//! staged material the commit phase lands.
use std::collections::HashMap;
use crate::entity::{Entity, EntityId, Relationship, normalise_description};
use crate::ops::WarningHint;
use super::validate::ValidatedCreate;
use super::{CreatePrepareOutcome, Engine, EngineError, PreparedCreate};
impl Engine {
/// Synthesise, render and judge the composed entity; return the
/// dry-run outcome or the prepared write.
pub(super) fn compose_create(
&self,
validated: ValidatedCreate,
) -> Result<CreatePrepareOutcome, EngineError> {
let ValidatedCreate {
args,
mount_idx,
type_def,
id,
file_path,
metadata,
anchors: validated_anchors,
mut warnings,
type_guidance,
} = validated;
// 7. Synthesise the in-memory entity for the generator. The
// `content_hash` and `heading_spans` are derived; left
// blank because we re-parse the generated bytes below.
// Inline relations land in `relationships` so the
// generator emits them and the post-parse re-ingest
// rebuilds the edges in the store.
let relationships: Vec<Relationship> = args
.relations
.iter()
.map(|r| Relationship {
rel_type: r.rel_type.clone(),
target: r.target.clone(),
description: normalise_description(r.description.as_deref()),
})
.collect();
// Pre-compute the `relations_declared` outcome echo. Read
// `target_was_stubbed` against the pre-mutation store state
// (the post-parse `push_entities_into_store` step will
// auto-stub absent targets). Shape matches
// `memstead_update.relations_declared` so callers see a uniform
// wire shape across the two tools.
let relations_declared: Vec<crate::engine::outcomes::RelationDeclared> = args
.relations
.iter()
.map(|r| crate::engine::outcomes::RelationDeclared {
rel_type: r.rel_type.clone(),
target: r.target.clone(),
target_was_stubbed: !self.store.contains(&r.target),
})
.collect();
let mut entity_for_render = Entity {
id: id.clone(),
title: args.title.clone(),
entity_type: args.entity_type.clone(),
mem: args.mem.clone(),
file_path: file_path.clone(),
metadata,
sections: args.sections,
relationships,
content_hash: String::new(),
stub: false,
stub_kind: None,
heading_spans: HashMap::new(),
raw_section_headings: Vec::new(),
};
// Alias-synthesis pass: for schemas declaring
// `alias_target_rel_type`, append engine-emitted relations of
// that rel-type for every body wiki-link not already backed.
// Cross-mem refusal aborts the create — no partial state.
// Schemas without the pointer fall through unchanged and the
// validator below catches the missing relations.
//
// The returned `Vec<Relationship>` is the per-call set of
// relations the pass just emitted (in body iteration order).
// It feeds the `InlineWikiLinkAutoStubbed` emission below —
// using the post-mutation `entity.relationships` as the source
// via `parse_markdown` filters out the body-link targets
// because the parser-side `relationships`-coverage filter has
// already absorbed them.
let empty_prev_targets = std::collections::HashSet::new();
let alias_outcome = super::super::synthesise_alias_relations(
self,
&empty_prev_targets,
&mut entity_for_render,
)?;
let synthesised_relations = alias_outcome.emitted;
if alias_outcome.self_link_ignored {
warnings.push(WarningHint::SelfLinkIgnored { id: id.clone() });
}
let undeclared_targets: std::collections::HashSet<crate::entity::EntityId> = alias_outcome
.undeclared_dropped
.iter()
.map(|d| d.target.clone())
.collect();
for dropped in alias_outcome.undeclared_dropped {
warnings.push(WarningHint::CrossSchemaLinkUndeclared {
from: id.clone(),
target: dropped.target,
source_schema: dropped.source_schema,
target_schema: dropped.target_schema,
});
}
// Alias-existence invariant: every body wiki-link must be
// backed by an entry in `entity.relationships` (the auto-managed
// `## Relationships` section). Runs unconditionally on every
// Write-Mem create. See [`scan_wikilinks_without_relation`].
let missing =
super::super::scan_wikilinks_without_relation(&entity_for_render, &undeclared_targets)?;
if !missing.is_empty() {
return Err(EngineError::WikiLinkWithoutRelation {
from_id: id.to_string(),
missing: missing
.into_iter()
.map(|(section_key, target)| crate::engine::MissingWikiLink {
section_key,
target_id: target.to_string(),
})
.collect(),
});
}
let markdown = super::super::render_for_write(&entity_for_render, type_def.as_ref())?;
// 7a. Inline `[[wiki-link]]` patterns in section bodies that
// point at non-existent targets get auto-stubbed by the
// loader on re-ingest. Surface the would-be stubs as a
// warning so prose-induced ghosts are reviewable. Mirrors
// `memstead_relate`'s `AUTO_STUB_CREATED` observation
// discipline.
//
// The input set is the relations the alias-synthesis pass
// emitted on this call — NOT a re-parse of the generated
// markdown. `parse_markdown` filters its `inline_links`
// against the entity's `relationships` vec (which the
// synthesis pass has already appended to), so the
// pre-fix path saw `inline_links: []` and never fired
// the warning. The synthesised vec is the authoritative
// per-call source.
let auto_stubbed: Vec<EntityId> = synthesised_relations
.iter()
.filter_map(|rel| {
if !self.store.contains(&rel.target) {
Some(rel.target.clone())
} else {
None
}
})
.collect();
if !auto_stubbed.is_empty() {
warnings.push(WarningHint::InlineWikiLinkAutoStubbed {
from: id.clone(),
stubs: auto_stubbed,
});
}
// 7a-bis. Required-outgoing evaluation — the warning the tool
// descriptions have promised all along. Runs now that every
// edge this create carries (declared + alias-synthesised) is
// known, through the same evaluation the health sweep uses
// (one implementation; the two surfaces cannot disagree). A
// warning, never a refusal: entities are legitimately built up
// over several calls.
// Section-format evaluation (plan 08): each written section
// body against its declared markdown shape, judged by the
// real CommonMark reduction. Block-tier refuses with the
// first violation, pre-commit; warn-tier surfaces via the
// health sweep, never at write time.
for def in &type_def.sections {
if def.format_severity != memstead_schema::ConstraintSeverity::Block {
continue;
}
// Absent-as-empty: the generator renders every declared
// section heading (empty body when omitted), so the
// format judges the state that actually lands on disk —
// an expression that does not admit the empty sequence
// makes its section effectively required (declare a `?`
// or `*` form to admit omission). Without this, an
// omitting create passes while health flags the same
// on-disk state — write path and health must agree.
let body = entity_for_render
.sections
.get(def.key.as_str())
.map(String::as_str)
.unwrap_or("");
if let Some(first) = crate::section_format::check_section_format(def, body)
.into_iter()
.next()
{
return Err(EngineError::SectionFormatRefused {
entity_type: entity_for_render.entity_type.clone(),
entity_id: id.to_string(),
violation: first,
});
}
}
let unsatisfied = crate::ops::health::unsatisfied_required_outgoing(
&entity_for_render,
type_def.as_ref(),
);
if !unsatisfied.is_empty() {
// A block declared `severity: block` promotes the warning
// to a refusal — evaluated here, before any disk or store
// effect, so a refused create leaves nothing behind.
let blocked: Vec<_> = unsatisfied
.iter()
.filter(|b| b.severity == memstead_schema::ConstraintSeverity::Block)
.cloned()
.collect();
if !blocked.is_empty() {
return Err(EngineError::RequiredOutgoingUnsatisfied {
entity_type: entity_for_render.entity_type.clone(),
entity_id: id.to_string(),
missing: blocked,
});
}
warnings.push(WarningHint::MissingRequiredOutgoing {
entity_type: entity_for_render.entity_type.clone(),
entity_id: id.clone(),
missing: unsatisfied,
});
}
// Declared-constraints evaluation (`requires_when`, …) — the
// same single evaluation the health `constraints` include
// runs. Block-tier violations refuse; warn-tier violations
// warn and the write proceeds.
let check_provider = self.check_standing_provider();
let violated = crate::ops::health::unsatisfied_constraints(
&self.store,
&entity_for_render,
type_def.as_ref(),
None,
Some(&check_provider),
);
if !violated.is_empty() {
let blocked: Vec<_> = violated
.iter()
.filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
.cloned()
.collect();
if !blocked.is_empty() {
return Err(EngineError::ConstraintUnsatisfied {
entity_type: entity_for_render.entity_type.clone(),
entity_id: id.to_string(),
violations: blocked,
});
}
warnings.push(WarningHint::ConstraintUnsatisfied {
entity_type: entity_for_render.entity_type.clone(),
entity_id: id.clone(),
violations: violated,
});
}
let prepared = PreparedCreate {
mount_idx,
id,
title: args.title,
mem: args.mem,
file_path,
markdown,
anchors: validated_anchors,
warnings,
type_guidance,
relations_declared,
relation_targets: args.relations.iter().map(|r| r.target.clone()).collect(),
type_def,
};
// 7b. Dry-run: compute prospective hash from the in-memory
// entity and return without touching disk, store, or
// edges. Mirrors full's `CreateArgs.dry_run` semantics —
// `content_hash` carries the prospective hash since
// there's no current to differentiate from. `write_id`
// is empty. Stub creation is also skipped (no
// in-memory side effects).
if args.dry_run {
// `created_date` from the in-memory entity (the
// metadata-construction loop already set the
// init_timestamp default to `today_iso`-equivalent).
let created_date = entity_for_render
.metadata
.get("created_date")
.map(|v| v.to_frontmatter_string())
.unwrap_or_default();
return Ok(CreatePrepareOutcome::Done(
self.create_dry_run_outcome(prepared, created_date),
));
}
Ok(CreatePrepareOutcome::Prepared(prepared))
}
}