1use std::collections::HashMap;
7use std::sync::{Arc, OnceLock};
8
9use memstead_schema::{
10 FieldType, Filterable, ManualAuthoring, PerEdgeDescription, RelationshipMode, Schema,
11 Serialization, TypeDefinition, all_types, type_by_name,
12};
13use serde::Serialize;
14
15use crate::chunking::estimate_tokens;
16use crate::graph::community::generate_auto_summary;
17use crate::ops::Direction;
18use crate::ops::{ExpansionInfo, Facets, ScoreBreakdown, SubsectionFacet, TermMatch};
19use crate::store::Store;
20use crate::{
21 ContextResult, Edge, Entity, InEdge, ListResult, LouvainOutput, SearchHit, SearchResult,
22};
23
24pub fn render_entity_markdown(entity: &Entity, sections_filter: Option<&[String]>) -> String {
36 render_entity_markdown_with_signals(entity, sections_filter, None, None)
37}
38
39pub fn render_entity_markdown_with_signals(
49 entity: &Entity,
50 sections_filter: Option<&[String]>,
51 signals: Option<&[crate::ops::signals::ComputedSignal]>,
52 labelling: Option<&crate::ops::labelling::LabellingView>,
53) -> String {
54 let body_text = render_entity_body(entity, sections_filter);
55
56 let mut lines = Vec::new();
58 lines.push("---".to_string());
59 lines.push(format!("_hash: {}", entity.content_hash));
60 if let Some(kind) = &entity.stub_kind {
66 match kind {
67 crate::entity::StubKind::ForwardReference => {
68 lines.push("_stub_kind: forward_reference".to_string());
69 }
70 crate::entity::StubKind::LoadTime => {
71 lines.push("_stub_kind: load_time".to_string());
72 }
73 crate::entity::StubKind::Residual {
74 since_commit,
75 readonly_referrers,
76 } => {
77 lines.push("_stub_kind: residual".to_string());
78 if !since_commit.is_empty() {
79 lines.push(format!("_stub_since_commit: {since_commit}"));
80 }
81 if !readonly_referrers.is_empty() {
82 let refs: Vec<String> =
83 readonly_referrers.iter().map(|r| r.to_string()).collect();
84 lines.push(format!("_stub_readonly_referrers: [{}]", refs.join(", ")));
85 }
86 }
87 }
88 }
89 if let Some(sigs) = signals
93 && !sigs.is_empty()
94 {
95 let headline: Vec<String> = sigs
96 .iter()
97 .map(|s| format!("{}: {} ({})", s.name, s.value, s.level_wire()))
98 .collect();
99 lines.push(format!("_signals: [{}]", headline.join(", ")));
100 }
101 if let Some(lab) = labelling {
104 lines.push(format!("_label: {}", lab.label.wire()));
105 }
106 if let Some((absorbing, _)) = entity.sections.iter().find_map(|(k, v)| {
112 crate::markdown::closing_fence_if_unterminated(v.trim()).map(|f| (k.clone(), f))
113 }) {
114 let unread: Vec<&str> = entity
115 .sections
116 .iter()
117 .filter(|(k, v)| **k != absorbing && v.trim().is_empty())
118 .map(|(k, _)| k.as_str())
119 .collect();
120 if !unread.is_empty() {
121 lines.push(format!(
122 "_unread_sections: [{}] NOT empty: an unterminated code fence in `{absorbing}` \
123 swallowed them, and their content is inside that section's body",
124 unread.join(", "),
125 ));
126 }
127 }
128 let tokens = estimate_tokens(&body_text);
129 lines.push(format!("_tokens: {tokens}"));
130
131 let is_filtered = sections_filter.is_some_and(|f| {
134 let all_keys: Vec<&String> = entity.sections.keys().collect();
135 f.len() < all_keys.len() || !all_keys.iter().all(|k| f.iter().any(|fk| fk == *k))
136 });
137 if is_filtered {
138 let full_body = render_entity_body(entity, None);
139 let full_tokens = estimate_tokens(&full_body);
140 lines.push(format!("_tokens_unfiltered_body: {full_tokens}"));
141 }
142
143 for (key, value) in &entity.metadata {
150 if key.starts_with('_')
151 || crate::runtime_validator::READ_ONLY_METADATA_KEYS.contains(&key.as_str())
152 {
153 continue;
154 }
155 lines.push(format!("{key}: {value}"));
156 }
157 lines.push("---".to_string());
158 lines.push(String::new());
159
160 lines.push(body_text);
161
162 if let Some(sigs) = signals
165 && !sigs.is_empty()
166 {
167 lines.push(String::new());
168 lines.push("## Signals".to_string());
169 lines.push(String::new());
170 for s in sigs {
171 if s.contributors.is_empty() {
172 lines.push(format!(
173 "- **{}**: {} ({})",
174 s.name,
175 s.value,
176 s.level_wire()
177 ));
178 } else {
179 let ids: Vec<String> = s.contributors.iter().map(|c| c.to_string()).collect();
180 lines.push(format!(
181 "- **{}**: {} ({}) — {}",
182 s.name,
183 s.value,
184 s.level_wire(),
185 ids.join(", ")
186 ));
187 }
188 }
189 }
190 if let Some(lab) = labelling {
195 lines.push(String::new());
196 lines.push("## Labelling".to_string());
197 lines.push(String::new());
198 lines.push(format!("- label: {}", lab.label.wire()));
199 if !lab.defeated_by.is_empty() {
200 lines.push(format!("- defeated_by: {}", lab.defeated_by.join(", ")));
201 }
202 if !lab.undecided_by.is_empty() {
203 lines.push(format!("- undecided_by: {}", lab.undecided_by.join(", ")));
204 }
205 if let Some(shape) = &lab.shape {
206 let share = match shape.terminal_share {
207 Some(s) => format!("{s:.2}"),
208 None => "null".to_string(),
209 };
210 lines.push(format!(
211 "- shape: depth {}, branching {:.2}, terminal_share {}, defeated_in_support {}, undecided_in_support {}",
212 shape.depth,
213 shape.branching,
214 share,
215 shape.defeated_in_support,
216 shape.undecided_in_support,
217 ));
218 }
219 }
220 lines.join("\n")
221}
222
223pub fn rendered_body_tokens(entity: &Entity, sections_filter: Option<&[String]>) -> usize {
230 estimate_tokens(&render_entity_body(entity, sections_filter))
231}
232
233fn render_entity_body(entity: &Entity, sections_filter: Option<&[String]>) -> String {
240 let mut body = Vec::new();
241
242 body.push(format!("# {}", entity.title));
243 body.push(String::new());
244
245 let type_def = lookup_builtin_type(&entity.entity_type);
253
254 for (key, content) in &entity.sections {
255 if let Some(filter) = sections_filter
256 && !filter.iter().any(|f| f == key)
257 {
258 continue;
259 }
260 let heading = section_heading_for(type_def.as_deref(), key);
261 body.push(format!("## {heading}"));
262 body.push(String::new());
263 body.push(content.trim().to_string());
264 body.push(String::new());
265 }
266
267 if !entity.relationships.is_empty()
268 && sections_filter.is_none_or(|f| f.iter().any(|s| s == "relationships"))
269 {
270 body.push("## Relationships".to_string());
271 body.push(String::new());
272 for rel in &entity.relationships {
273 match rel
277 .description
278 .as_deref()
279 .map(str::trim)
280 .filter(|s| !s.is_empty())
281 {
282 Some(text) => body.push(format!(
283 "- **{}**: [[{}]] \u{2014} {text}",
284 rel.rel_type, rel.target
285 )),
286 None => body.push(format!("- **{}**: [[{}]]", rel.rel_type, rel.target)),
287 }
288 }
289 body.push(String::new());
290 }
291
292 body.join("\n")
293}
294
295pub fn render_relations_markdown(
300 entity_id: &str,
301 outgoing: &[Edge],
302 incoming: &[InEdge],
303) -> String {
304 let mut lines = Vec::new();
305 lines.push(String::new());
306 lines.push("## Relations".to_string());
307 lines.push(String::new());
308
309 if outgoing.is_empty() && incoming.is_empty() {
310 lines.push(format!("(no relations for {entity_id})"));
311 lines.push(String::new());
312 return lines.join("\n");
313 }
314
315 if !outgoing.is_empty() {
316 lines.push("### Outgoing".to_string());
317 for e in outgoing {
318 lines.push(format!("- **{}** → [[{}]]", e.rel_type, e.target));
319 }
320 lines.push(String::new());
321 }
322
323 if !incoming.is_empty() {
324 lines.push("### Incoming".to_string());
325 for e in incoming {
326 lines.push(format!("- [[{}]] → **{}** → (this)", e.from, e.rel_type));
327 }
328 lines.push(String::new());
329 }
330
331 lines.join("\n")
332}
333
334pub fn render_relations_json(
337 entity_id: &str,
338 outgoing: &[Edge],
339 incoming: &[InEdge],
340) -> serde_json::Value {
341 let out: Vec<serde_json::Value> = outgoing
342 .iter()
343 .map(|e| {
344 serde_json::json!({
345 "rel_type": e.rel_type,
346 "target": e.target.to_string(),
347 "source": format!("{:?}", e.source).to_lowercase(),
348 })
349 })
350 .collect();
351
352 let inc: Vec<serde_json::Value> = incoming
353 .iter()
354 .map(|e| {
355 serde_json::json!({
356 "rel_type": e.rel_type,
357 "from": e.from.to_string(),
358 "source": format!("{:?}", e.source).to_lowercase(),
359 })
360 })
361 .collect();
362
363 serde_json::json!({
364 "entity": entity_id,
365 "outgoing": out,
366 "incoming": inc,
367 })
368}
369
370pub fn render_search_markdown(result: &SearchResult, offset: usize) -> String {
376 let mut lines = Vec::new();
377
378 lines.push("---".to_string());
379 lines.push(format!("_total: {}", result.total));
380 lines.push(format!("_returned: {}", result.returned));
381 lines.push(format!("_offset: {offset}"));
382 lines.push(format!("_total_tokens: {}", result.total_tokens));
383 lines.push("---".to_string());
384 lines.push(String::new());
385
386 if !result.warnings.is_empty() {
387 lines.push("## Filter warnings".to_string());
392 for w in &result.warnings {
393 lines.push(format!("- **{}**: {}", w.code(), w.message()));
394 }
395 lines.push(String::new());
396 }
397
398 if let Some(facets) = &result.facets
399 && let Some(block) = render_facets_block(facets)
400 {
401 lines.push(block);
402 }
403
404 for hit in &result.hits {
405 lines.push(format!(
406 "### {} — {} (_score: {:.1}, _tokens: {})",
407 hit.id, hit.title, hit.score, hit.tokens,
408 ));
409 lines.push(hit_summary_line(hit));
410 if let Some(line) = render_matched_terms_line(hit.matched_terms.as_ref()) {
411 lines.push(line);
412 }
413 if let Some(line) = render_score_breakdown_line(hit.score_breakdown.as_ref()) {
414 lines.push(line);
415 }
416 if let Some(line) = render_heading_paths_line(hit.matched_terms.as_ref()) {
417 lines.push(line);
418 }
419 if let Some(line) = render_expansion_line(hit.expansion.as_ref()) {
420 lines.push(line);
421 }
422 if let Some(snippet) = &hit.snippet {
423 lines.push(format!("> ...{snippet}..."));
424 }
425 lines.push(String::new());
426 }
427
428 lines.join("\n")
429}
430
431fn render_facets_block(facets: &Facets) -> Option<String> {
439 let blocks: Vec<(&str, String)> = [
440 ("by_type", &facets.by_type),
441 ("by_mem", &facets.by_mem),
442 ("by_level", &facets.by_level),
443 ("by_status", &facets.by_status),
444 ("by_confidence", &facets.by_confidence),
445 ("by_expansion", &facets.by_expansion),
446 ]
447 .into_iter()
448 .filter_map(|(name, bucket)| format_facet_bucket(bucket).map(|s| (name, s)))
449 .collect();
450
451 if blocks.is_empty() && facets.by_subsection.is_empty() {
452 return None;
453 }
454
455 let mut out = String::new();
456 out.push_str("## Facets\n");
457 for (name, body) in blocks {
458 out.push_str(&format!("- **{name}:** {body}\n"));
459 }
460 if !facets.by_subsection.is_empty() {
461 out.push_str("- **by_subsection:**\n");
462 for entry in &facets.by_subsection {
463 out.push_str(&format!(" - {}\n", format_subsection_facet(entry)));
464 }
465 }
466 Some(out)
467}
468
469fn format_facet_bucket(bucket: &HashMap<String, usize>) -> Option<String> {
470 if bucket.is_empty() {
471 return None;
472 }
473 let mut entries: Vec<(&String, &usize)> = bucket.iter().collect();
474 entries.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
475 Some(
476 entries
477 .iter()
478 .map(|(k, v)| format!("{k}={v}"))
479 .collect::<Vec<_>>()
480 .join(", "),
481 )
482}
483
484fn format_subsection_facet(entry: &SubsectionFacet) -> String {
485 let path = entry.path.join(" › ");
486 format!("`{path}`: {}", entry.count)
487}
488
489fn render_matched_terms_line(matched: Option<&HashMap<String, Vec<TermMatch>>>) -> Option<String> {
494 let matched = matched?;
495 if matched.is_empty() {
496 return None;
497 }
498 let mut terms: Vec<(&String, &Vec<TermMatch>)> = matched.iter().collect();
499 terms.sort_by(|a, b| a.0.cmp(b.0));
500 let groups: Vec<String> = terms
501 .iter()
502 .map(|(term, tms)| {
503 let mut field_counts: HashMap<&str, usize> = HashMap::new();
504 for tm in tms.iter() {
505 *field_counts.entry(tm.field.as_str()).or_insert(0) += 1;
506 }
507 let mut fields: Vec<(&&str, &usize)> = field_counts.iter().collect();
508 fields.sort_by(|a, b| a.0.cmp(b.0));
509 let inner: Vec<String> = fields.iter().map(|(f, n)| format!("{f}×{n}")).collect();
510 format!("`{term}` ({})", inner.join(", "))
511 })
512 .collect();
513 Some(format!("**Matched terms:** {}", groups.join(", ")))
514}
515
516fn render_score_breakdown_line(breakdown: Option<&ScoreBreakdown>) -> Option<String> {
521 let b = breakdown?;
522 let mut parts: Vec<String> = Vec::new();
523 parts.push(format!("bm25 {:.1}", b.bm25));
524 parts.push(format!("title {:.1}", b.title_boost));
525 let mut fields: Vec<(&String, &f32)> = b.field_weights.iter().collect();
526 fields.sort_by(|a, b| a.0.cmp(b.0));
527 for (k, v) in fields {
528 parts.push(format!("{k} {v:.1}"));
529 }
530 if let Some(decay) = b.expansion_decay {
531 parts.push(format!("expansion_decay ×{decay:.1}"));
532 }
533 Some(format!("**Score:** {}", parts.join(" + ")))
534}
535
536fn render_heading_paths_line(matched: Option<&HashMap<String, Vec<TermMatch>>>) -> Option<String> {
540 let matched = matched?;
541 let mut paths: Vec<Vec<String>> = Vec::new();
542 let mut term_keys: Vec<&String> = matched.keys().collect();
543 term_keys.sort();
544 for term in term_keys {
545 for tm in &matched[term] {
546 if let Some(path) = &tm.heading_path
547 && !path.is_empty()
548 && !paths.iter().any(|p| p == path)
549 {
550 paths.push(path.clone());
551 }
552 }
553 }
554 if paths.is_empty() {
555 return None;
556 }
557 let formatted: Vec<String> = paths.iter().map(|p| p.join(" › ")).collect();
558 Some(format!("**Heading path:** {}", formatted.join("; ")))
559}
560
561fn render_expansion_line(expansion: Option<&ExpansionInfo>) -> Option<String> {
565 let e = expansion?;
566 let dir = match e.via_direction {
567 crate::graph::query::TraversalDirection::Out => "out",
568 crate::graph::query::TraversalDirection::In => "in",
569 crate::graph::query::TraversalDirection::Both => "both",
572 };
573 Some(format!(
574 "**Expansion:** from `{}` via `{}` [{dir}] (depth {})",
575 e.of, e.via_edge, e.depth,
576 ))
577}
578
579pub fn render_list_markdown(result: &ListResult) -> String {
581 let mut lines = Vec::new();
582
583 lines.push("---".to_string());
584 lines.push(format!("_total: {}", result.total));
585 lines.push(format!("_returned: {}", result.returned));
586 lines.push(format!("_offset: {}", result.offset));
587 lines.push(format!("_total_tokens: {}", result.total_tokens));
588 lines.push("---".to_string());
589 lines.push(String::new());
590
591 if !result.warnings.is_empty() {
592 lines.push("## Filter warnings".to_string());
593 for w in &result.warnings {
594 lines.push(format!("- **{}**: {}", w.code(), w.message()));
595 }
596 lines.push(String::new());
597 }
598
599 for hit in &result.hits {
600 let meta = hit
601 .sections
602 .get("level")
603 .map(|l| format!("{l}, "))
604 .unwrap_or_default();
605 lines.push(format!(
606 "### {} — {} ({meta}_tokens: {})",
607 hit.id, hit.title, hit.tokens,
608 ));
609 lines.push(hit_summary_line(hit));
610 lines.push(String::new());
611 }
612
613 lines.join("\n")
614}
615
616pub fn render_community_context_section(result: &ContextResult, cluster_id: &str) -> String {
624 let mut lines = Vec::new();
625 lines.push(String::new());
626 lines.push("## Community Context".to_string());
627 lines.push(String::new());
628 lines.push(format!("**Cluster {cluster_id}**"));
629 lines.push(String::new());
630
631 if !result.neighbors.is_empty() {
632 lines.push("### Neighbors".to_string());
633 for n in &result.neighbors {
634 let dir = match n.direction {
635 Direction::Outgoing => "→",
636 Direction::Incoming => "←",
637 };
638 lines.push(format!(
639 "- {} —{}— **{}** ({})",
640 result.entity_id, dir, n.id, n.relationship,
641 ));
642 }
643 lines.push(String::new());
644 }
645
646 lines.join("\n")
647}
648
649pub fn render_context_markdown(result: &ContextResult, cluster_id: &str) -> String {
651 let mut lines = Vec::new();
652
653 lines.push("---".to_string());
654 lines.push(format!("_cluster_id: {cluster_id}"));
655 lines.push("---".to_string());
656 lines.push(String::new());
657 lines.push(format!("## Cluster {cluster_id}"));
658 lines.push(String::new());
659
660 lines.push("### Neighbors".to_string());
662 for n in &result.neighbors {
663 let dir = match n.direction {
664 Direction::Outgoing => "→",
665 Direction::Incoming => "←",
666 };
667 lines.push(format!(
668 "- {} —{}— **{}** ({})",
669 result.entity_id, dir, n.id, n.relationship,
670 ));
671 }
672 lines.push(String::new());
673
674 lines.join("\n")
675}
676
677pub fn render_overview_markdown(output: &LouvainOutput, store: &Store) -> String {
680 let mut lines = Vec::new();
681
682 let entity_count: usize = output.clusters.values().map(|c| c.entities.len()).sum();
683
684 lines.push("---".to_string());
685 lines.push(format!("_cluster_count: {}", output.count));
686 lines.push(format!("_entity_count: {entity_count}"));
687 let mod_str = if output.modularity == 0.0 {
689 "0".to_string()
690 } else {
691 format!("{:.4}", output.modularity)
692 };
693 lines.push(format!("_modularity: {mod_str}"));
694 lines.push("---".to_string());
695 lines.push(String::new());
696
697 let mut cluster_ids: Vec<&String> = output.clusters.keys().collect();
699 cluster_ids.sort();
700
701 for cluster_id in cluster_ids {
702 let info = &output.clusters[cluster_id];
703 let summary = generate_auto_summary(store, &info.entities);
704
705 lines.push(format!(
706 "## Cluster {cluster_id} ({} entities)",
707 info.entities.len(),
708 ));
709 if !summary.is_empty() {
710 lines.push(summary);
711 }
712 for entity_id in &info.entities {
713 lines.push(format!("- {entity_id}"));
714 }
715 lines.push(String::new());
716 }
717
718 lines.join("\n")
719}
720
721#[derive(Serialize)]
737pub struct SearchHitEnvelope<'a> {
738 #[serde(flatten)]
739 pub hit: &'a SearchHit,
740 pub summary_heading: String,
741 pub summary_value: String,
742 pub origin: &'static str,
747}
748
749#[derive(Serialize)]
759pub struct SearchResultEnvelope<'a> {
760 #[serde(rename = "_total")]
761 pub total: usize,
762 #[serde(rename = "_returned")]
763 pub returned: usize,
764 #[serde(rename = "_offset")]
765 pub offset: usize,
766 #[serde(rename = "_total_tokens")]
770 pub total_tokens: usize,
771 pub hits: Vec<SearchHitEnvelope<'a>>,
772 #[serde(skip_serializing_if = "Option::is_none")]
777 pub facets: Option<&'a Facets>,
778 pub warnings: &'a Vec<crate::ops::WarningHint>,
782}
783
784#[derive(Serialize)]
790pub struct ListResultEnvelope<'a> {
791 #[serde(rename = "_total")]
792 pub total: usize,
793 #[serde(rename = "_returned")]
794 pub returned: usize,
795 #[serde(rename = "_offset")]
796 pub offset: usize,
797 #[serde(rename = "_total_tokens")]
798 pub total_tokens: usize,
799 pub hits: Vec<SearchHitEnvelope<'a>>,
800 pub warnings: &'a Vec<crate::ops::WarningHint>,
803}
804
805#[allow(clippy::too_many_arguments)] pub fn build_entity_envelope(
840 entity: &Entity,
841 rendered_body_tokens: usize,
842 full_tokens: Option<usize>,
843 sections_filter: Option<&[String]>,
844 schema_anchor: Option<&str>,
845 origin: OriginClass,
846 outgoing_edges: &[crate::store::Edge],
847 incoming_edges: Option<&[crate::store::InEdge]>,
848 signals: Option<&[crate::ops::signals::ComputedSignal]>,
849 labelling: Option<&crate::ops::labelling::LabellingView>,
850) -> serde_json::Value {
851 let mut envelope = serde_json::Map::new();
852 if let Some(sigs) = signals
857 && !sigs.is_empty()
858 {
859 envelope.insert(
860 "_signals".to_string(),
861 crate::ops::signals::signals_json(sigs),
862 );
863 }
864 if let Some(lab) = labelling {
869 envelope.insert("_labelling".to_string(), lab.to_json());
870 }
871 envelope.insert(
872 "_hash".to_string(),
873 serde_json::Value::String(entity.content_hash.clone()),
874 );
875 envelope.insert(
882 "origin".to_string(),
883 serde_json::Value::String(origin.as_wire().to_string()),
884 );
885 if let Some((absorbing, fence)) = entity.sections.iter().find_map(|(k, v)| {
898 crate::markdown::closing_fence_if_unterminated(v.trim()).map(|f| (k.clone(), f))
899 }) {
900 let unread: Vec<String> = entity
901 .sections
902 .iter()
903 .filter(|(k, v)| **k != absorbing && v.trim().is_empty())
904 .map(|(k, _)| k.clone())
905 .collect();
906 envelope.insert(
907 "_unread_sections".to_string(),
908 serde_json::json!({
909 "reason": "UNTERMINATED_FENCE",
910 "absorbed_into": absorbing,
911 "fence": fence,
912 "sections": unread,
913 "note": "these sections read as empty because an unterminated code fence in \
914 `absorbed_into` swallowed them: their content is inside that section's \
915 body. Repair through the engine by replacing that section; a write that \
916 does not is refused.",
917 }),
918 );
919 }
920 envelope.insert(
921 "id".to_string(),
922 serde_json::Value::String(entity.id.to_string()),
923 );
924 envelope.insert(
925 "mem".to_string(),
926 serde_json::Value::String(entity.mem.clone()),
927 );
928 envelope.insert(
935 "entity_type".to_string(),
936 serde_json::Value::String(entity.entity_type.clone()),
937 );
938 envelope.insert(
943 "title".to_string(),
944 serde_json::Value::String(entity.title.clone()),
945 );
946
947 let mut metadata = serde_json::Map::new();
963 for (key, value) in &entity.metadata {
964 if key.starts_with('_')
965 || crate::runtime_validator::READ_ONLY_METADATA_KEYS.contains(&key.as_str())
966 {
967 continue;
968 }
969 metadata.insert(
970 key.clone(),
971 serde_json::Value::String(value.to_frontmatter_string()),
972 );
973 }
974 envelope.insert("metadata".to_string(), serde_json::Value::Object(metadata));
975
976 envelope.insert(
977 "_tokens".to_string(),
978 serde_json::Value::Number(serde_json::Number::from(rendered_body_tokens)),
979 );
980 if let Some(t) = full_tokens {
981 envelope.insert(
988 "_tokens_unfiltered_body".to_string(),
989 serde_json::Value::Number(serde_json::Number::from(t)),
990 );
991 }
992 if let Some(s) = schema_anchor {
993 envelope.insert(
994 "_mem_schema".to_string(),
995 serde_json::Value::String(s.to_string()),
996 );
997 }
998
999 if let Some(kind) = &entity.stub_kind {
1000 envelope.insert(
1001 "_stub_kind".to_string(),
1002 serde_json::to_value(kind).unwrap_or(serde_json::Value::Null),
1003 );
1004 }
1005
1006 let mut sections = serde_json::Map::new();
1007 for (key, content) in &entity.sections {
1008 if let Some(filter) = sections_filter
1009 && !filter.iter().any(|f| f == key)
1010 {
1011 continue;
1012 }
1013 sections.insert(key.clone(), serde_json::Value::String(content.clone()));
1014 }
1015 envelope.insert("sections".to_string(), serde_json::Value::Object(sections));
1016
1017 let resolve_source = |rel: &crate::entity::Relationship| -> &'static str {
1028 outgoing_edges
1029 .iter()
1030 .find(|e| e.rel_type == rel.rel_type && e.target == rel.target)
1031 .map(|e| match e.source {
1032 crate::store::EdgeSource::BodyLink => "body_link",
1033 crate::store::EdgeSource::Hierarchy => "hierarchy",
1034 crate::store::EdgeSource::Explicit => "explicit",
1035 })
1036 .unwrap_or("explicit")
1037 };
1038 let mut relationships: Vec<serde_json::Value> = entity
1046 .relationships
1047 .iter()
1048 .map(|rel| {
1049 let mut obj = serde_json::Map::new();
1050 obj.insert(
1051 "rel_type".to_string(),
1052 serde_json::Value::String(rel.rel_type.clone()),
1053 );
1054 obj.insert(
1055 "target".to_string(),
1056 serde_json::Value::String(rel.target.to_string()),
1057 );
1058 obj.insert(
1059 "direction".to_string(),
1060 serde_json::Value::String("out".to_string()),
1061 );
1062 obj.insert(
1063 "source".to_string(),
1064 serde_json::Value::String(resolve_source(rel).to_string()),
1065 );
1066 if let Some(desc) = rel
1067 .description
1068 .as_deref()
1069 .map(str::trim)
1070 .filter(|s| !s.is_empty())
1071 {
1072 obj.insert(
1073 "description".to_string(),
1074 serde_json::Value::String(desc.to_string()),
1075 );
1076 }
1077 serde_json::Value::Object(obj)
1078 })
1079 .collect();
1080 if let Some(incoming) = incoming_edges {
1081 for e in incoming {
1082 let mut obj = serde_json::Map::new();
1083 obj.insert(
1084 "rel_type".to_string(),
1085 serde_json::Value::String(e.rel_type.clone()),
1086 );
1087 obj.insert(
1088 "from".to_string(),
1089 serde_json::Value::String(e.from.to_string()),
1090 );
1091 obj.insert(
1092 "direction".to_string(),
1093 serde_json::Value::String("in".to_string()),
1094 );
1095 obj.insert(
1096 "source".to_string(),
1097 serde_json::Value::String(
1098 match e.source {
1099 crate::store::EdgeSource::BodyLink => "body_link",
1100 crate::store::EdgeSource::Hierarchy => "hierarchy",
1101 crate::store::EdgeSource::Explicit => "explicit",
1102 }
1103 .to_string(),
1104 ),
1105 );
1106 relationships.push(serde_json::Value::Object(obj));
1107 }
1108 }
1109 envelope.insert(
1110 "relationships".to_string(),
1111 serde_json::Value::Array(relationships),
1112 );
1113
1114 serde_json::Value::Object(envelope)
1115}
1116
1117pub fn build_search_envelope<'a>(
1122 result: &'a SearchResult,
1123 offset: usize,
1124 origin_of: &dyn Fn(&str) -> OriginClass,
1125) -> SearchResultEnvelope<'a> {
1126 SearchResultEnvelope {
1127 total: result.total,
1128 returned: result.returned,
1129 offset,
1130 total_tokens: result.total_tokens,
1131 hits: result
1132 .hits
1133 .iter()
1134 .map(|h| build_hit_envelope(h, origin_of))
1135 .collect(),
1136 facets: result.facets.as_ref(),
1137 warnings: &result.warnings,
1138 }
1139}
1140
1141pub fn build_list_envelope<'a>(
1144 result: &'a ListResult,
1145 origin_of: &dyn Fn(&str) -> OriginClass,
1146) -> ListResultEnvelope<'a> {
1147 ListResultEnvelope {
1148 total: result.total,
1149 returned: result.returned,
1150 offset: result.offset,
1151 total_tokens: result.total_tokens,
1152 hits: result
1153 .hits
1154 .iter()
1155 .map(|h| build_hit_envelope(h, origin_of))
1156 .collect(),
1157 warnings: &result.warnings,
1158 }
1159}
1160
1161fn build_hit_envelope<'a>(
1162 hit: &'a SearchHit,
1163 origin_of: &dyn Fn(&str) -> OriginClass,
1164) -> SearchHitEnvelope<'a> {
1165 let (heading, value) = hit_summary_pair(hit);
1166 SearchHitEnvelope {
1167 hit,
1168 summary_heading: heading,
1169 summary_value: value,
1170 origin: origin_of(&hit.mem).as_wire(),
1171 }
1172}
1173
1174fn hit_summary_line(hit: &SearchHit) -> String {
1184 let (heading, value) = hit_summary_pair(hit);
1185 format!("**{heading}**: {value}")
1186}
1187
1188fn hit_summary_pair(hit: &SearchHit) -> (String, String) {
1198 if let Some(summary) = &hit.summary {
1199 return (summary.heading.clone(), summary.value.clone());
1200 }
1201 summary_pair(type_by_name(&hit.entity_type).as_deref(), &hit.sections)
1202}
1203
1204fn summary_pair(
1206 schema: Option<&TypeDefinition>,
1207 sections: &HashMap<String, String>,
1208) -> (String, String) {
1209 match schema {
1210 Some(schema) => lead_section_pair(schema, |k| sections.get(k).map(String::as_str)),
1211 None => ("Summary".to_string(), "—".to_string()),
1212 }
1213}
1214
1215pub(crate) fn lead_section_pair<'a>(
1223 schema: &TypeDefinition,
1224 get_section: impl Fn(&str) -> Option<&'a str>,
1225) -> (String, String) {
1226 let Some(section) = schema
1227 .required_sections()
1228 .next()
1229 .or(schema.sections.first())
1230 else {
1231 return ("Summary".to_string(), "—".to_string());
1232 };
1233 let value = get_section(section.key.as_str()).unwrap_or("—");
1234 (section.heading.clone(), value.to_string())
1235}
1236
1237fn section_key_to_heading(key: &str) -> String {
1241 let mut chars = key.chars();
1242 match chars.next() {
1243 None => String::new(),
1244 Some(c) => {
1245 let first: String = c.to_uppercase().collect();
1246 let rest: String = chars.map(|c| if c == '_' { ' ' } else { c }).collect();
1247 format!("{first}{rest}")
1248 }
1249 }
1250}
1251
1252fn section_heading_for(type_def: Option<&TypeDefinition>, key: &str) -> String {
1259 type_def
1260 .and_then(|t| t.sections.iter().find(|s| s.key == key))
1261 .map(|s| s.heading.clone())
1262 .unwrap_or_else(|| section_key_to_heading(key))
1263}
1264
1265fn lookup_builtin_type(name: &str) -> Option<Arc<TypeDefinition>> {
1274 static CACHE: OnceLock<Vec<Arc<Schema>>> = OnceLock::new();
1275 let schemas =
1276 CACHE.get_or_init(|| memstead_schema::builtins::load_builtin_schemas().unwrap_or_default());
1277 for s in schemas {
1278 if let Some(t) = s.get_type(name) {
1279 return Some(t);
1280 }
1281 }
1282 None
1283}
1284
1285pub fn render_type_catalog_markdown() -> String {
1291 render_type_catalog_lines(all_types())
1292}
1293
1294pub fn render_type_catalog_markdown_for(schema: &Schema) -> String {
1300 let mut types: Vec<Arc<TypeDefinition>> = schema.types.values().cloned().collect();
1301 types.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
1302 render_type_catalog_lines(types)
1303}
1304
1305fn render_type_catalog_lines(types: Vec<Arc<TypeDefinition>>) -> String {
1306 let mut lines = vec![
1307 "# Available types".to_string(),
1308 String::new(),
1309 "Run `memstead type <name>` to see its metadata fields, sections, relationship types, and writing guidance — over MCP, `memstead_schema` takes the *schema* name and returns every type at once."
1310 .to_string(),
1311 String::new(),
1312 ];
1313 for schema in types {
1314 let required_sections = schema.required_sections().count();
1315 let total_sections = schema.sections.len();
1316 let metadata_count = schema.metadata_fields.len();
1317 lines.push(format!(
1318 "- **{}** — {} sections ({} required), {} metadata fields, staleness {}d",
1319 schema.name.as_str(),
1320 total_sections,
1321 required_sections,
1322 metadata_count,
1323 schema.staleness_threshold_days,
1324 ));
1325 }
1326 lines.push(String::new());
1327 lines.join("\n")
1328}
1329
1330pub fn render_type_info_markdown(schema: &TypeDefinition) -> String {
1332 render_type_info_markdown_in(schema, None)
1333}
1334
1335pub fn render_type_info_markdown_in(
1342 schema: &TypeDefinition,
1343 parent: Option<&memstead_schema::Schema>,
1344) -> String {
1345 let mut lines = Vec::new();
1346 lines.push(format!("# Type: {}", schema.name.as_str()));
1347 lines.push(String::new());
1348 lines.push(format!(
1349 "Staleness threshold: {} days. Hierarchy: `{}`.",
1350 schema.staleness_threshold_days, schema.hierarchy_relationship,
1351 ));
1352 if schema.last_resort {
1353 lines.push(String::new());
1354 lines.push(
1355 "Last resort: this is the schema's fallback type, chosen only when no more \
1356 specific type fits; the `vital_signs` health axis counts what sits on it."
1357 .to_string(),
1358 );
1359 }
1360 lines.push(String::new());
1361
1362 lines.push("## Metadata fields".to_string());
1364 for field in &schema.metadata_fields {
1365 lines.push(format!("- {}", describe_metadata_field(field)));
1366 }
1367 lines.push(String::new());
1368
1369 lines.push("## Sections".to_string());
1371 for section in &schema.sections {
1372 let req = if section.required {
1373 "required"
1374 } else {
1375 "optional"
1376 };
1377 let catch_all = if section.catch_all { ", catch-all" } else { "" };
1378 lines.push(format!(
1379 "- **{}** ({req}{catch_all}, search_weight: {:.1})",
1380 section.key, section.search_weight,
1381 ));
1382 for rule in §ion.write_rules {
1383 lines.push(format!(" - Write rule: {rule}"));
1384 }
1385 }
1386 lines.push(String::new());
1387
1388 lines.push("## Relationship types (with edge weights)".to_string());
1390 for (rel_type, weight) in &schema.edge_weights {
1391 if rel_type == "_default" {
1392 continue;
1393 }
1394 let mut flags: Vec<&str> = Vec::new();
1395 if rel_type == &schema.hierarchy_relationship {
1396 flags.push("hierarchy");
1397 }
1398 if schema
1399 .no_self_loop_relationships
1400 .iter()
1401 .any(|r| r == rel_type)
1402 {
1403 flags.push("no-self-loop");
1404 }
1405 if let Some(p) = parent {
1410 match p.relationship_manual_authoring(rel_type) {
1411 memstead_schema::ManualAuthoring::Forbidden => {
1412 flags.push("manual authoring FORBIDDEN — emitted from body wiki-links only");
1413 }
1414 memstead_schema::ManualAuthoring::Warn => {
1415 flags.push("manual authoring warns");
1416 }
1417 memstead_schema::ManualAuthoring::Allow => {}
1418 }
1419 }
1420 let flag_str = if flags.is_empty() {
1421 String::new()
1422 } else {
1423 format!(" ({})", flags.join(", "))
1424 };
1425 lines.push(format!("- **{rel_type}**: {weight}{flag_str}"));
1426 }
1427 if let Some((_, default_weight)) = schema.edge_weights.iter().find(|(n, _)| *n == "_default") {
1429 lines.push(format!(
1430 "- _default_ (any other relationship type): {default_weight}"
1431 ));
1432 }
1433 lines.push(String::new());
1434
1435 if !schema.write_rules.is_empty() {
1437 lines.push("## Writing guidance".to_string());
1438 for rule in &schema.write_rules {
1439 lines.push(format!("- {rule}"));
1440 }
1441 lines.push(String::new());
1442 }
1443
1444 let system_msg = schema.system_message_str();
1446 if !system_msg.is_empty() {
1447 lines.push("## System context".to_string());
1448 lines.push(system_msg.to_string());
1449 lines.push(String::new());
1450 }
1451
1452 if let Some(ex) = &schema.exemplar {
1456 lines.push("## Exemplar (engine-validated)".to_string());
1457 lines.push(String::new());
1458 lines.push(format!("Title: {}", ex.title));
1459 if !ex.metadata.is_empty() {
1460 lines.push("Metadata:".to_string());
1461 for (k, v) in &ex.metadata {
1462 lines.push(format!("- {k}: {v}"));
1463 }
1464 }
1465 for (key, body) in &ex.sections {
1466 let heading = schema
1467 .section(key)
1468 .map(|s| s.heading.clone())
1469 .unwrap_or_else(|| key.clone());
1470 lines.push(format!("### {heading}"));
1471 lines.push(body.clone());
1472 }
1473 if !ex.relations.is_empty() {
1474 lines.push("Relations (placeholder targets):".to_string());
1475 for r in &ex.relations {
1476 match &r.description {
1477 Some(d) => lines.push(format!(
1478 "- {} → {} — {d}",
1479 r.rel_type_name(),
1480 r.target_slug()
1481 )),
1482 None => lines.push(format!("- {} → {}", r.rel_type_name(), r.target_slug())),
1483 }
1484 }
1485 }
1486 lines.push(String::new());
1487 }
1488
1489 lines.join("\n")
1490}
1491
1492pub fn per_edge_description_str(p: PerEdgeDescription) -> &'static str {
1498 match p {
1499 PerEdgeDescription::Forbidden => "forbidden",
1500 PerEdgeDescription::Optional => "optional",
1501 PerEdgeDescription::Required => "required",
1502 }
1503}
1504
1505pub fn manual_authoring_str(p: ManualAuthoring) -> &'static str {
1507 match p {
1508 ManualAuthoring::Allow => "allow",
1509 ManualAuthoring::Warn => "warn",
1510 ManualAuthoring::Forbidden => "forbidden",
1511 }
1512}
1513
1514#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1530pub enum SchemaVerbosity {
1531 #[default]
1532 Full,
1533 Lite,
1534}
1535
1536impl SchemaVerbosity {
1537 pub fn from_wire(s: &str) -> Option<Self> {
1542 match s {
1543 "full" => Some(Self::Full),
1544 "lite" => Some(Self::Lite),
1545 _ => None,
1546 }
1547 }
1548
1549 pub fn as_wire(self) -> &'static str {
1551 match self {
1552 Self::Full => "full",
1553 Self::Lite => "lite",
1554 }
1555 }
1556}
1557
1558#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1585pub enum OriginClass {
1586 FirstParty,
1588 #[default]
1591 ThirdParty,
1592}
1593
1594impl OriginClass {
1595 pub fn as_wire(self) -> &'static str {
1599 match self {
1600 Self::FirstParty => "first-party",
1601 Self::ThirdParty => "third-party",
1602 }
1603 }
1604
1605 pub fn is_third_party(self) -> bool {
1608 matches!(self, Self::ThirdParty)
1609 }
1610}
1611
1612fn append_section_format(
1633 obj: &mut serde_json::Map<String, serde_json::Value>,
1634 s: &memstead_schema::SectionDef,
1635) {
1636 if let Some(content) = &s.content {
1637 obj.insert("content".into(), serde_json::json!(content));
1638 obj.insert(
1639 "format_severity".into(),
1640 serde_json::json!(s.format_severity),
1641 );
1642 }
1643 if let Some(pattern) = &s.item_pattern {
1644 obj.insert("item_pattern".into(), serde_json::json!(pattern));
1645 }
1646 if let Some(table) = &s.table {
1647 obj.insert("table".into(), serde_json::json!(table));
1648 }
1649 if let Some(example) = &s.example {
1650 obj.insert("example".into(), serde_json::json!(example));
1651 }
1652}
1653
1654#[derive(Debug, Clone)]
1659pub struct UnknownSchemaTypes {
1660 pub unknown: Vec<String>,
1661 pub known: Vec<String>,
1662}
1663
1664fn estimate_payload_tokens(value: &serde_json::Value) -> usize {
1668 serde_json::to_string(value)
1669 .map(|s| estimate_tokens(&s))
1670 .unwrap_or(0)
1671}
1672
1673pub const DEFAULT_SCHEMA_FULL_BUDGET: usize = 15_000;
1683
1684pub fn build_schema_payload(
1685 schema: &Arc<Schema>,
1686 used_by: Vec<String>,
1687 verbosity: SchemaVerbosity,
1688 origin: OriginClass,
1689) -> serde_json::Value {
1690 build_schema_payload_scoped(schema, used_by, verbosity, origin, None, None)
1693 .expect("no type selection, no refusal")
1694}
1695
1696pub fn build_schema_payload_scoped(
1712 schema: &Arc<Schema>,
1713 used_by: Vec<String>,
1714 verbosity: SchemaVerbosity,
1715 origin: OriginClass,
1716 type_selection: Option<&[String]>,
1717 token_budget: Option<usize>,
1718) -> Result<serde_json::Value, UnknownSchemaTypes> {
1719 let manifest = &schema.manifest;
1720
1721 if let Some(sel) = type_selection {
1725 let unknown: Vec<String> = sel
1726 .iter()
1727 .filter(|t| !manifest.types.iter().any(|m| m == *t))
1728 .cloned()
1729 .collect();
1730 if !unknown.is_empty() {
1731 return Err(UnknownSchemaTypes {
1732 unknown,
1733 known: manifest.types.clone(),
1734 });
1735 }
1736 }
1737 let verbosity = if origin.is_third_party() {
1745 SchemaVerbosity::Lite
1746 } else {
1747 verbosity
1748 };
1749
1750 let relationships: Vec<serde_json::Value> = manifest
1761 .relationships
1762 .definitions
1763 .iter()
1764 .filter(|d| d.name != "_default")
1765 .map(|d| {
1766 let mut o = serde_json::json!({
1787 "name": d.name,
1788 "description": d.description,
1789 "when_to_use": d.when_to_use,
1790 "default_weight": d.default_weight,
1791 "acyclic": d.acyclic,
1792 "per_edge_description": per_edge_description_str(d.per_edge_description),
1793 "manual_authoring": manual_authoring_str(d.manual_authoring),
1794 "allowed_sources": d.source_types,
1795 "allowed_targets": d.target_types,
1796 });
1797 if d.derivation {
1803 o["derivation"] = serde_json::json!(true);
1804 }
1805 o
1806 })
1807 .collect();
1808
1809 let cross_mem_relationships: Vec<serde_json::Value> = manifest
1816 .cross_mem_relationships
1817 .iter()
1818 .map(|entry| {
1819 let definitions: Vec<serde_json::Value> = entry
1820 .definitions
1821 .iter()
1822 .filter(|d| d.name != "_default")
1823 .map(|d| {
1824 serde_json::json!({
1825 "name": d.name,
1826 "description": d.description,
1827 "when_to_use": d.when_to_use,
1828 "default_weight": d.default_weight,
1829 "source_types": d.source_types,
1830 "target_types": d.target_types,
1831 "per_edge_description": per_edge_description_str(d.per_edge_description),
1832 })
1833 })
1834 .collect();
1835 serde_json::json!({
1836 "to_schema": entry.to_schema,
1837 "definitions": definitions,
1838 })
1839 })
1840 .collect();
1841
1842 let types_full: Vec<serde_json::Value> = manifest
1845 .types
1846 .iter()
1847 .filter_map(|name| schema.types.get(name.as_str()).map(|td| (name, td)))
1848 .map(|(_, td)| {
1849 let sections: Vec<serde_json::Value> = td
1850 .sections
1851 .iter()
1852 .map(|s| {
1853 let mut obj = serde_json::json!({
1854 "key": s.key,
1855 "heading": s.heading,
1856 "required": s.required,
1857 "write_rules": s.write_rules,
1858 });
1859 append_section_format(obj.as_object_mut().unwrap(), s);
1865 obj
1866 })
1867 .collect();
1868
1869 let fields: Vec<serde_json::Value> = td
1870 .metadata_fields
1871 .iter()
1872 .map(|f| {
1873 let mut obj = serde_json::json!({
1874 "name": f.key,
1875 "description": f.description,
1876 "required": f.is_required(),
1877 });
1878 if let Some(enum_values) = &f.enum_values {
1879 obj.as_object_mut()
1880 .unwrap()
1881 .insert("enum".into(), serde_json::json!(enum_values));
1882 }
1883 if let Some(default) = &f.default_value {
1890 obj.as_object_mut()
1891 .unwrap()
1892 .insert("default".into(), serde_json::json!(default));
1893 }
1894 if let Some(pattern) = &f.value_pattern {
1898 obj.as_object_mut()
1899 .unwrap()
1900 .insert("pattern".into(), serde_json::json!(pattern));
1901 }
1902 obj.as_object_mut().unwrap().insert(
1908 "filterable".into(),
1909 match f.filterable.as_wire_str() {
1910 Some(s) => serde_json::json!(s),
1911 None => serde_json::Value::Null,
1912 },
1913 );
1914 obj
1915 })
1916 .collect();
1917
1918 let required_outgoing: Vec<serde_json::Value> = td
1933 .required_outgoing
1934 .iter()
1935 .map(|block| {
1936 let mut b = serde_json::json!({
1937 "relationships": block.relationships,
1938 "cardinality": block.cardinality.to_string(),
1939 "severity": block.severity,
1940 });
1941 if let (Some(wf), Some(wv)) = (&block.when_field, &block.when_value) {
1946 b["when_field"] = serde_json::json!(wf);
1947 b["when_value"] = serde_json::json!(wv);
1948 }
1949 b
1950 })
1951 .collect();
1952
1953 let constraints: Vec<serde_json::Value> = td
1962 .constraints
1963 .iter()
1964 .map(|c| match c {
1965 memstead_schema::ConstraintDef::RequiresWhen {
1966 field,
1967 when_field,
1968 when_value,
1969 severity,
1970 } => serde_json::json!({
1971 "kind": "requires_when",
1972 "field": field,
1973 "when_field": when_field,
1974 "when_value": when_value,
1975 "severity": severity,
1976 }),
1977 memstead_schema::ConstraintDef::Unique { fields, severity } => {
1978 serde_json::json!({
1979 "kind": "unique",
1980 "fields": fields,
1981 "severity": severity,
1982 })
1983 }
1984 memstead_schema::ConstraintDef::EnumFromNeighbour {
1985 field,
1986 rel_type,
1987 section,
1988 severity,
1989 } => serde_json::json!({
1990 "kind": "enum_from_neighbour",
1991 "field": field,
1992 "rel_type": rel_type,
1993 "section": section,
1994 "severity": severity,
1995 }),
1996 memstead_schema::ConstraintDef::StatusPropagation {
1997 field,
1998 value,
1999 rel_type,
2000 rel_types,
2001 direction,
2002 severity,
2003 } => {
2004 let mut c = serde_json::json!({
2005 "kind": "status_propagation",
2006 "field": field,
2007 "value": value,
2008 "direction": direction,
2009 "severity": severity,
2010 });
2011 if let Some(single) = rel_type {
2015 c["rel_type"] = serde_json::json!(single);
2016 }
2017 if let Some(set) = rel_types {
2018 c["rel_types"] = serde_json::json!(set);
2019 }
2020 c
2021 }
2022 memstead_schema::ConstraintDef::TransitionRequiresChecks {
2023 field,
2024 to_value,
2025 relationships,
2026 direction,
2027 severity,
2028 } => serde_json::json!({
2029 "kind": "transition_requires_checks",
2030 "field": field,
2031 "to_value": to_value,
2032 "relationships": relationships,
2033 "direction": direction,
2034 "severity": severity,
2035 }),
2036 })
2037 .collect();
2038 let mut obj = serde_json::json!({
2039 "name": td.name,
2040 "description": td.description,
2041 "when_to_use": td.when_to_use,
2042 "sections": sections,
2043 "fields": fields,
2044 "writing_guidance": td.write_rules,
2045 "system_context": td.system_message_str(),
2046 "staleness_threshold_days": td.staleness_threshold_days,
2047 "no_self_loop_relationships": td.no_self_loop_relationships,
2048 "required_outgoing": required_outgoing,
2049 "constraints": constraints,
2050 });
2051 if !td.must_reach.is_empty() {
2057 obj["must_reach"] = serde_json::to_value(&td.must_reach)
2058 .expect("must_reach declarations serialize");
2059 }
2060 if !td.signals.is_empty() {
2066 obj["signals"] =
2067 serde_json::to_value(&td.signals).expect("signal declarations serialize");
2068 }
2069 if td.leaf {
2073 obj["leaf"] = serde_json::json!(true);
2074 }
2075 if td.last_resort {
2081 obj["last_resort"] = serde_json::json!(true);
2082 }
2083 if let Some(ex) = &td.exemplar {
2097 let relations: Vec<serde_json::Value> = ex
2098 .relations
2099 .iter()
2100 .map(|r| {
2101 let mut o = serde_json::json!({
2102 "target": r.target_slug(),
2103 "rel_type": r.rel_type_name(),
2104 });
2105 if let Some(d) = &r.description {
2106 o["description"] = serde_json::json!(d);
2107 }
2108 o
2109 })
2110 .collect();
2111 obj["exemplar"] = serde_json::json!({
2112 "title": ex.title,
2113 "metadata": ex.metadata,
2114 "sections": ex.sections,
2115 "relations": relations,
2116 });
2117 }
2118 obj
2119 })
2120 .collect();
2121
2122 let mode = match manifest.relationships.mode {
2123 RelationshipMode::Strict => "strict",
2124 RelationshipMode::Open => "open",
2125 };
2126
2127 let full = verbosity == SchemaVerbosity::Full;
2128
2129 let mut payload = serde_json::json!({
2133 "ref": format!("{}@{}", manifest.name, schema.version),
2134 "relationship_mode": mode,
2135 "community": {
2136 "resolution": manifest.community.resolution,
2137 "seed": manifest.community.seed,
2138 },
2139 "used_by": used_by,
2140 "origin": origin.as_wire(),
2146 });
2147 let obj = payload.as_object_mut().unwrap();
2148
2149 if !manifest.relationships.acyclic_sets.is_empty() {
2154 obj.insert(
2155 "acyclic_sets".into(),
2156 serde_json::to_value(&manifest.relationships.acyclic_sets)
2157 .expect("acyclic_sets serialize"),
2158 );
2159 }
2160 if let Some(lab) = &manifest.relationships.labelling {
2165 obj.insert(
2166 "labelling".into(),
2167 serde_json::to_value(lab).expect("labelling declaration serializes"),
2168 );
2169 }
2170
2171 if full {
2176 obj.insert(
2177 "description".into(),
2178 serde_json::Value::String(manifest.description.clone()),
2179 );
2180 obj.insert(
2181 "when_to_use".into(),
2182 serde_json::Value::String(manifest.when_to_use.clone()),
2183 );
2184 if let Some(msg) = &manifest.system_message {
2190 obj.insert(
2191 "system_context".into(),
2192 serde_json::Value::String(msg.clone()),
2193 );
2194 }
2195 }
2196
2197 obj.insert(
2204 "no_self_loop_relationships_effect".into(),
2205 serde_json::Value::String(
2206 "Per-type `no_self_loop_relationships` governs exactly one behaviour: \
2207 memstead_relate refuses a self-loop (from == to) on a rel-type the \
2208 source type lists here. It does not propagate impact, imply an \
2209 evidence obligation, or have any other effect (the name says it \
2210 all). To declare real impact propagation, use the \
2211 `status_propagation` constraint (`constraints:` on the type), which \
2212 taints dependents of a terminal status value via a named rel-type \
2213 and direction and surfaces them as health findings."
2214 .to_string(),
2215 ),
2216 );
2217
2218 if let Some(target) = &manifest.alias_target_rel_type {
2227 obj.insert(
2228 "alias_target_rel_type".into(),
2229 serde_json::Value::String(target.clone()),
2230 );
2231 }
2232
2233 if full && let Some(dwg) = &manifest.default_writing_guidance {
2240 let mut block = serde_json::Map::new();
2241 if let Some(avoid) = &dwg.avoid {
2242 block.insert("avoid".into(), serde_json::Value::String(avoid.clone()));
2243 }
2244 if let Some(goal) = &dwg.goal {
2245 block.insert("goal".into(), serde_json::Value::String(goal.clone()));
2246 }
2247 if !block.is_empty() {
2248 obj.insert(
2249 "default_writing_guidance".into(),
2250 serde_json::Value::Object(block),
2251 );
2252 }
2253 }
2254
2255 let selected = |name: &serde_json::Value| -> bool {
2260 match type_selection {
2261 None => true,
2262 Some(sel) => name.as_str().is_some_and(|n| sel.iter().any(|s| s == n)),
2263 }
2264 };
2265 let omitted_names: Vec<serde_json::Value> = types_full
2266 .iter()
2267 .filter(|t| !selected(&t["name"]))
2268 .map(|t| t["name"].clone())
2269 .collect();
2270
2271 if full {
2272 obj.insert(
2273 "relationships".into(),
2274 serde_json::Value::Array(relationships),
2275 );
2276 if !cross_mem_relationships.is_empty() {
2280 obj.insert(
2281 "cross_mem_relationships".into(),
2282 serde_json::Value::Array(cross_mem_relationships),
2283 );
2284 }
2285 match type_selection {
2286 Some(_) => {
2287 let served: Vec<serde_json::Value> = types_full
2288 .iter()
2289 .filter(|t| selected(&t["name"]))
2290 .cloned()
2291 .collect();
2292 obj.insert("types".into(), serde_json::Value::Array(served));
2293 if !omitted_names.is_empty() {
2294 obj.insert(
2295 "types_omitted".into(),
2296 serde_json::Value::Array(omitted_names),
2297 );
2298 }
2299 }
2300 None => {
2301 obj.insert("types".into(), serde_json::Value::Array(types_full.clone()));
2302 if let Some(budget) = token_budget {
2310 let estimated = estimate_payload_tokens(&payload);
2311 if estimated > budget {
2312 let obj = payload.as_object_mut().unwrap();
2313 obj.remove("types");
2314 let all_names: Vec<serde_json::Value> =
2315 types_full.iter().map(|t| t["name"].clone()).collect();
2316 obj.insert(
2317 "types_summary".into(),
2318 serde_json::Value::Array(lite_types_projection(&types_full)),
2319 );
2320 obj.insert("types_omitted".into(), serde_json::Value::Array(all_names));
2321 obj.insert(
2322 "_schema_mode".into(),
2323 serde_json::Value::String("reduced".into()),
2324 );
2325 obj.insert("_estimated_tokens".into(), serde_json::json!(estimated));
2326 obj.insert("_token_budget".into(), serde_json::json!(budget));
2327 obj.insert(
2328 "_hint".into(),
2329 serde_json::Value::String(format!(
2330 "the full prose for all {} types (~{estimated} tokens) exceeds \
2331 the response budget ({budget}); per-type prose is served as the \
2332 lite skeleton here — request the full prose for exactly the \
2333 types you will write via `types: [\"<name>\", …]` (valid names \
2334 in `types_omitted`)",
2335 types_full.len(),
2336 )),
2337 );
2338 }
2339 }
2340 }
2341 }
2342 } else {
2343 let relationships_summary: Vec<serde_json::Value> = relationships
2353 .iter()
2354 .map(|r| {
2355 let mut o = serde_json::json!({
2356 "name": r["name"],
2357 "allowed_sources": r["allowed_sources"],
2358 "allowed_targets": r["allowed_targets"],
2359 "manual_authoring": r["manual_authoring"],
2360 "acyclic": r["acyclic"],
2361 "per_edge_description": r["per_edge_description"],
2362 });
2363 if r.get("derivation") == Some(&serde_json::json!(true)) {
2364 o["derivation"] = serde_json::json!(true);
2365 }
2366 o
2367 })
2368 .collect();
2369 obj.insert(
2370 "relationships_summary".into(),
2371 serde_json::Value::Array(relationships_summary),
2372 );
2373
2374 if !cross_mem_relationships.is_empty() {
2378 let cross_summary: Vec<serde_json::Value> = cross_mem_relationships
2379 .iter()
2380 .map(|e| {
2381 let definitions: Vec<serde_json::Value> = e["definitions"]
2382 .as_array()
2383 .map(|defs| {
2384 defs.iter()
2385 .map(|d| {
2386 serde_json::json!({
2387 "name": d["name"],
2388 "source_types": d["source_types"],
2389 "target_types": d["target_types"],
2390 })
2391 })
2392 .collect()
2393 })
2394 .unwrap_or_default();
2395 serde_json::json!({
2396 "to_schema": e["to_schema"],
2397 "definitions": definitions,
2398 })
2399 })
2400 .collect();
2401 obj.insert(
2402 "cross_mem_relationships_summary".into(),
2403 serde_json::Value::Array(cross_summary),
2404 );
2405 }
2406
2407 let served: Vec<serde_json::Value> = types_full
2411 .iter()
2412 .filter(|t| selected(&t["name"]))
2413 .cloned()
2414 .collect();
2415 obj.insert(
2416 "types_summary".into(),
2417 serde_json::Value::Array(lite_types_projection(&served)),
2418 );
2419 if !omitted_names.is_empty() {
2420 obj.insert(
2421 "types_omitted".into(),
2422 serde_json::Value::Array(omitted_names),
2423 );
2424 }
2425 }
2426
2427 Ok(payload)
2428}
2429
2430fn lite_types_projection(types_full: &[serde_json::Value]) -> Vec<serde_json::Value> {
2446 types_full
2447 .iter()
2448 .map(|t| {
2449 let sections: Vec<serde_json::Value> = t["sections"]
2450 .as_array()
2451 .map(|secs| {
2452 secs.iter()
2453 .map(|s| {
2454 let mut o = serde_json::Map::new();
2455 o.insert("key".into(), s["key"].clone());
2456 o.insert("required".into(), s["required"].clone());
2457 for k in [
2461 "content",
2462 "item_pattern",
2463 "table",
2464 "example",
2465 "format_severity",
2466 ] {
2467 if let Some(v) = s.get(k) {
2468 o.insert(k.into(), v.clone());
2469 }
2470 }
2471 serde_json::Value::Object(o)
2472 })
2473 .collect()
2474 })
2475 .unwrap_or_default();
2476 let fields: Vec<serde_json::Value> = t["fields"]
2477 .as_array()
2478 .map(|fs| {
2479 fs.iter()
2480 .map(|f| {
2481 let mut o = serde_json::Map::new();
2482 o.insert("name".into(), f["name"].clone());
2483 o.insert("required".into(), f["required"].clone());
2484 if let Some(e) = f.get("enum") {
2485 o.insert("enum".into(), e.clone());
2486 }
2487 if let Some(d) = f.get("default") {
2488 o.insert("default".into(), d.clone());
2489 }
2490 if let Some(p) = f.get("pattern") {
2497 o.insert("pattern".into(), p.clone());
2498 }
2499 serde_json::Value::Object(o)
2500 })
2501 .collect()
2502 })
2503 .unwrap_or_default();
2504 let mut o = serde_json::json!({
2505 "name": t["name"],
2506 "sections": sections,
2507 "fields": fields,
2508 "no_self_loop_relationships": t["no_self_loop_relationships"],
2509 "required_outgoing": t["required_outgoing"],
2510 "constraints": t["constraints"],
2511 });
2512 if t.get("leaf") == Some(&serde_json::json!(true)) {
2515 o["leaf"] = serde_json::json!(true);
2516 }
2517 if t.get("last_resort") == Some(&serde_json::json!(true)) {
2521 o["last_resort"] = serde_json::json!(true);
2522 }
2523 if let Some(mr) = t.get("must_reach") {
2527 o["must_reach"] = mr.clone();
2528 }
2529 if let Some(sig) = t.get("signals") {
2531 o["signals"] = sig.clone();
2532 }
2533 o
2534 })
2535 .collect()
2536}
2537
2538fn describe_metadata_field(field: &memstead_schema::MetadataFieldDef) -> String {
2540 let type_str = match field.field_type {
2541 FieldType::String => "String",
2542 FieldType::Number => "Number",
2543 FieldType::Date => "Date",
2544 FieldType::Boolean => "Boolean",
2545 };
2546
2547 let mut flags: Vec<&str> = Vec::new();
2548 if !field.is_required() {
2549 flags.push("optional");
2550 } else {
2551 flags.push("required");
2552 }
2553 if field.init_timestamp {
2554 flags.push("auto-init");
2555 }
2556 if field.auto_timestamp {
2557 flags.push("auto-update");
2558 }
2559 match field.serialization {
2560 Serialization::CsvArray => flags.push("csv array"),
2561 Serialization::OmitWhenFalsy => flags.push("omit when falsy"),
2562 Serialization::Default => {}
2563 }
2564
2565 let mut extras: Vec<String> = Vec::new();
2566 if let Some(values) = &field.enum_values {
2567 extras.push(format!("enum: {}", values.join(", ")));
2568 }
2569 if let Some(default) = &field.default_value {
2570 extras.push(format!("default: {default}"));
2571 }
2572 if let Some(pattern) = &field.value_pattern {
2573 extras.push(format!("pattern: `{pattern}`"));
2574 }
2575 let filterable_str = match field.filterable {
2576 Filterable::None => None,
2577 Filterable::Equality => Some("filterable: equality"),
2578 Filterable::Range => Some("filterable: range"),
2579 };
2580 if let Some(f) = filterable_str {
2581 extras.push(f.to_string());
2582 }
2583
2584 let extras_str = if extras.is_empty() {
2585 String::new()
2586 } else {
2587 format!(" — {}", extras.join(" — "))
2588 };
2589
2590 format!(
2591 "**{key}**: {type_str} ({flags}){extras_str}",
2592 key = field.key,
2593 flags = flags.join(", "),
2594 )
2595}
2596
2597#[cfg(test)]
2598mod tests {
2599 use super::*;
2600 use crate::{Entity, EntityId, ListResult, SearchResult};
2601 use indexmap::IndexMap;
2602 use std::collections::HashMap;
2603
2604 fn make_hit(id: &str, title: &str, entity_type: &str, sections: &[(&str, &str)]) -> SearchHit {
2605 SearchHit {
2606 id: EntityId(id.to_string()),
2607 last_modified: None,
2608 title: title.to_string(),
2609 mem: id.split("--").next().unwrap_or("").to_string(),
2610 entity_type: entity_type.to_string(),
2611 stub: false,
2612 score: 1.0,
2613 tokens: 10,
2614 snippet: None,
2615 sections: sections
2616 .iter()
2617 .map(|(k, v)| (k.to_string(), v.to_string()))
2618 .collect(),
2619 score_breakdown: None,
2620 matched_terms: None,
2621 expansion: None,
2622 summary: None,
2625 }
2626 }
2627
2628 fn search_result(hits: Vec<SearchHit>) -> SearchResult {
2629 let returned = hits.len();
2630 let total_tokens = hits.iter().map(|h| h.tokens).sum();
2631 SearchResult {
2632 total: returned,
2633 returned,
2634 offset: 0,
2635 total_tokens,
2636 hits,
2637 facets: None,
2638 warnings: vec![],
2639 }
2640 }
2641
2642 fn list_result(hits: Vec<SearchHit>) -> ListResult {
2643 let returned = hits.len();
2644 ListResult {
2645 total: returned,
2646 returned,
2647 offset: 0,
2648 total_tokens: hits.iter().map(|h| h.tokens).sum(),
2649 hits,
2650 warnings: vec![],
2651 }
2652 }
2653
2654 fn test_entity() -> Entity {
2655 Entity {
2656 id: EntityId("specs--test-entity".to_string()),
2657 title: "Test Entity".to_string(),
2658 entity_type: "spec".to_string(),
2659 mem: "specs".to_string(),
2660 file_path: "test-entity.md".to_string(),
2661 metadata: IndexMap::new(),
2662 sections: IndexMap::from([
2663 ("identity".to_string(), "A test entity for unit tests.".to_string()),
2664 ("purpose".to_string(), "Validates render logic.".to_string()),
2665 ("specifies".to_string(), "Long section content that adds significant token weight to the full entity estimate.".to_string()),
2666 ]),
2667 relationships: vec![],
2668 content_hash: "abc123".to_string(),
2669 stub: false,
2670 stub_kind: None,
2671 heading_spans: std::collections::HashMap::new(),
2672 raw_section_headings: Vec::new(),
2673 }
2674 }
2675
2676 #[test]
2685 fn lite_skeleton_carries_value_pattern_and_last_resort() {
2686 let manifest = r#"name: flagged
2687version: 1.0.0
2688description: legality-flag render fixture
2689when_to_use: render tests
2690types:
2691 - ticket
2692 - misc
2693relationships:
2694 mode: strict
2695 definitions:
2696 - name: PART_OF
2697 description: hier
2698 default_weight: 1.0
2699 - name: _default
2700 description: fallback
2701 default_weight: 1.0
2702community:
2703 resolution: 1.0
2704 seed: 42
2705"#;
2706 let ticket = r#"name: ticket
2707description: t
2708when_to_use: tests
2709sections:
2710 - key: body
2711 heading: Body
2712 required: true
2713 search_weight: 10.0
2714 catch_all: true
2715 write_rules: []
2716metadata_fields:
2717 - key: ticket_key
2718 description: The tracker key.
2719 field_type: string
2720 value_pattern: "[A-Z]+-[0-9]+"
2721 - key: owner
2722 description: Who holds it.
2723 field_type: string
2724title_weight: 100.0
2725text_fields:
2726 - body
2727hierarchy_relationship: PART_OF
2728no_self_loop_relationships: []
2729updatable_fields:
2730 - title
2731 - body
2732health_required_fields:
2733 - body
2734staleness_threshold_days: 90
2735write_rules: []
2736"#;
2737 let misc = r#"name: misc
2738description: the fallback
2739when_to_use: tests
2740last_resort: true
2741sections:
2742 - key: body
2743 heading: Body
2744 required: true
2745 search_weight: 10.0
2746 catch_all: true
2747 write_rules: []
2748metadata_fields: []
2749title_weight: 100.0
2750text_fields:
2751 - body
2752hierarchy_relationship: PART_OF
2753no_self_loop_relationships: []
2754updatable_fields:
2755 - title
2756 - body
2757health_required_fields:
2758 - body
2759staleness_threshold_days: 90
2760write_rules: []
2761"#;
2762 let schema = Arc::new(
2763 memstead_schema::loader::load_schema_from_memory(
2764 manifest,
2765 &[
2766 ("ticket".to_string(), ticket.to_string()),
2767 ("misc".to_string(), misc.to_string()),
2768 ],
2769 )
2770 .expect("flag fixture loads"),
2771 );
2772 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
2773 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
2774 let types = match verbosity {
2775 SchemaVerbosity::Full => &payload["types"],
2776 SchemaVerbosity::Lite => &payload["types_summary"],
2777 };
2778 let types = types.as_array().unwrap();
2779 let ticket = types.iter().find(|t| t["name"] == "ticket").unwrap();
2780 let misc = types.iter().find(|t| t["name"] == "misc").unwrap();
2781 let fields = ticket["fields"].as_array().unwrap();
2782 let keyed = fields.iter().find(|f| f["name"] == "ticket_key").unwrap();
2783 assert_eq!(
2784 keyed["pattern"], "[A-Z]+-[0-9]+",
2785 "{verbosity:?} carries the declared value_pattern"
2786 );
2787 let owner = fields.iter().find(|f| f["name"] == "owner").unwrap();
2788 assert!(
2789 owner.get("pattern").is_none(),
2790 "{verbosity:?}: a field without a pattern renders no key"
2791 );
2792 assert_eq!(
2793 misc["last_resort"],
2794 serde_json::json!(true),
2795 "{verbosity:?} carries the last_resort declaration"
2796 );
2797 assert!(
2798 ticket.get("last_resort").is_none(),
2799 "{verbosity:?}: a type not declaring last_resort renders no key"
2800 );
2801 }
2802 let md = render_type_info_markdown(&schema.types["misc"]);
2804 assert!(md.contains("Last resort:"), "{md}");
2805 let md = render_type_info_markdown(&schema.types["ticket"]);
2806 assert!(!md.contains("Last resort:"), "{md}");
2807 assert!(md.contains("pattern: `[A-Z]+-[0-9]+`"), "{md}");
2808 }
2809
2810 #[test]
2811 fn markdown_frontmatter_filters_computed_and_reserved_metadata_keys() {
2812 use crate::entity::MetadataValue;
2817 let mut entity = test_entity();
2818 entity.metadata.insert(
2819 "_hash".to_string(),
2820 MetadataValue::String("stale".to_string()),
2821 );
2822 entity.metadata.insert(
2823 "type".to_string(),
2824 MetadataValue::String("spec".to_string()),
2825 );
2826 entity
2827 .metadata
2828 .insert("level".to_string(), MetadataValue::String("M0".to_string()));
2829
2830 let md = render_entity_markdown(&entity, None);
2831 assert_eq!(
2832 md.matches("_hash:").count(),
2833 1,
2834 "one computed _hash line, no stored copy"
2835 );
2836 assert!(md.contains("_hash: abc123"), "the computed hash wins");
2837 assert!(
2838 !md.contains("stale"),
2839 "the stored _hash value never renders"
2840 );
2841 assert!(
2842 !md.contains("\ntype: "),
2843 "the reserved triple stays structural"
2844 );
2845 assert!(md.contains("level: M0"), "declared metadata still renders");
2846 }
2847
2848 #[test]
2849 fn section_key_to_heading_basic() {
2850 assert_eq!(section_key_to_heading("identity"), "Identity");
2851 assert_eq!(section_key_to_heading("current_state"), "Current state");
2852 }
2853
2854 #[test]
2855 fn render_uses_schema_declared_heading_for_non_trivial_casing() {
2856 let mut sections: IndexMap<String, String> = IndexMap::new();
2862 sections.insert("claim_a".to_string(), "Body A.".to_string());
2863 sections.insert("claim_b".to_string(), "Body B.".to_string());
2864
2865 let entity = Entity {
2866 id: EntityId("ingest--example".to_string()),
2867 title: "Example".to_string(),
2868 entity_type: "inconsistency".to_string(),
2869 mem: "ingest".to_string(),
2870 file_path: "example.md".to_string(),
2871 metadata: IndexMap::new(),
2872 sections,
2873 relationships: vec![],
2874 content_hash: "h".to_string(),
2875 stub: false,
2876 stub_kind: None,
2877 heading_spans: std::collections::HashMap::new(),
2878 raw_section_headings: Vec::new(),
2879 };
2880
2881 let md = render_entity_markdown(&entity, None);
2882 assert!(
2883 md.contains("## Claim A"),
2884 "expected schema-declared `## Claim A` heading; got:\n{md}"
2885 );
2886 assert!(
2887 md.contains("## Claim B"),
2888 "expected schema-declared `## Claim B` heading; got:\n{md}"
2889 );
2890 assert!(
2892 !md.contains("## Claim a"),
2893 "renderer must not fall back to key-derivation when the \
2894 schema declares a heading; got:\n{md}"
2895 );
2896 }
2897
2898 #[test]
2899 fn render_falls_back_to_key_derivation_for_unknown_types() {
2900 let mut sections: IndexMap<String, String> = IndexMap::new();
2904 sections.insert("identity".to_string(), "body".to_string());
2905
2906 let entity = Entity {
2907 id: EntityId("custom--example".to_string()),
2908 title: "Example".to_string(),
2909 entity_type: "not-a-builtin-type".to_string(),
2910 mem: "custom".to_string(),
2911 file_path: "example.md".to_string(),
2912 metadata: IndexMap::new(),
2913 sections,
2914 relationships: vec![],
2915 content_hash: "h".to_string(),
2916 stub: false,
2917 stub_kind: None,
2918 heading_spans: std::collections::HashMap::new(),
2919 raw_section_headings: Vec::new(),
2920 };
2921
2922 let md = render_entity_markdown(&entity, None);
2923 assert!(
2924 md.contains("## Identity"),
2925 "fallback derivation must produce `## Identity`; got:\n{md}"
2926 );
2927 }
2928
2929 #[test]
2936 fn render_entity_sections_follow_indexmap_insertion_order() {
2937 let mut sections: IndexMap<String, String> = IndexMap::new();
2938 sections.insert("specifies".to_string(), "S content.".to_string());
2939 sections.insert("purpose".to_string(), "P content.".to_string());
2940 sections.insert("identity".to_string(), "I content.".to_string());
2941
2942 let entity = Entity {
2943 id: EntityId("specs--order-test".to_string()),
2944 title: "Order Test".to_string(),
2945 entity_type: "spec".to_string(),
2946 mem: "specs".to_string(),
2947 file_path: "order-test.md".to_string(),
2948 metadata: IndexMap::new(),
2949 sections,
2950 relationships: vec![],
2951 content_hash: "abc123".to_string(),
2952 stub: false,
2953 stub_kind: None,
2954 heading_spans: std::collections::HashMap::new(),
2955 raw_section_headings: Vec::new(),
2956 };
2957
2958 let md = render_entity_markdown(&entity, None);
2959 let specifies_pos = md.find("## Specifies").expect("## Specifies must appear");
2960 let purpose_pos = md.find("## Purpose").expect("## Purpose must appear");
2961 let identity_pos = md.find("## Identity").expect("## Identity must appear");
2962
2963 assert!(
2964 specifies_pos < purpose_pos,
2965 "Specifies (inserted first) must render before Purpose; got:\n{md}"
2966 );
2967 assert!(
2968 purpose_pos < identity_pos,
2969 "Purpose (inserted second) must render before Identity; got:\n{md}"
2970 );
2971 }
2972
2973 #[test]
2979 fn tokens_reflect_filtered_output() {
2980 let entity = test_entity();
2981
2982 let full = render_entity_markdown(&entity, None);
2984 assert!(full.contains("_tokens:"), "should have _tokens");
2985 assert!(
2986 !full.contains("_tokens_unfiltered_body:"),
2987 "should NOT have _tokens_unfiltered_body when unfiltered"
2988 );
2989 assert!(
2990 !full.contains("_tokens_full:"),
2991 "old _tokens_full name must not survive — rename is one-way"
2992 );
2993
2994 let filtered = render_entity_markdown(&entity, Some(&["identity".to_string()]));
2996 assert!(filtered.contains("_tokens:"), "should have _tokens");
2997 assert!(
2998 filtered.contains("_tokens_unfiltered_body:"),
2999 "should have _tokens_unfiltered_body when filtered"
3000 );
3001 assert!(
3002 !filtered.contains("_tokens_full:"),
3003 "old _tokens_full name must not survive — rename is one-way"
3004 );
3005
3006 let full_tokens: usize = full
3008 .lines()
3009 .find(|l| l.starts_with("_tokens:"))
3010 .unwrap()
3011 .trim_start_matches("_tokens: ")
3012 .parse()
3013 .unwrap();
3014 let filtered_tokens: usize = filtered
3015 .lines()
3016 .find(|l| l.starts_with("_tokens:"))
3017 .unwrap()
3018 .trim_start_matches("_tokens: ")
3019 .parse()
3020 .unwrap();
3021 let tokens_unfiltered_body: usize = filtered
3022 .lines()
3023 .find(|l| l.starts_with("_tokens_unfiltered_body:"))
3024 .unwrap()
3025 .trim_start_matches("_tokens_unfiltered_body: ")
3026 .parse()
3027 .unwrap();
3028
3029 assert!(
3030 filtered_tokens < full_tokens,
3031 "filtered _tokens ({filtered_tokens}) should be less than full _tokens ({full_tokens})"
3032 );
3033 assert!(
3034 tokens_unfiltered_body >= full_tokens,
3035 "_tokens_unfiltered_body ({tokens_unfiltered_body}) should be >= full render _tokens ({full_tokens})"
3036 );
3037 }
3038
3039 #[test]
3044 fn render_search_uses_first_required_section_for_spec() {
3045 let hit = make_hit(
3046 "specs--demo",
3047 "Demo Spec",
3048 "spec",
3049 &[
3050 ("identity", "A demo spec."),
3051 ("purpose", "Verifies rendering."),
3052 ],
3053 );
3054 let out = render_search_markdown(&search_result(vec![hit]), 0);
3055 assert!(
3056 out.contains("**Identity**: A demo spec."),
3057 "expected Identity line for spec hit, got:\n{out}"
3058 );
3059 }
3060
3061 #[test]
3062 fn render_search_uses_first_required_section_for_memo() {
3063 let hit = make_hit(
3064 "memos--d1",
3065 "Memo One",
3066 "memo",
3067 &[("claim", "Some claim."), ("context", "Some context.")],
3068 );
3069 let out = render_search_markdown(&search_result(vec![hit]), 0);
3070 assert!(
3071 out.contains("**Claim**: Some claim."),
3072 "expected Claim line for memo hit, got:\n{out}"
3073 );
3074 assert!(
3075 !out.contains("**Identity**"),
3076 "memo hit must not render Identity label"
3077 );
3078 assert!(
3079 !out.contains("**Purpose**"),
3080 "memo hit must not render Purpose label"
3081 );
3082 }
3083
3084 #[test]
3085 fn render_search_uses_first_required_section_for_concept() {
3086 let hit = make_hit(
3087 "concepts--thing",
3088 "Thing",
3089 "concept",
3090 &[("definition", "A thing."), ("explanation", "Details.")],
3091 );
3092 let out = render_search_markdown(&search_result(vec![hit]), 0);
3093 assert!(
3094 out.contains("**Definition**: A thing."),
3095 "expected Definition line for concept hit, got:\n{out}"
3096 );
3097 }
3098
3099 #[test]
3100 fn render_search_missing_summary_section_shows_dash() {
3101 let hit = make_hit("memos--empty", "Empty Memo", "memo", &[]);
3103 let out = render_search_markdown(&search_result(vec![hit]), 0);
3104 assert!(
3105 out.contains("**Claim**: —"),
3106 "expected Claim dash fallback, got:\n{out}"
3107 );
3108 }
3109
3110 #[test]
3111 fn render_search_mixes_schemas_in_one_result() {
3112 let spec_hit = make_hit(
3113 "specs--s1",
3114 "Spec One",
3115 "spec",
3116 &[("identity", "Spec body.")],
3117 );
3118 let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
3119 let out = render_search_markdown(&search_result(vec![spec_hit, memo_hit]), 0);
3120 assert!(
3121 out.contains("**Identity**: Spec body."),
3122 "spec hit should still render Identity, got:\n{out}"
3123 );
3124 assert!(
3125 out.contains("**Claim**: Memo claim."),
3126 "memo hit should render Claim in the same output, got:\n{out}"
3127 );
3128 }
3129
3130 #[test]
3131 fn render_search_unknown_schema_shows_summary_dash() {
3132 let hit = make_hit("bogus--x", "Bogus", "bogus", &[]);
3133 let out = render_search_markdown(&search_result(vec![hit]), 0);
3134 assert!(
3135 out.contains("**Summary**: —"),
3136 "unknown schema should render Summary dash, got:\n{out}"
3137 );
3138 }
3139
3140 #[test]
3141 fn summary_pair_falls_back_when_schema_has_no_required_sections() {
3142 use memstead_schema::{SectionDef, TypeDefinition};
3143
3144 let schema = TypeDefinition {
3145 name: "spec".to_string(),
3146 description: "test".to_string(),
3147 when_to_use: "test".to_string(),
3148 boundaries: vec![],
3149 exemplar: None,
3150 legacy_examples: None,
3151 system_message: None,
3152 sections: vec![SectionDef {
3153 key: "note".to_string(),
3154 heading: "Note".to_string(),
3155 required: false,
3156 load_bearing: None,
3157 search_weight: 1.0,
3158 catch_all: false,
3159 write_rules: vec![],
3160 description: None,
3161 content: None,
3162 item_pattern: None,
3163 table: None,
3164 example: None,
3165 format_severity: memstead_schema::ConstraintSeverity::Block,
3166 compiled_content: None,
3167 format_problems: Vec::new(),
3168 }],
3169 metadata_fields: vec![],
3170 title_weight: 1.0,
3171 text_fields: vec![],
3172 hierarchy_relationship: "PART_OF".to_string(),
3173 last_resort: false,
3174 edge_weight_overrides: indexmap::IndexMap::new(),
3175 edge_weights: indexmap::IndexMap::new(),
3176 no_self_loop_relationships: vec![],
3177 legacy_propagating_relationships: None,
3178 due: None,
3179 resolution: None,
3180 leaf: false,
3181 updatable_fields: vec![],
3182 health_required_fields: vec![],
3183 staleness_threshold_days: 90,
3184 write_rules: vec![],
3185 required_outgoing: vec![],
3186 must_reach: vec![],
3187 signals: vec![],
3188 constraints: vec![],
3189 declared_metadata_keys: vec![],
3190 };
3191
3192 let mut sections = HashMap::new();
3193 sections.insert("note".to_string(), "a note".to_string());
3194 assert_eq!(
3195 summary_pair(Some(&schema), §ions),
3196 ("Note".to_string(), "a note".to_string()),
3197 );
3198
3199 assert_eq!(
3200 summary_pair(Some(&schema), &HashMap::new()),
3201 ("Note".to_string(), "—".to_string()),
3202 );
3203 }
3204
3205 #[test]
3210 fn render_list_uses_first_required_section_for_spec() {
3211 let hit = make_hit(
3212 "specs--demo",
3213 "Demo Spec",
3214 "spec",
3215 &[
3216 ("identity", "A demo spec."),
3217 ("purpose", "Verifies rendering."),
3218 ],
3219 );
3220 let out = render_list_markdown(&list_result(vec![hit]));
3221 assert!(
3222 out.contains("**Identity**: A demo spec."),
3223 "expected Identity line for spec hit, got:\n{out}"
3224 );
3225 }
3226
3227 #[test]
3228 fn render_list_uses_first_required_section_for_memo() {
3229 let hit = make_hit("memos--d1", "Memo One", "memo", &[("claim", "Some claim.")]);
3230 let out = render_list_markdown(&list_result(vec![hit]));
3231 assert!(
3232 out.contains("**Claim**: Some claim."),
3233 "expected Claim line for memo hit, got:\n{out}"
3234 );
3235 assert!(
3236 !out.contains("**Identity**"),
3237 "memo hit must not render Identity label in list output"
3238 );
3239 }
3240
3241 #[test]
3242 fn render_list_uses_first_required_section_for_concept() {
3243 let hit = make_hit(
3244 "concepts--thing",
3245 "Thing",
3246 "concept",
3247 &[("definition", "A thing.")],
3248 );
3249 let out = render_list_markdown(&list_result(vec![hit]));
3250 assert!(
3251 out.contains("**Definition**: A thing."),
3252 "expected Definition line for concept hit, got:\n{out}"
3253 );
3254 }
3255
3256 #[test]
3257 fn render_list_missing_summary_section_shows_dash() {
3258 let hit = make_hit("memos--empty", "Empty Memo", "memo", &[]);
3259 let out = render_list_markdown(&list_result(vec![hit]));
3260 assert!(
3261 out.contains("**Claim**: —"),
3262 "expected Claim dash fallback in list output, got:\n{out}"
3263 );
3264 }
3265
3266 #[test]
3267 fn render_list_mixes_schemas_in_one_result() {
3268 let spec_hit = make_hit(
3269 "specs--s1",
3270 "Spec One",
3271 "spec",
3272 &[("identity", "Spec body.")],
3273 );
3274 let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
3275 let out = render_list_markdown(&list_result(vec![spec_hit, memo_hit]));
3276 assert!(
3277 out.contains("**Identity**: Spec body."),
3278 "spec hit should still render Identity in list output, got:\n{out}"
3279 );
3280 assert!(
3281 out.contains("**Claim**: Memo claim."),
3282 "memo hit should render Claim in list output, got:\n{out}"
3283 );
3284 }
3285
3286 #[test]
3287 fn render_list_unknown_schema_shows_summary_dash() {
3288 let hit = make_hit("bogus--x", "Bogus", "bogus", &[]);
3289 let out = render_list_markdown(&list_result(vec![hit]));
3290 assert!(
3291 out.contains("**Summary**: —"),
3292 "unknown schema should render Summary dash in list output, got:\n{out}"
3293 );
3294 }
3295
3296 #[test]
3301 fn summary_pair_for_spec_returns_identity() {
3302 let schema = type_by_name("spec");
3303 let mut sections = HashMap::new();
3304 sections.insert("identity".to_string(), "A demo spec.".to_string());
3305 assert_eq!(
3306 summary_pair(schema.as_deref(), §ions),
3307 ("Identity".to_string(), "A demo spec.".to_string()),
3308 );
3309 }
3310
3311 #[test]
3312 fn summary_pair_for_memo_returns_claim() {
3313 let schema = type_by_name("memo");
3314 let mut sections = HashMap::new();
3315 sections.insert("claim".to_string(), "Memos matter.".to_string());
3316 assert_eq!(
3317 summary_pair(schema.as_deref(), §ions),
3318 ("Claim".to_string(), "Memos matter.".to_string()),
3319 );
3320 }
3321
3322 #[test]
3323 fn summary_pair_missing_section_returns_dash() {
3324 let schema = type_by_name("memo");
3325 assert_eq!(
3326 summary_pair(schema.as_deref(), &HashMap::new()),
3327 ("Claim".to_string(), "—".to_string()),
3328 );
3329 }
3330
3331 #[test]
3332 fn summary_pair_unknown_schema_returns_summary_dash() {
3333 assert_eq!(
3334 summary_pair(None, &HashMap::new()),
3335 ("Summary".to_string(), "—".to_string()),
3336 );
3337 }
3338
3339 #[test]
3344 fn envelope_serializes_summary_fields() {
3345 let hit = make_hit(
3346 "memos--d1",
3347 "Memo One",
3348 "memo",
3349 &[("claim", "Memos matter.")],
3350 );
3351 let result = search_result(vec![hit]);
3352 let envelope = build_search_envelope(&result, 0, &|_| OriginClass::FirstParty);
3353 let value = serde_json::to_value(&envelope).expect("envelope must serialize");
3354
3355 assert_eq!(value["_total"], 1);
3359 assert_eq!(value["_returned"], 1);
3360 assert_eq!(value["_offset"], 0);
3361 assert_eq!(
3364 value["warnings"],
3365 serde_json::json!([]),
3366 "empty warnings must serialise as [], got: {value}"
3367 );
3368
3369 let hit0 = &value["hits"][0];
3370 assert_eq!(hit0["summary_heading"], "Claim");
3371 assert_eq!(hit0["summary_value"], "Memos matter.");
3372 assert_eq!(hit0["id"], "memos--d1");
3374 assert_eq!(hit0["title"], "Memo One");
3375 assert_eq!(hit0["entity_type"], "memo");
3376 assert_eq!(hit0["mem"], "memos");
3377 assert_eq!(hit0["stub"], false);
3378 assert_eq!(hit0["tokens"], 10);
3379 assert!(hit0["sections"].is_object());
3380 }
3381
3382 #[test]
3383 fn envelope_roundtrips_through_structured_content() {
3384 let spec_hit = make_hit(
3387 "specs--s1",
3388 "Spec One",
3389 "spec",
3390 &[("identity", "Spec body.")],
3391 );
3392 let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
3393 let result = search_result(vec![spec_hit, memo_hit]);
3394 let envelope = build_search_envelope(&result, 0, &|_| OriginClass::FirstParty);
3395 let value = serde_json::to_value(&envelope).expect("envelope must serialize");
3396
3397 let hits = value["hits"].as_array().expect("hits must be array");
3398 assert_eq!(hits.len(), 2);
3399 assert_eq!(hits[0]["summary_heading"], "Identity");
3400 assert_eq!(hits[0]["summary_value"], "Spec body.");
3401 assert_eq!(hits[1]["summary_heading"], "Claim");
3402 assert_eq!(hits[1]["summary_value"], "Memo claim.");
3403 }
3404
3405 #[test]
3406 fn list_envelope_includes_total_tokens() {
3407 let hit = make_hit(
3408 "concepts--c1",
3409 "Thing",
3410 "concept",
3411 &[("definition", "A thing.")],
3412 );
3413 let result = list_result(vec![hit]);
3414 let envelope = build_list_envelope(&result, &|_| OriginClass::FirstParty);
3415 let value = serde_json::to_value(&envelope).expect("envelope must serialize");
3416
3417 assert_eq!(value["_total"], 1);
3419 assert_eq!(value["_total_tokens"], 10);
3420 assert!(value.get("total").is_none(), "unprefixed keys retired");
3421 assert_eq!(value["hits"][0]["summary_heading"], "Definition");
3422 assert_eq!(value["hits"][0]["summary_value"], "A thing.");
3423 }
3424
3425 #[test]
3426 fn envelope_emits_warnings_when_present() {
3427 let mut result = search_result(vec![]);
3428 result.warnings = vec![crate::ops::WarningHint::FieldNotFilterable {
3431 field: "foo".to_string(),
3432 }];
3433 let envelope = build_search_envelope(&result, 0, &|_| OriginClass::FirstParty);
3434 let value = serde_json::to_value(&envelope).expect("envelope must serialize");
3435 assert_eq!(value["warnings"][0]["code"], "FIELD_NOT_FILTERABLE");
3436 assert_eq!(value["warnings"][0]["details"]["field"], "foo");
3437 assert!(
3438 value["warnings"][0]["message"]
3439 .as_str()
3440 .is_some_and(|m| m.contains("not filterable"))
3441 );
3442 }
3443
3444 fn tm(field: &str, snippet: &str, heading_path: Option<&[&str]>) -> TermMatch {
3449 TermMatch {
3450 field: field.to_string(),
3451 snippet: snippet.to_string(),
3452 heading_path: heading_path.map(|p| p.iter().map(|s| s.to_string()).collect()),
3453 }
3454 }
3455
3456 fn sample_facets() -> Facets {
3457 use crate::ops::SubsectionFacet;
3458 Facets {
3459 by_type: HashMap::from([
3460 ("spec".to_string(), 7),
3461 ("memo".to_string(), 3),
3462 ("decision".to_string(), 2),
3463 ]),
3464 by_mem: HashMap::from([("specs".to_string(), 10), ("memos".to_string(), 2)]),
3465 by_level: HashMap::from([("high".to_string(), 4)]),
3466 by_status: HashMap::from([("active".to_string(), 6)]),
3467 by_confidence: HashMap::from([("medium".to_string(), 3)]),
3468 by_subsection: vec![
3469 SubsectionFacet {
3470 path: vec!["specifies".to_string(), "Response Shapes".to_string()],
3471 count: 4,
3472 },
3473 SubsectionFacet {
3474 path: vec!["purpose".to_string(), "Rationale".to_string()],
3475 count: 2,
3476 },
3477 ],
3478 by_expansion: HashMap::from([("primary".to_string(), 8), ("expanded".to_string(), 4)]),
3479 }
3480 }
3481
3482 #[test]
3483 fn render_search_emits_matched_terms_line() {
3484 let mut hit = make_hit(
3485 "specs--e1",
3486 "Entity One",
3487 "spec",
3488 &[("identity", "Body text.")],
3489 );
3490 hit.matched_terms = Some(HashMap::from([
3491 (
3492 "entity".to_string(),
3493 vec![
3494 tm("title", "...entity...", None),
3495 tm("purpose", "...entity...", None),
3496 tm("purpose", "...entity two...", None),
3497 ],
3498 ),
3499 ("one".to_string(), vec![tm("title", "...one...", None)]),
3500 ]));
3501 let out = render_search_markdown(&search_result(vec![hit]), 0);
3502 assert!(
3503 out.contains("**Matched terms:**"),
3504 "missing Matched terms line; got:\n{out}"
3505 );
3506 assert!(
3507 out.contains("`entity` (purpose×2, title×1)"),
3508 "entity term grouping wrong; got:\n{out}"
3509 );
3510 assert!(
3511 out.contains("`one` (title×1)"),
3512 "one term grouping wrong; got:\n{out}"
3513 );
3514 }
3515
3516 #[test]
3517 fn render_search_emits_score_breakdown_line() {
3518 let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
3519 hit.score_breakdown = Some(ScoreBreakdown {
3520 bm25: 2.5,
3521 title_boost: 2.0,
3522 field_weights: HashMap::from([("body".to_string(), 0.8), ("purpose".to_string(), 0.3)]),
3523 expansion_decay: Some(0.5),
3524 });
3525 let out = render_search_markdown(&search_result(vec![hit]), 0);
3526 assert!(
3527 out.contains(
3528 "**Score:** bm25 2.5 + title 2.0 + body 0.8 + purpose 0.3 + expansion_decay ×0.5"
3529 ),
3530 "score breakdown line wrong; got:\n{out}"
3531 );
3532 }
3533
3534 #[test]
3535 fn render_search_omits_expansion_decay_when_none() {
3536 let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
3537 hit.score_breakdown = Some(ScoreBreakdown {
3538 bm25: 1.5,
3539 title_boost: 1.0,
3540 field_weights: HashMap::new(),
3541 expansion_decay: None,
3542 });
3543 let out = render_search_markdown(&search_result(vec![hit]), 0);
3544 assert!(
3545 out.contains("**Score:** bm25 1.5 + title 1.0"),
3546 "base score wrong; got:\n{out}"
3547 );
3548 assert!(
3549 !out.contains("expansion_decay"),
3550 "expansion_decay must be absent when None; got:\n{out}"
3551 );
3552 }
3553
3554 #[test]
3555 fn render_search_emits_heading_path_line() {
3556 let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
3557 hit.matched_terms = Some(HashMap::from([(
3558 "x".to_string(),
3559 vec![
3560 tm("purpose", "...x...", Some(&["Purpose", "Rationale"])),
3561 tm("purpose", "...x...", Some(&["Purpose", "Rationale"])), tm("specifies", "...x...", Some(&["Specifies", "Responses"])),
3563 ],
3564 )]));
3565 let out = render_search_markdown(&search_result(vec![hit]), 0);
3566 assert!(
3567 out.contains("**Heading path:** Purpose › Rationale; Specifies › Responses"),
3568 "heading path line wrong; got:\n{out}"
3569 );
3570 }
3571
3572 #[test]
3573 fn render_search_emits_expansion_line() {
3574 let mut hit = make_hit("specs--e2", "Entity Two", "spec", &[("identity", "b")]);
3575 hit.expansion = Some(ExpansionInfo {
3576 of: EntityId("specs--seed".to_string()),
3577 via_edge: "refines".to_string(),
3578 via_direction: crate::graph::query::TraversalDirection::Out,
3579 depth: 1,
3580 });
3581 let out = render_search_markdown(&search_result(vec![hit]), 0);
3582 assert!(
3583 out.contains("**Expansion:** from `specs--seed` via `refines` [out] (depth 1)"),
3584 "expansion line reports the traversal direction beside the label; got:\n{out}"
3585 );
3586 }
3587
3588 #[test]
3589 fn render_search_emits_facets_block() {
3590 let mut result = search_result(vec![]);
3591 result.facets = Some(sample_facets());
3592 let out = render_search_markdown(&result, 0);
3593 assert!(
3594 out.contains("## Facets"),
3595 "facets header missing; got:\n{out}"
3596 );
3597 assert!(
3598 out.contains("- **by_type:** spec=7, memo=3, decision=2"),
3599 "by_type bucket wrong; got:\n{out}"
3600 );
3601 assert!(
3602 out.contains("- **by_mem:** specs=10, memos=2"),
3603 "by_mem bucket wrong; got:\n{out}"
3604 );
3605 assert!(
3606 out.contains("- **by_level:** high=4"),
3607 "by_level bucket wrong; got:\n{out}"
3608 );
3609 assert!(
3610 out.contains("- **by_status:** active=6"),
3611 "by_status bucket wrong; got:\n{out}"
3612 );
3613 assert!(
3614 out.contains("- **by_confidence:** medium=3"),
3615 "by_confidence bucket wrong; got:\n{out}"
3616 );
3617 assert!(
3618 out.contains("- **by_expansion:** primary=8, expanded=4"),
3619 "by_expansion bucket wrong; got:\n{out}"
3620 );
3621 assert!(
3622 out.contains("- **by_subsection:**"),
3623 "by_subsection header missing; got:\n{out}"
3624 );
3625 assert!(
3626 out.contains("`specifies › Response Shapes`: 4"),
3627 "subsection facet wrong; got:\n{out}"
3628 );
3629 }
3630
3631 #[test]
3632 fn render_search_omits_facets_block_when_all_empty() {
3633 let mut result = search_result(vec![]);
3634 result.facets = Some(Facets::default());
3635 let out = render_search_markdown(&result, 0);
3636 assert!(
3637 !out.contains("## Facets"),
3638 "empty facets must not emit header; got:\n{out}"
3639 );
3640 }
3641
3642 #[test]
3646 fn search_markdown_covers_every_sidecar_field() {
3647 let mut hit = make_hit(
3648 "specs--e1",
3649 "Entity One",
3650 "spec",
3651 &[("identity", "Body text.")],
3652 );
3653 hit.matched_terms = Some(HashMap::from([(
3654 "entity".to_string(),
3655 vec![tm("title", "...entity...", Some(&["Purpose", "Rationale"]))],
3656 )]));
3657 hit.score_breakdown = Some(ScoreBreakdown {
3658 bm25: 1.5,
3659 title_boost: 1.0,
3660 field_weights: HashMap::from([("body".to_string(), 0.4)]),
3661 expansion_decay: Some(0.5),
3662 });
3663 hit.expansion = Some(ExpansionInfo {
3664 of: EntityId("specs--seed".to_string()),
3665 via_edge: "refines".to_string(),
3666 via_direction: crate::graph::query::TraversalDirection::Out,
3667 depth: 2,
3668 });
3669
3670 let mut result = search_result(vec![hit]);
3671 result.facets = Some(sample_facets());
3672
3673 let out = render_search_markdown(&result, 0);
3674 for marker in [
3675 "## Facets",
3676 "- **by_type:**",
3677 "- **by_mem:**",
3678 "- **by_level:**",
3679 "- **by_status:**",
3680 "- **by_confidence:**",
3681 "- **by_expansion:**",
3682 "- **by_subsection:**",
3683 "**Matched terms:**",
3684 "**Score:**",
3685 "**Heading path:**",
3686 "**Expansion:**",
3687 ] {
3688 assert!(
3689 out.contains(marker),
3690 "lockstep marker `{marker}` missing from search markdown; \
3691 update render_search_markdown when adding sidecar fields. got:\n{out}"
3692 );
3693 }
3694 }
3695
3696 #[test]
3703 fn build_entity_envelope_source_field_reads_edge_source() {
3704 let mut entity = test_entity();
3705 let body_link_target = EntityId("specs--body-link-target".to_string());
3706 let explicit_target = EntityId("specs--explicit-target".to_string());
3707 entity.relationships = vec![
3708 crate::entity::Relationship::new("REFERENCES".to_string(), body_link_target.clone()),
3709 crate::entity::Relationship::new("USES".to_string(), explicit_target.clone()),
3710 ];
3711
3712 let edges = vec![
3713 crate::store::Edge {
3714 rel_type: "REFERENCES".to_string(),
3715 target: body_link_target.clone(),
3716 source: crate::store::EdgeSource::BodyLink,
3717 },
3718 crate::store::Edge {
3719 rel_type: "USES".to_string(),
3720 target: explicit_target.clone(),
3721 source: crate::store::EdgeSource::Explicit,
3722 },
3723 ];
3724
3725 let env = build_entity_envelope(
3726 &entity,
3727 0,
3728 None,
3729 None,
3730 None,
3731 OriginClass::FirstParty,
3732 &edges,
3733 None,
3734 None,
3735 None,
3736 );
3737 let relationships = env["relationships"].as_array().expect("array");
3738 let refs = relationships
3739 .iter()
3740 .find(|r| r["rel_type"] == "REFERENCES")
3741 .expect("REFERENCES present");
3742 assert_eq!(
3743 refs["source"], "body_link",
3744 "alias-synthesised edge must label body_link"
3745 );
3746 let uses = relationships
3747 .iter()
3748 .find(|r| r["rel_type"] == "USES")
3749 .expect("USES present");
3750 assert_eq!(
3751 uses["source"], "explicit",
3752 "explicit-authored edge must label explicit"
3753 );
3754 }
3755
3756 #[test]
3763 fn build_entity_envelope_carries_origin_direction_and_incoming() {
3764 let mut entity = test_entity();
3765 let out_target = EntityId("specs--downstream".to_string());
3766 entity.relationships = vec![crate::entity::Relationship::new(
3767 "USES".to_string(),
3768 out_target.clone(),
3769 )];
3770 let edges = vec![crate::store::Edge {
3771 rel_type: "USES".to_string(),
3772 target: out_target,
3773 source: crate::store::EdgeSource::Explicit,
3774 }];
3775 let incoming = vec![crate::store::InEdge {
3776 rel_type: "MANAGES".to_string(),
3777 from: EntityId("specs--upstream".to_string()),
3778 source: crate::store::EdgeSource::Explicit,
3779 }];
3780
3781 let env = build_entity_envelope(
3783 &entity,
3784 0,
3785 None,
3786 None,
3787 None,
3788 OriginClass::ThirdParty,
3789 &edges,
3790 None,
3791 None,
3792 None,
3793 );
3794 assert_eq!(env["origin"], "third-party", "origin is envelope-level");
3795 let rels = env["relationships"].as_array().expect("array");
3796 assert_eq!(rels.len(), 1);
3797 assert_eq!(rels[0]["direction"], "out");
3798
3799 let env = build_entity_envelope(
3802 &entity,
3803 0,
3804 None,
3805 None,
3806 None,
3807 OriginClass::FirstParty,
3808 &edges,
3809 Some(&incoming),
3810 None,
3811 None,
3812 );
3813 assert_eq!(env["origin"], "first-party");
3814 let rels = env["relationships"].as_array().expect("array");
3815 assert_eq!(rels.len(), 2);
3816 let inc = rels
3817 .iter()
3818 .find(|r| r["direction"] == "in")
3819 .expect("incoming entry present");
3820 assert_eq!(inc["rel_type"], "MANAGES");
3821 assert_eq!(inc["from"], "specs--upstream");
3822 assert!(
3823 inc.get("target").is_none(),
3824 "incoming carries from, not target"
3825 );
3826 }
3827
3828 #[test]
3833 fn build_entity_envelope_source_field_falls_back_to_explicit_when_edge_missing() {
3834 let mut entity = test_entity();
3835 let target = EntityId("specs--unmapped".to_string());
3836 entity.relationships = vec![crate::entity::Relationship::new("USES".to_string(), target)];
3837 let edges: Vec<crate::store::Edge> = Vec::new();
3838 let env = build_entity_envelope(
3839 &entity,
3840 0,
3841 None,
3842 None,
3843 None,
3844 OriginClass::FirstParty,
3845 &edges,
3846 None,
3847 None,
3848 None,
3849 );
3850 let relationships = env["relationships"].as_array().expect("array");
3851 assert_eq!(relationships[0]["source"], "explicit");
3852 }
3853
3854 #[test]
3860 fn build_entity_envelope_nested_metadata_carries_every_schema_field() {
3861 use crate::entity::MetadataValue;
3862 let mut entity = test_entity();
3863 entity.entity_type = "contract".to_string();
3864 entity.metadata = IndexMap::from([
3866 ("level".to_string(), MetadataValue::String("M0".to_string())),
3867 (
3868 "stability".to_string(),
3869 MetadataValue::String("stable".to_string()),
3870 ),
3871 (
3872 "created_date".to_string(),
3873 MetadataValue::String("2026-01-01".to_string()),
3874 ),
3875 (
3876 "last_modified".to_string(),
3877 MetadataValue::String("2026-05-19".to_string()),
3878 ),
3879 (
3880 "protocol".to_string(),
3881 MetadataValue::String("https".to_string()),
3882 ),
3883 (
3884 "version".to_string(),
3885 MetadataValue::String("0.1.0".to_string()),
3886 ),
3887 (
3888 "deprecation_status".to_string(),
3889 MetadataValue::String("none".to_string()),
3890 ),
3891 ]);
3892
3893 let env = build_entity_envelope(
3894 &entity,
3895 0,
3896 None,
3897 None,
3898 None,
3899 OriginClass::FirstParty,
3900 &[],
3901 None,
3902 None,
3903 None,
3904 );
3905
3906 assert!(
3909 env.get("level").is_none(),
3910 "level must not be hoisted top-level"
3911 );
3912 assert!(
3913 env.get("stability").is_none(),
3914 "stability must not be hoisted"
3915 );
3916 assert!(
3917 env.get("created_date").is_none(),
3918 "created_date must not be hoisted"
3919 );
3920 assert!(
3921 env.get("last_modified").is_none(),
3922 "last_modified must not be hoisted"
3923 );
3924 assert_eq!(env["entity_type"], "contract");
3928 assert!(
3929 env.get("type").is_none(),
3930 "the retired wire key must not survive"
3931 );
3932
3933 let metadata = env["metadata"].as_object().expect("metadata map");
3935 assert_eq!(metadata["level"], "M0");
3936 assert_eq!(metadata["stability"], "stable");
3937 assert_eq!(metadata["created_date"], "2026-01-01");
3938 assert_eq!(metadata["last_modified"], "2026-05-19");
3939 assert_eq!(metadata["protocol"], "https");
3940 assert_eq!(metadata["version"], "0.1.0");
3941 assert_eq!(metadata["deprecation_status"], "none");
3942
3943 for k in metadata.keys() {
3946 assert!(
3947 !k.starts_with('_'),
3948 "metadata map must not carry underscore-prefixed key `{k}`"
3949 );
3950 assert!(
3951 !["mem", "id", "type"].contains(&k.as_str()),
3952 "metadata map must not carry identity key `{k}` (it lives top-level)"
3953 );
3954 }
3955 }
3956
3957 #[test]
3961 fn build_entity_envelope_stub_carries_empty_metadata_map() {
3962 let mut entity = test_entity();
3963 entity.stub = true;
3964 entity.stub_kind = Some(crate::entity::StubKind::ForwardReference);
3965 entity.metadata = IndexMap::new();
3966 let env = build_entity_envelope(
3967 &entity,
3968 0,
3969 None,
3970 None,
3971 None,
3972 OriginClass::FirstParty,
3973 &[],
3974 None,
3975 None,
3976 None,
3977 );
3978 let metadata = env["metadata"]
3979 .as_object()
3980 .expect("metadata key present even on stubs");
3981 assert!(metadata.is_empty(), "stub metadata map must be empty");
3982 }
3983
3984 #[test]
3991 fn build_entity_envelope_user_field_collisions_isolated_to_nested_map() {
3992 use crate::entity::MetadataValue;
3993 let mut entity = test_entity();
3994 entity.metadata = IndexMap::from([
3995 (
3996 "sections".to_string(),
3997 MetadataValue::String("user-supplied-shadow".to_string()),
3998 ),
3999 (
4000 "relationships".to_string(),
4001 MetadataValue::String("also-shadowed".to_string()),
4002 ),
4003 ]);
4004 let env = build_entity_envelope(
4005 &entity,
4006 0,
4007 None,
4008 None,
4009 None,
4010 OriginClass::FirstParty,
4011 &[],
4012 None,
4013 None,
4014 None,
4015 );
4016 assert!(
4018 env["sections"].is_object(),
4019 "top-level sections stays a map"
4020 );
4021 assert!(
4022 env["relationships"].is_array(),
4023 "top-level relationships stays an array"
4024 );
4025 let metadata = env["metadata"].as_object().expect("metadata map");
4027 assert_eq!(metadata["sections"], "user-supplied-shadow");
4028 assert_eq!(metadata["relationships"], "also-shadowed");
4029 }
4030
4031 #[test]
4035 fn build_entity_envelope_unfiltered_body_token_field_name() {
4036 let entity = test_entity();
4037 let env_filtered = build_entity_envelope(
4039 &entity,
4040 10,
4041 Some(42),
4042 None,
4043 None,
4044 OriginClass::FirstParty,
4045 &[],
4046 None,
4047 None,
4048 None,
4049 );
4050 assert_eq!(env_filtered["_tokens_unfiltered_body"], 42);
4051 assert!(
4052 env_filtered.get("_tokens_full").is_none(),
4053 "_tokens_full must not survive — rename is one-way"
4054 );
4055 let env_unfiltered = build_entity_envelope(
4057 &entity,
4058 10,
4059 None,
4060 None,
4061 None,
4062 OriginClass::FirstParty,
4063 &[],
4064 None,
4065 None,
4066 None,
4067 );
4068 assert!(env_unfiltered.get("_tokens_unfiltered_body").is_none());
4069 assert!(env_unfiltered.get("_tokens_full").is_none());
4070 }
4071
4072 fn software_schema() -> Arc<Schema> {
4080 memstead_schema::builtins::load_builtin_schemas()
4081 .expect("builtins load")
4082 .into_iter()
4083 .find(|s| s.manifest.name == "software")
4084 .expect("software schema is a builtin")
4085 }
4086
4087 #[test]
4088 fn schema_verbosity_wire_round_trips() {
4089 assert_eq!(
4090 SchemaVerbosity::from_wire("full"),
4091 Some(SchemaVerbosity::Full)
4092 );
4093 assert_eq!(
4094 SchemaVerbosity::from_wire("lite"),
4095 Some(SchemaVerbosity::Lite)
4096 );
4097 assert_eq!(SchemaVerbosity::from_wire("brief"), None);
4098 assert_eq!(SchemaVerbosity::from_wire(""), None);
4099 assert_eq!(SchemaVerbosity::Full.as_wire(), "full");
4100 assert_eq!(SchemaVerbosity::Lite.as_wire(), "lite");
4101 assert_eq!(SchemaVerbosity::default(), SchemaVerbosity::Full);
4102 }
4103
4104 #[test]
4110 fn exemplar_serves_at_full_and_lite_stays_byte_unchanged() {
4111 let manifest = r#"name: servefix
4112version: 1.0.0
4113description: serving fixture
4114when_to_use: tests
4115types:
4116 - sample
4117relationships:
4118 mode: strict
4119 definitions:
4120 - name: PART_OF
4121 description: hier
4122 default_weight: 3.0
4123 - name: _default
4124 description: fallback
4125 default_weight: 1.0
4126community:
4127 resolution: 1.0
4128 seed: 42
4129"#;
4130 let base_type = r#"name: sample
4131description: t
4132when_to_use: tests
4133sections:
4134 - key: body
4135 heading: Body
4136 required: true
4137 search_weight: 10.0
4138 catch_all: true
4139 write_rules: []
4140metadata_fields:
4141 - key: status
4142 description: state
4143 field_type: string
4144 enum_values: [draft, final]
4145 optional: true
4146title_weight: 100.0
4147text_fields:
4148 - body
4149hierarchy_relationship: PART_OF
4150no_self_loop_relationships: []
4151updatable_fields:
4152 - title
4153 - body
4154health_required_fields:
4155 - body
4156staleness_threshold_days: 90
4157write_rules: []
4158"#;
4159 let with_exemplar = format!(
4160 "{base_type}exemplar:\n title: A Conforming Sample\n metadata:\n status: draft\n sections:\n body: \"One canonical body paragraph.\"\n relations:\n - to: parent-placeholder\n type: PART_OF\n"
4161 );
4162
4163 let plain = Arc::new(
4164 memstead_schema::loader::load_schema_from_memory(
4165 manifest,
4166 &[("sample".to_string(), base_type.to_string())],
4167 )
4168 .expect("fixture loads"),
4169 );
4170 let exemplary = Arc::new(
4171 memstead_schema::loader::load_schema_from_memory(
4172 manifest,
4173 &[("sample".to_string(), with_exemplar)],
4174 )
4175 .expect("fixture loads"),
4176 );
4177
4178 let full = build_schema_payload(
4180 &exemplary,
4181 vec![],
4182 SchemaVerbosity::Full,
4183 OriginClass::FirstParty,
4184 );
4185 let ex = &full["types"][0]["exemplar"];
4186 assert_eq!(ex["title"], "A Conforming Sample", "{full}");
4187 assert_eq!(ex["metadata"]["status"], "draft");
4188 assert_eq!(ex["sections"]["body"], "One canonical body paragraph.");
4189 assert_eq!(ex["relations"][0]["target"], "parent-placeholder");
4190 assert_eq!(ex["relations"][0]["rel_type"], "PART_OF");
4191
4192 let full_plain = build_schema_payload(
4194 &plain,
4195 vec![],
4196 SchemaVerbosity::Full,
4197 OriginClass::FirstParty,
4198 );
4199 assert!(full_plain["types"][0].get("exemplar").is_none());
4200
4201 let lite_with = build_schema_payload(
4204 &exemplary,
4205 vec![],
4206 SchemaVerbosity::Lite,
4207 OriginClass::FirstParty,
4208 );
4209 let lite_without = build_schema_payload(
4210 &plain,
4211 vec![],
4212 SchemaVerbosity::Lite,
4213 OriginClass::FirstParty,
4214 );
4215 assert_eq!(
4216 serde_json::to_string(&lite_with).unwrap(),
4217 serde_json::to_string(&lite_without).unwrap(),
4218 "lite must not change when an exemplar exists"
4219 );
4220 assert!(
4221 !serde_json::to_string(&lite_with)
4222 .unwrap()
4223 .contains("exemplar"),
4224 "lite must not mention exemplars at all"
4225 );
4226 }
4227
4228 #[test]
4232 fn first_party_origin_is_labelled_and_keeps_prose() {
4233 let schema = software_schema();
4234 let full = build_schema_payload(
4235 &schema,
4236 vec!["v".into()],
4237 SchemaVerbosity::Full,
4238 OriginClass::FirstParty,
4239 );
4240 assert_eq!(full["origin"], "first-party");
4241 assert!(full["description"].is_string());
4243 let t = &full["types"].as_array().unwrap()[0];
4244 assert!(t.get("system_context").is_some());
4245 assert!(t.get("writing_guidance").is_some());
4246
4247 let lite = build_schema_payload(
4249 &schema,
4250 vec!["v".into()],
4251 SchemaVerbosity::Lite,
4252 OriginClass::FirstParty,
4253 );
4254 assert_eq!(lite["origin"], "first-party");
4255 }
4256
4257 #[test]
4262 fn constraints_and_severity_render_at_both_verbosities() {
4263 let manifest = r#"name: constrained
4264version: 1.0.0
4265description: constraint render fixture
4266when_to_use: render tests
4267types:
4268 - sample
4269relationships:
4270 mode: strict
4271 definitions:
4272 - name: PART_OF
4273 description: hier
4274 default_weight: 3.0
4275 - name: _default
4276 description: fallback
4277 default_weight: 1.0
4278community:
4279 resolution: 1.0
4280 seed: 42
4281"#;
4282 let type_yaml = r#"name: sample
4283description: t
4284when_to_use: tests
4285sections:
4286 - key: body
4287 heading: Body
4288 required: true
4289 search_weight: 10.0
4290 catch_all: true
4291 write_rules: []
4292metadata_fields:
4293 - key: status
4294 description: state
4295 field_type: string
4296 enum_values: [open, checked]
4297 optional: true
4298 - key: checked_by
4299 description: who
4300 field_type: string
4301 optional: true
4302title_weight: 100.0
4303text_fields:
4304 - body
4305hierarchy_relationship: PART_OF
4306no_self_loop_relationships: []
4307updatable_fields:
4308 - title
4309 - body
4310health_required_fields:
4311 - body
4312staleness_threshold_days: 90
4313required_outgoing:
4314 - relationships: [PART_OF]
4315 cardinality: at_least_one
4316 severity: block
4317constraints:
4318 - kind: requires_when
4319 field: checked_by
4320 when_field: status
4321 when_value: checked
4322 - kind: unique
4323 fields: [status, checked_by]
4324 - kind: enum_from_neighbour
4325 field: status
4326 rel_type: PART_OF
4327 section: body
4328 - kind: status_propagation
4329 field: status
4330 value: checked
4331 rel_type: PART_OF
4332 direction: incoming
4333write_rules: []
4334"#;
4335 let schema = Arc::new(
4336 memstead_schema::loader::load_schema_from_memory(
4337 manifest,
4338 &[("sample".to_string(), type_yaml.to_string())],
4339 )
4340 .expect("fixture loads"),
4341 );
4342
4343 let expected_constraints = serde_json::json!([
4348 {
4349 "kind": "requires_when",
4350 "field": "checked_by",
4351 "when_field": "status",
4352 "when_value": "checked",
4353 "severity": "warn",
4354 },
4355 {
4356 "kind": "unique",
4357 "fields": ["status", "checked_by"],
4358 "severity": "block",
4359 },
4360 {
4361 "kind": "enum_from_neighbour",
4362 "field": "status",
4363 "rel_type": "PART_OF",
4364 "section": "body",
4365 "severity": "warn",
4366 },
4367 {
4368 "kind": "status_propagation",
4369 "field": "status",
4370 "value": "checked",
4371 "rel_type": "PART_OF",
4372 "direction": "incoming",
4373 "severity": "warn",
4374 },
4375 ]);
4376
4377 let full = build_schema_payload(
4378 &schema,
4379 vec![],
4380 SchemaVerbosity::Full,
4381 OriginClass::FirstParty,
4382 );
4383 let t = &full["types"].as_array().unwrap()[0];
4384 assert_eq!(t["constraints"], expected_constraints);
4385 assert_eq!(t["required_outgoing"][0]["severity"], "block");
4386
4387 let lite = build_schema_payload(
4388 &schema,
4389 vec![],
4390 SchemaVerbosity::Lite,
4391 OriginClass::FirstParty,
4392 );
4393 let ts = &lite["types_summary"].as_array().unwrap()[0];
4394 assert_eq!(ts["constraints"], expected_constraints);
4395 assert_eq!(ts["required_outgoing"][0]["severity"], "block");
4396
4397 let fmt_manifest = r#"name: formatted
4400version: 1.0.0
4401description: format render fixture
4402when_to_use: render tests
4403types:
4404 - plan
4405relationships:
4406 mode: strict
4407 definitions:
4408 - name: PART_OF
4409 description: hier
4410 default_weight: 1.0
4411 - name: _default
4412 description: fallback
4413 default_weight: 1.0
4414community:
4415 resolution: 1.0
4416 seed: 42
4417"#;
4418 let fmt_type = r#"name: plan
4419description: t
4420when_to_use: tests
4421sections:
4422 - key: body
4423 heading: Body
4424 required: true
4425 search_weight: 10.0
4426 catch_all: true
4427 write_rules: []
4428 - key: meilensteine
4429 heading: Meilensteine
4430 required: false
4431 search_weight: 5.0
4432 catch_all: false
4433 write_rules: []
4434 content: "(heading(3) list(bullet))+"
4435 item_pattern: '\*\*(?<name>[^*]+)\*\*'
4436 example: |
4437 ### Phase 1
4438 - **Kickoff**
4439 format_severity: warn
4440 - key: tabelle
4441 heading: Tabelle
4442 required: false
4443 search_weight: 5.0
4444 catch_all: false
4445 write_rules: []
4446 content: "table"
4447 table:
4448 columns: [Name, Datum]
4449 column_patterns:
4450 Datum: '\d{4}-\d{2}-\d{2}'
4451 - key: belege
4452 heading: Belege
4453 required: false
4454 search_weight: 5.0
4455 catch_all: false
4456 write_rules: []
4457 content: "paragraph+"
4458 item_pattern: '(?<quelle>\S[^|]*?) \| (?<aussage>.+)'
4459metadata_fields: []
4460title_weight: 100.0
4461text_fields:
4462 - body
4463hierarchy_relationship: PART_OF
4464no_self_loop_relationships: []
4465updatable_fields:
4466 - title
4467 - body
4468health_required_fields:
4469 - body
4470staleness_threshold_days: 90
4471write_rules: []
4472"#;
4473 let fmt_schema = Arc::new(
4474 memstead_schema::loader::load_schema_from_memory(
4475 fmt_manifest,
4476 &[("plan".to_string(), fmt_type.to_string())],
4477 )
4478 .expect("format fixture loads"),
4479 );
4480 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4481 let payload =
4482 build_schema_payload(&fmt_schema, vec![], verbosity, OriginClass::FirstParty);
4483 let sections_key = match verbosity {
4484 SchemaVerbosity::Full => &payload["types"][0]["sections"],
4485 SchemaVerbosity::Lite => &payload["types_summary"][0]["sections"],
4486 };
4487 let secs = sections_key.as_array().unwrap();
4488 let meilensteine = secs
4489 .iter()
4490 .find(|s| s["key"] == "meilensteine")
4491 .expect("declared section present");
4492 assert_eq!(
4493 meilensteine["content"], "(heading(3) list(bullet))+",
4494 "{verbosity:?} carries content"
4495 );
4496 assert!(
4497 meilensteine["item_pattern"]
4498 .as_str()
4499 .unwrap()
4500 .contains("name")
4501 );
4502 assert!(
4503 meilensteine["example"]
4504 .as_str()
4505 .unwrap()
4506 .contains("Kickoff")
4507 );
4508 assert_eq!(meilensteine["format_severity"], "warn");
4509 let tabelle = secs.iter().find(|s| s["key"] == "tabelle").unwrap();
4510 assert_eq!(tabelle["format_severity"], "block", "default renders");
4511 assert_eq!(tabelle["table"]["columns"][0], "Name");
4512 assert!(
4513 tabelle["table"]["column_patterns"]["Datum"]
4514 .as_str()
4515 .is_some()
4516 );
4517 let belege = secs.iter().find(|s| s["key"] == "belege").unwrap();
4518 assert_eq!(belege["content"], "paragraph+");
4519 assert!(belege["item_pattern"].as_str().unwrap().contains("quelle"));
4520 let body = secs.iter().find(|s| s["key"] == "body").unwrap();
4521 assert!(
4522 body.get("content").is_none() && body.get("format_severity").is_none(),
4523 "undeclared section keeps its pre-plan shape"
4524 );
4525 }
4526
4527 let plain_full = build_schema_payload(
4530 &software_schema(),
4531 vec![],
4532 SchemaVerbosity::Full,
4533 OriginClass::FirstParty,
4534 );
4535 let pt = &plain_full["types"].as_array().unwrap()[0];
4536 assert_eq!(pt["constraints"], serde_json::json!([]));
4537 let plain_lite = build_schema_payload(
4538 &software_schema(),
4539 vec![],
4540 SchemaVerbosity::Lite,
4541 OriginClass::FirstParty,
4542 );
4543 let pts = &plain_lite["types_summary"].as_array().unwrap()[0];
4544 assert_eq!(pts["constraints"], serde_json::json!([]));
4545 }
4546
4547 #[test]
4557 fn third_party_origin_forces_structural_only_even_under_full() {
4558 let schema = software_schema();
4559 let full_requested = build_schema_payload(
4560 &schema,
4561 vec!["v".into()],
4562 SchemaVerbosity::Full,
4563 OriginClass::ThirdParty,
4564 );
4565
4566 assert_eq!(full_requested["origin"], "third-party");
4568
4569 assert!(
4572 full_requested.get("types").is_none(),
4573 "third-party omits the rich `types` array even under full"
4574 );
4575 assert!(
4576 full_requested.get("relationships").is_none(),
4577 "third-party omits the rich `relationships` array even under full"
4578 );
4579 assert!(
4580 full_requested["types_summary"].is_array(),
4581 "third-party serves the structural `types_summary` skeleton"
4582 );
4583 assert!(
4584 full_requested["relationships_summary"].is_array(),
4585 "third-party serves the structural `relationships_summary` skeleton"
4586 );
4587
4588 assert!(
4590 full_requested.get("description").is_none(),
4591 "third-party drops schema description prose"
4592 );
4593 assert!(
4594 full_requested.get("when_to_use").is_none(),
4595 "third-party drops schema when_to_use prose"
4596 );
4597 assert!(
4598 full_requested.get("default_writing_guidance").is_none(),
4599 "third-party drops default_writing_guidance prose"
4600 );
4601
4602 for t in full_requested["types_summary"].as_array().unwrap() {
4604 assert!(
4605 t.get("system_context").is_none(),
4606 "third-party drops system_context"
4607 );
4608 assert!(
4609 t.get("writing_guidance").is_none(),
4610 "third-party drops writing_guidance"
4611 );
4612 assert!(
4613 t.get("description").is_none(),
4614 "third-party drops type description"
4615 );
4616 for s in t["sections"].as_array().unwrap() {
4617 assert!(
4618 s.get("write_rules").is_none(),
4619 "third-party drops section write_rules"
4620 );
4621 }
4622 }
4623 for r in full_requested["relationships_summary"].as_array().unwrap() {
4625 assert!(
4626 r.get("description").is_none(),
4627 "third-party drops rel description"
4628 );
4629 assert!(
4630 r.get("when_to_use").is_none(),
4631 "third-party drops rel when_to_use"
4632 );
4633 }
4634
4635 let lite_requested = build_schema_payload(
4639 &schema,
4640 vec!["v".into()],
4641 SchemaVerbosity::Lite,
4642 OriginClass::ThirdParty,
4643 );
4644 assert_eq!(
4645 full_requested, lite_requested,
4646 "third-party full must collapse to the lite skeleton"
4647 );
4648 }
4649
4650 #[test]
4651 fn full_payload_carries_the_rich_arrays_and_prose() {
4652 let schema = software_schema();
4653 let full = build_schema_payload(
4654 &schema,
4655 vec!["v".into()],
4656 SchemaVerbosity::Full,
4657 OriginClass::FirstParty,
4658 );
4659
4660 assert!(full["types"].is_array(), "full has `types`");
4662 assert!(full["relationships"].is_array(), "full has `relationships`");
4663 assert!(
4664 full.get("types_summary").is_none(),
4665 "full omits `types_summary`"
4666 );
4667 assert!(
4668 full.get("relationships_summary").is_none(),
4669 "full omits `relationships_summary`"
4670 );
4671 assert!(
4672 full["description"].is_string(),
4673 "full keeps schema description"
4674 );
4675 assert!(
4676 full["when_to_use"].is_string(),
4677 "full keeps schema when_to_use"
4678 );
4679 assert_eq!(full["alias_target_rel_type"], "REFERENCES");
4680
4681 let t = &full["types"].as_array().unwrap()[0];
4683 assert!(t["description"].is_string());
4684 assert!(t.get("writing_guidance").is_some());
4685 assert!(t.get("system_context").is_some());
4686 let r = &full["relationships"].as_array().unwrap()[0];
4688 assert!(r["description"].is_string());
4689 assert!(r.get("when_to_use").is_some());
4690 assert!(r.get("default_weight").is_some());
4691 }
4692
4693 #[test]
4702 fn required_outgoing_reported_with_cardinality_at_both_levels() {
4703 let reg = memstead_schema::SchemaRegistry::builtin();
4704 let project = reg
4705 .get("project", &semver::Version::new(0, 2, 0))
4706 .expect("project is a built-in");
4707
4708 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4709 let payload =
4710 build_schema_payload(&project, vec![], verbosity, OriginClass::FirstParty);
4711 let types_key = if verbosity == SchemaVerbosity::Full {
4712 "types"
4713 } else {
4714 "types_summary"
4715 };
4716 let types = payload[types_key].as_array().expect("types array");
4717
4718 let mut saw_evidence = false;
4719 let mut saw_memo = false;
4720 for t in types {
4721 let ro = t
4722 .get("required_outgoing")
4723 .unwrap_or_else(|| panic!("type {} omits required_outgoing", t["name"]))
4724 .as_array()
4725 .expect("required_outgoing is an array for every type");
4726 if t["name"] == "evidence" {
4727 saw_evidence = true;
4728 assert_eq!(ro.len(), 1, "evidence declares one block");
4729 assert_eq!(
4730 ro[0]["relationships"],
4731 serde_json::json!(["STRENGTHENS", "WEAKENS", "VALIDATES", "CONTRADICTS"]),
4732 "relationship alternatives in declaration order"
4733 );
4734 assert_eq!(
4735 ro[0]["cardinality"], "at_least_one",
4736 "cardinality rendered as declared — the open upper bound \
4737 stays open, never a finite number"
4738 );
4739 } else if t["name"] == "memo" {
4740 saw_memo = true;
4743 assert!(ro.is_empty(), "memo declares no blocks → empty list");
4744 }
4745 }
4746 assert!(saw_evidence, "project schema carries the evidence type");
4747 assert!(saw_memo, "project schema carries the memo type");
4748
4749 let note = payload["no_self_loop_relationships_effect"]
4752 .as_str()
4753 .expect("effect note present at both verbosity levels");
4754 assert!(note.contains("self-loop"), "names the actual effect");
4755 assert!(
4756 !note.contains("propagates impact") || note.contains("does not propagate"),
4757 "claims no propagation behaviour beyond the self-loop refusal"
4758 );
4759 assert!(
4760 note.contains("status_propagation"),
4761 "deprecation pointer names the real propagation declaration"
4762 );
4763 }
4764 }
4765
4766 #[test]
4772 fn conditional_required_outgoing_trigger_visible_at_both_levels() {
4773 let manifest = r#"name: condro-render
4774version: 0.1.0
4775description: conditional required_outgoing render fixture
4776when_to_use: tests
4777types:
4778 - task
4779relationships:
4780 mode: strict
4781 definitions:
4782 - name: PART_OF
4783 description: hier
4784 default_weight: 3.0
4785 - name: _default
4786 description: fallback
4787 default_weight: 1.0
4788community:
4789 resolution: 1.0
4790 seed: 42
4791"#;
4792 let task_yaml = "name: task\ndescription: t\nwhen_to_use: tests\nsections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\nmetadata_fields:\n - key: status\n description: workflow state\n field_type: string\n enum_values: [open, checked]\ntitle_weight: 100.0\ntext_fields:\n - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n - title\n - body\n - status\nhealth_required_fields:\n - body\nstaleness_threshold_days: 90\nwrite_rules: []\nrequired_outgoing:\n - relationships: [PART_OF]\n cardinality: at_least_one\n - relationships: [PART_OF]\n cardinality: at_least_one\n severity: block\n when_field: status\n when_value: checked\n";
4793 let schema = Arc::new(
4794 memstead_schema::load_schema_from_memory(
4795 manifest,
4796 &[("task".to_string(), task_yaml.to_string())],
4797 )
4798 .expect("render fixture schema must parse"),
4799 );
4800
4801 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4802 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
4803 let types_key = if verbosity == SchemaVerbosity::Full {
4804 "types"
4805 } else {
4806 "types_summary"
4807 };
4808 let task = &payload[types_key].as_array().expect("types array")[0];
4809 let ro = task["required_outgoing"].as_array().expect("blocks array");
4810 assert_eq!(ro.len(), 2);
4811 assert!(
4812 ro[0].get("when_field").is_none() && ro[0].get("when_value").is_none(),
4813 "unconditional block carries no when_* keys: {:?}",
4814 ro[0]
4815 );
4816 assert_eq!(ro[1]["when_field"], "status");
4817 assert_eq!(ro[1]["when_value"], "checked");
4818 }
4819 }
4820
4821 #[test]
4827 fn acyclic_sets_and_propagation_rel_types_visible_at_both_levels() {
4828 let manifest = r#"name: relsets-render
4829version: 0.1.0
4830description: relation-set render fixture
4831when_to_use: tests
4832types:
4833 - claim
4834relationships:
4835 mode: strict
4836 acyclic_sets:
4837 - [GROUNDS, CONCLUDES]
4838 definitions:
4839 - name: GROUNDS
4840 description: g
4841 default_weight: 3.0
4842 - name: CONCLUDES
4843 description: c
4844 default_weight: 3.0
4845 - name: PART_OF
4846 description: hier
4847 default_weight: 1.0
4848 - name: _default
4849 description: fallback
4850 default_weight: 1.0
4851community:
4852 resolution: 1.0
4853 seed: 42
4854"#;
4855 let claim = "name: claim\ndescription: t\nwhen_to_use: tests\nsections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\nmetadata_fields:\n - key: standing\n description: s\n field_type: string\n enum_values: [active, withdrawn]\ntitle_weight: 100.0\ntext_fields:\n - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n - title\n - body\n - standing\nhealth_required_fields:\n - body\nstaleness_threshold_days: 90\nwrite_rules: []\nconstraints:\n - kind: status_propagation\n field: standing\n value: withdrawn\n rel_types: [GROUNDS, CONCLUDES]\n direction: incoming\n - kind: status_propagation\n field: standing\n value: withdrawn\n rel_type: PART_OF\n direction: outgoing\n";
4856 let schema = Arc::new(
4857 memstead_schema::load_schema_from_memory(
4858 manifest,
4859 &[("claim".to_string(), claim.to_string())],
4860 )
4861 .expect("render fixture schema must parse"),
4862 );
4863
4864 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4865 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
4866 assert_eq!(
4867 payload["acyclic_sets"],
4868 serde_json::json!([["GROUNDS", "CONCLUDES"]]),
4869 "acyclic_sets present at {verbosity:?}"
4870 );
4871 let types_key = if verbosity == SchemaVerbosity::Full {
4872 "types"
4873 } else {
4874 "types_summary"
4875 };
4876 let claim = &payload[types_key].as_array().expect("types array")[0];
4877 let constraints = claim["constraints"].as_array().expect("constraints array");
4878 assert_eq!(
4879 constraints[0]["rel_types"],
4880 serde_json::json!(["GROUNDS", "CONCLUDES"])
4881 );
4882 assert!(
4883 constraints[0].get("rel_type").is_none(),
4884 "set declaration carries no single-name key: {:?}",
4885 constraints[0]
4886 );
4887 assert_eq!(constraints[1]["rel_type"], "PART_OF");
4888 assert!(
4889 constraints[1].get("rel_types").is_none(),
4890 "single-name declaration stays byte-identical: {:?}",
4891 constraints[1]
4892 );
4893 }
4894
4895 let plain = software_schema();
4897 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4898 let payload = build_schema_payload(&plain, vec![], verbosity, OriginClass::FirstParty);
4899 assert!(
4900 payload.get("acyclic_sets").is_none(),
4901 "undeclared schema carries no acyclic_sets key"
4902 );
4903 }
4904 }
4905
4906 #[test]
4910 fn labelling_declaration_visible_at_both_levels_and_absent_when_undeclared() {
4911 let manifest = r#"name: labelling-render
4912version: 0.1.0
4913description: labelling render fixture
4914when_to_use: tests
4915types:
4916 - claim
4917relationships:
4918 mode: strict
4919 labelling:
4920 attack: [REBUTS]
4921 support:
4922 relationships: [GROUNDS]
4923 direction: out
4924 terminal_types: [claim]
4925 definitions:
4926 - name: REBUTS
4927 description: attack
4928 default_weight: 3.0
4929 - name: GROUNDS
4930 description: support
4931 default_weight: 3.0
4932 - name: PART_OF
4933 description: hier
4934 default_weight: 1.0
4935 - name: _default
4936 description: fallback
4937 default_weight: 1.0
4938community:
4939 resolution: 1.0
4940 seed: 42
4941"#;
4942 let claim = "name: claim\ndescription: t\nwhen_to_use: tests\nmetadata_fields: []\nsections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\ntitle_weight: 100.0\ntext_fields:\n - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n - title\n - body\nhealth_required_fields:\n - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
4943 let schema = Arc::new(
4944 memstead_schema::load_schema_from_memory(
4945 manifest,
4946 &[("claim".to_string(), claim.to_string())],
4947 )
4948 .expect("render fixture schema must parse"),
4949 );
4950
4951 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4952 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
4953 assert_eq!(
4954 payload["labelling"]["attack"],
4955 serde_json::json!(["REBUTS"]),
4956 "attack set present at {verbosity:?}"
4957 );
4958 assert_eq!(
4959 payload["labelling"]["support"]["relationships"],
4960 serde_json::json!(["GROUNDS"])
4961 );
4962 assert_eq!(payload["labelling"]["support"]["direction"], "out");
4963 }
4964
4965 let plain = software_schema();
4966 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
4967 let payload = build_schema_payload(&plain, vec![], verbosity, OriginClass::FirstParty);
4968 assert!(
4969 payload.get("labelling").is_none(),
4970 "undeclared schema carries no labelling key"
4971 );
4972 }
4973 }
4974
4975 #[test]
4979 fn signal_declarations_visible_at_both_levels_and_absent_when_undeclared() {
4980 let manifest = r#"name: signals-render
4981version: 0.1.0
4982description: signal render fixture
4983when_to_use: tests
4984types:
4985 - claim
4986 - objection
4987relationships:
4988 mode: strict
4989 definitions:
4990 - name: REBUTS
4991 description: r
4992 default_weight: 3.0
4993 - name: PART_OF
4994 description: hier
4995 default_weight: 1.0
4996 - name: _default
4997 description: fallback
4998 default_weight: 1.0
4999community:
5000 resolution: 1.0
5001 seed: 42
5002"#;
5003 let body = "sections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\ntitle_weight: 100.0\ntext_fields:\n - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n - title\n - body\nhealth_required_fields:\n - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
5004 let claim = format!(
5005 "name: claim\ndescription: t\nwhen_to_use: tests\nmetadata_fields: []\n{body}signals:\n - name: attack_load\n kind: edge_load\n relationships: [REBUTS]\n direction: in\n thresholds:\n - at_least: 1\n level: notice\n - at_least: 3\n level: warn\n"
5006 );
5007 let objection = format!(
5008 "name: objection\ndescription: t\nwhen_to_use: tests\nmetadata_fields:\n - key: state\n description: s\n field_type: string\n enum_values: [open, closed]\n{body}"
5009 );
5010 let schema = Arc::new(
5011 memstead_schema::load_schema_from_memory(
5012 manifest,
5013 &[
5014 ("claim".to_string(), claim),
5015 ("objection".to_string(), objection),
5016 ],
5017 )
5018 .expect("render fixture schema must parse"),
5019 );
5020
5021 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
5022 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
5023 let types_key = if verbosity == SchemaVerbosity::Full {
5024 "types"
5025 } else {
5026 "types_summary"
5027 };
5028 let types = payload[types_key].as_array().expect("types array");
5029 let claim = types
5030 .iter()
5031 .find(|t| t["name"] == "claim")
5032 .expect("claim type present");
5033 let sigs = claim["signals"].as_array().expect("signals array");
5034 assert_eq!(sigs[0]["name"], "attack_load");
5035 assert_eq!(sigs[0]["kind"], "edge_load");
5036 assert_eq!(sigs[0]["direction"], "in");
5037 assert_eq!(sigs[0]["thresholds"][1]["at_least"], 3);
5038 assert_eq!(sigs[0]["thresholds"][1]["level"], "warn");
5039 let objection = types
5040 .iter()
5041 .find(|t| t["name"] == "objection")
5042 .expect("objection type present");
5043 assert!(
5044 objection.get("signals").is_none(),
5045 "undeclared type carries no signals key"
5046 );
5047 }
5048 }
5049
5050 #[test]
5056 fn must_reach_visible_at_both_levels_and_absent_when_undeclared() {
5057 let manifest = r#"name: mustreach-render
5058version: 0.1.0
5059description: must_reach render fixture
5060when_to_use: tests
5061types:
5062 - claim
5063 - evidence
5064relationships:
5065 mode: strict
5066 definitions:
5067 - name: GROUNDS
5068 description: g
5069 default_weight: 3.0
5070 - name: PART_OF
5071 description: hier
5072 default_weight: 1.0
5073 - name: _default
5074 description: fallback
5075 default_weight: 1.0
5076community:
5077 resolution: 1.0
5078 seed: 42
5079"#;
5080 let body = "sections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n - title\n - body\nhealth_required_fields:\n - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
5081 let claim = format!(
5082 "name: claim\ndescription: t\nwhen_to_use: tests\n{body}must_reach:\n - relationships: [GROUNDS]\n direction: out\n terminal_types: [evidence]\n max_depth: 12\n"
5083 );
5084 let evidence = format!("name: evidence\ndescription: t\nwhen_to_use: tests\n{body}");
5085 let schema = Arc::new(
5086 memstead_schema::load_schema_from_memory(
5087 manifest,
5088 &[
5089 ("claim".to_string(), claim),
5090 ("evidence".to_string(), evidence),
5091 ],
5092 )
5093 .expect("render fixture schema must parse"),
5094 );
5095
5096 for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
5097 let payload = build_schema_payload(&schema, vec![], verbosity, OriginClass::FirstParty);
5098 let types_key = if verbosity == SchemaVerbosity::Full {
5099 "types"
5100 } else {
5101 "types_summary"
5102 };
5103 let types = payload[types_key].as_array().expect("types array");
5104 let claim = types
5105 .iter()
5106 .find(|t| t["name"] == "claim")
5107 .expect("claim type present");
5108 let mr = claim["must_reach"].as_array().expect("obligations array");
5109 assert_eq!(mr.len(), 1);
5110 assert_eq!(mr[0]["relationships"], serde_json::json!(["GROUNDS"]));
5111 assert_eq!(mr[0]["direction"], "out");
5112 assert_eq!(mr[0]["terminal_types"], serde_json::json!(["evidence"]));
5113 assert_eq!(mr[0]["max_depth"], 12);
5114 let evidence = types
5115 .iter()
5116 .find(|t| t["name"] == "evidence")
5117 .expect("evidence type present");
5118 assert!(
5119 evidence.get("must_reach").is_none(),
5120 "undeclared type carries no must_reach key: {evidence:?}"
5121 );
5122 }
5123 }
5124
5125 #[test]
5126 fn lite_payload_is_the_structural_skeleton_without_prose() {
5127 let schema = software_schema();
5128 let lite = build_schema_payload(
5129 &schema,
5130 vec!["v".into()],
5131 SchemaVerbosity::Lite,
5132 OriginClass::FirstParty,
5133 );
5134
5135 let types = lite["types_summary"]
5137 .as_array()
5138 .expect("lite has `types_summary`");
5139 let rels = lite["relationships_summary"]
5140 .as_array()
5141 .expect("lite has `relationships_summary`");
5142 assert!(lite.get("types").is_none(), "lite omits rich `types`");
5143 assert!(
5144 lite.get("relationships").is_none(),
5145 "lite omits rich `relationships`"
5146 );
5147
5148 assert_eq!(lite["alias_target_rel_type"], "REFERENCES");
5151
5152 assert!(
5154 lite.get("description").is_none(),
5155 "lite drops schema description"
5156 );
5157 assert!(
5158 lite.get("when_to_use").is_none(),
5159 "lite drops schema when_to_use"
5160 );
5161 assert!(
5162 lite.get("default_writing_guidance").is_none(),
5163 "lite drops default_writing_guidance"
5164 );
5165
5166 for t in types {
5169 assert!(t["name"].is_string());
5170 let sections = t["sections"].as_array().expect("lite type has sections");
5171 for s in sections {
5172 assert!(s["key"].is_string(), "section carries its key");
5173 assert!(s["required"].is_boolean(), "section carries required flag");
5174 assert!(
5175 s.get("write_rules").is_none(),
5176 "lite section drops write_rules prose"
5177 );
5178 assert!(s.get("heading").is_none(), "lite section drops heading");
5179 }
5180 assert!(
5181 t.get("description").is_none(),
5182 "lite type drops description"
5183 );
5184 assert!(
5185 t.get("writing_guidance").is_none(),
5186 "lite type drops writing_guidance"
5187 );
5188 assert!(
5189 t.get("system_context").is_none(),
5190 "lite type drops system_context"
5191 );
5192 assert!(
5196 t.get("no_self_loop_relationships").is_some(),
5197 "lite type keeps no_self_loop_relationships"
5198 );
5199 assert!(
5203 t.get("required_outgoing").is_some_and(|v| v.is_array()),
5204 "lite type keeps required_outgoing as an array"
5205 );
5206 if let Some(fields) = t["fields"].as_array() {
5208 for f in fields {
5209 assert!(f["name"].is_string());
5210 assert!(f["required"].is_boolean());
5211 assert!(
5212 f.get("description").is_none(),
5213 "lite field drops description"
5214 );
5215 }
5216 }
5217 }
5218
5219 for r in rels {
5222 assert!(r["name"].is_string());
5223 assert!(
5224 r.get("allowed_sources").is_some(),
5225 "lite rel has allowed_sources"
5226 );
5227 assert!(
5228 r.get("allowed_targets").is_some(),
5229 "lite rel has allowed_targets"
5230 );
5231 assert!(
5232 r.get("manual_authoring").is_some(),
5233 "lite rel keeps manual_authoring"
5234 );
5235 assert!(r.get("acyclic").is_some(), "lite rel keeps acyclic");
5236 assert!(
5237 r.get("per_edge_description").is_some(),
5238 "lite rel keeps per_edge_description"
5239 );
5240 assert!(r.get("description").is_none(), "lite rel drops description");
5241 assert!(r.get("when_to_use").is_none(), "lite rel drops when_to_use");
5242 assert!(
5243 r.get("default_weight").is_none(),
5244 "lite rel drops default_weight"
5245 );
5246 }
5247 }
5248
5249 #[test]
5250 fn lite_is_measurably_smaller_than_full() {
5251 let schema = software_schema();
5252 let full = build_schema_payload(
5253 &schema,
5254 vec!["v".into()],
5255 SchemaVerbosity::Full,
5256 OriginClass::FirstParty,
5257 );
5258 let lite = build_schema_payload(
5259 &schema,
5260 vec!["v".into()],
5261 SchemaVerbosity::Lite,
5262 OriginClass::FirstParty,
5263 );
5264 let full_len = serde_json::to_string(&full).unwrap().len();
5265 let lite_len = serde_json::to_string(&lite).unwrap().len();
5266 assert!(
5267 lite_len * 2 < full_len,
5268 "lite ({lite_len} B) must be well under half of full ({full_len} B)"
5269 );
5270 }
5271
5272 #[test]
5273 fn lite_full_carry_the_same_type_and_rel_names() {
5274 let schema = software_schema();
5277 let full = build_schema_payload(
5278 &schema,
5279 vec!["v".into()],
5280 SchemaVerbosity::Full,
5281 OriginClass::FirstParty,
5282 );
5283 let lite = build_schema_payload(
5284 &schema,
5285 vec!["v".into()],
5286 SchemaVerbosity::Lite,
5287 OriginClass::FirstParty,
5288 );
5289
5290 let names = |arr: &serde_json::Value| -> Vec<String> {
5291 arr.as_array()
5292 .unwrap()
5293 .iter()
5294 .map(|v| v["name"].as_str().unwrap().to_string())
5295 .collect()
5296 };
5297 assert_eq!(names(&full["types"]), names(&lite["types_summary"]));
5298 assert_eq!(
5299 names(&full["relationships"]),
5300 names(&lite["relationships_summary"])
5301 );
5302 }
5303
5304 #[test]
5309 fn swallowed_sections_carry_a_marker_on_the_plain_read() {
5310 let mut e = test_entity();
5311 e.sections.insert(
5312 "identity".to_string(),
5313 "intro\n\n```rust\nfn main() {}".to_string(),
5314 );
5315 e.sections.insert("purpose".to_string(), String::new());
5316 let env = build_entity_envelope(
5317 &e,
5318 10,
5319 None,
5320 None,
5321 None,
5322 OriginClass::FirstParty,
5323 &[],
5324 None,
5325 None,
5326 None,
5327 );
5328 let marker = &env["_unread_sections"];
5329 assert_eq!(marker["reason"], "UNTERMINATED_FENCE");
5330 assert_eq!(marker["absorbed_into"], "identity");
5331 assert_eq!(marker["sections"], serde_json::json!(["purpose"]));
5332 }
5333
5334 #[test]
5335 fn an_ordinary_entity_carries_no_unread_marker() {
5336 for body in ["plain prose", "```rust\nfn main() {}\n```"] {
5340 let mut e = test_entity();
5341 e.sections.insert("identity".to_string(), body.to_string());
5342 e.sections.insert("purpose".to_string(), String::new());
5343 let env = build_entity_envelope(
5344 &e,
5345 10,
5346 None,
5347 None,
5348 None,
5349 OriginClass::FirstParty,
5350 &[],
5351 None,
5352 None,
5353 None,
5354 );
5355 assert!(
5356 env.get("_unread_sections").is_none(),
5357 "body {body:?} produced a marker"
5358 );
5359 }
5360 }
5361}