Skip to main content

memstead_base/
render.rs

1//! Markdown rendering of Engine result types.
2//!
3//! Shared by `memstead-mcp` (wraps output in MCP `CallToolResult`) and
4//! `memstead-cli` (prints directly to stdout).
5
6use 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
24// ---------------------------------------------------------------------------
25// Entity rendering
26// ---------------------------------------------------------------------------
27
28/// Render a single entity as markdown with frontmatter metadata.
29///
30/// Projection-free by contract: this is the canonical form (anchor
31/// hashing, export, parser round-trips). Serving surfaces that
32/// present declared signals or the grounded labelling call
33/// [`render_entity_markdown_with_signals`] instead — computed values
34/// are a projection and must never enter the canonical bytes.
35pub fn render_entity_markdown(entity: &Entity, sections_filter: Option<&[String]>) -> String {
36    render_entity_markdown_with_signals(entity, sections_filter, None, None)
37}
38
39/// Serving-surface variant of [`render_entity_markdown`]: when the
40/// entity's type declares signals, the headline (`name`, `value`,
41/// `level` per signal) rides in the frontmatter block — the one
42/// pre-body slot the format has — and the contributors in a
43/// `## Signals` section appended after the body, in the style of
44/// `## Relations`. When the mem's schema declares labelling, the
45/// grounded label rides as `_label` in the frontmatter and the
46/// evidence in a `## Labelling` section. `None`/`None` renders
47/// byte-identically to the canonical form.
48pub 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    // Frontmatter — _tokens reflects the rendered output, not the full entity.
57    let mut lines = Vec::new();
58    lines.push("---".to_string());
59    lines.push(format!("_hash: {}", entity.content_hash));
60    // Typed stub provenance — only emitted when the entity carries
61    // a `stub_kind` (real entities are absent from this surface).
62    // Agents reading a stub three calls after the mutation that
63    // produced it recover the diagnostic context that the
64    // mutation-time warning carried.
65    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    // Signal headline — name, value, level per declared signal, in
90    // declaration order. The contributors ride in the appended
91    // `## Signals` section below, never here.
92    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    // Grounded-label headline; the evidence rides in the appended
102    // `## Labelling` section below.
103    if let Some(lab) = labelling {
104        lines.push(format!("_label: {}", lab.label.wire()));
105    }
106    // The text channel's half of `_unread_sections`. The JSON envelope carries
107    // the structured block; a reader on this channel sees the same sections
108    // rendered blank and, without this line, has nothing to tell them apart
109    // from sections the author left empty. This is the channel a cold agent
110    // reads, so it cannot be the one that stays quiet.
111    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    // When sections are filtered and some were excluded, show full entity size
132    // so agents know how much they're missing.
133    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    // Emit entity metadata. Same predicate as the JSON envelope's
144    // metadata map: `_`-prefixed keys are computed read-channel slots
145    // (the `_hash` line above, `_tokens`, `_signals`, ...) and the
146    // reserved triple is structural identity — a stored key in either
147    // namespace would render as a second, stale copy beside the
148    // computed one.
149    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    // Contributors — the evidence ships with the number, always. One
163    // bullet per signal, mirroring the `## Relations` append style.
164    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    // Labelling evidence — a defeated label always carries its
191    // accepted direct attackers (one unanswered counter-claim
192    // flipping a well-supported claim is visible as exactly that);
193    // an undecided label the open attacker set that keeps it open.
194    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
223/// Token estimate for an entity's rendered body (title + sections +
224/// relationships, filter applied) — the exact number `render_entity_markdown`
225/// embeds as its frontmatter `_tokens`. Use this when building a structured
226/// envelope so the envelope's `_tokens` and the markdown channel's frontmatter
227/// `_tokens` describe the *same* thing for a given `_hash`: the rendered body,
228/// not the full markdown document (which would additionally count frontmatter).
229pub fn rendered_body_tokens(entity: &Entity, sections_filter: Option<&[String]>) -> usize {
230    estimate_tokens(&render_entity_body(entity, sections_filter))
231}
232
233/// Build the body (title + sections + relationships) for an entity, optionally filtered.
234///
235/// Section iteration order follows `entity.sections` — an `IndexMap`, so
236/// insertion order is the authoritative render order. The parser inserts keys
237/// in the schema's declared order, which is what ships to clients. Do not
238/// migrate `entity.sections` back to `HashMap`.
239fn 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    // Look up the entity's TypeDefinition across every built-in schema
246    // so non-default schemas (e.g. `ingest.inconsistency`) get their
247    // declared headings rendered exactly as the on-disk markdown
248    // emitted them. Falls back to key→heading derivation when no
249    // built-in schema declares this type — preserves the prior shape
250    // for custom workspace schemas not yet bridged through the
251    // renderer.
252    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            // Mirror the on-disk renderer (`entity::generator`):
274            // canonical em-dash delimiter when the relation carries a
275            // per-edge description, simple form otherwise.
276            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
295/// Render a `## Relations` section as markdown — typed edges grouped by
296/// direction. Appended to `memstead_entity` output when `include_relations: true`.
297/// A JSON-shaped version is available via `render_relations_json` for the
298/// `memstead-cli relations --json` consumer.
299pub 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
334/// Render outgoing/incoming relations as a JSON envelope. Consumed by
335/// `memstead-cli relations --json`; no MCP path uses it.
336pub 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
370// ---------------------------------------------------------------------------
371// Search / List rendering
372// ---------------------------------------------------------------------------
373
374/// Render search results as markdown.
375pub 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        // Render each search warning with its typed code as the lead — same
388        // shape mutation-tool `## Warnings` blocks already use — so an
389        // agent reading the markdown sees the code without decoding
390        // the structured channel.
391        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
431/// Render the `## Facets` block for a `SearchResult`. Returns `None` when
432/// every facet bucket is empty — callers elide the section entirely in
433/// that case. Buckets with mixed presence each ship independently.
434///
435/// Ordering: keys inside a bucket sort by count desc, then key asc so the
436/// output is deterministic for tests. `by_subsection` uses its native
437/// stored order (already sorted by count desc in `ops::search`).
438fn 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
489/// Render the `**Matched terms:**` line for one hit. `matched_terms`
490/// groups `TermMatch`es per query term; output is one `term (field×N, ...)`
491/// group per term, joined with `, `. Terms and fields both sort
492/// alphabetically for deterministic output.
493fn 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
516/// Render the `**Score:**` line from a `ScoreBreakdown`. Fields render as
517/// `bm25 X.X + title X.X + <field> X.X [+ expansion_decay ×X.X]`. Zero-
518/// valued components still ship — the breakdown is informational, and the
519/// composition "title 0.0" is itself a fact worth surfacing.
520fn 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
536/// Render the `**Heading path:**` line for one hit. Collects distinct
537/// non-empty `heading_path`s across the hit's `TermMatch`es. Single path
538/// renders inline (`A › B`), multiple paths render as `A › B; C › D`.
539fn 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
561/// Render the `**Expansion:**` line for one hit — `from <id> via <edge>
562/// [out|in] (depth N)`. The direction rides wherever the label does,
563/// so a `both` walk stays interpretable per hit.
564fn 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        // A concrete reaching edge always has one direction; `Both`
570        // cannot occur here by construction.
571        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
579/// Render list results as markdown.
580pub 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
616// ---------------------------------------------------------------------------
617// Context / Overview rendering
618// ---------------------------------------------------------------------------
619
620/// Render a `## Community Context` section — cluster id + neighbor list —
621/// appended to `memstead_entity` output when `include_context: true`. No
622/// frontmatter; the entity body owns that.
623pub 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
649/// Render context (community cluster) as markdown.
650pub 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    // Neighbors grouped by direction
661    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
677/// Render overview (all clusters) as markdown. `store` provides entity titles
678/// for the on-the-fly auto-summary (title-join) — there is no stored summary.
679pub 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    // Use compact formatting to match JS: "0" instead of "0.0000"
688    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    // Sort clusters by ID for deterministic output
698    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// ---------------------------------------------------------------------------
722// JSON envelopes for search / list — consumed by `memstead-cli` only
723// ---------------------------------------------------------------------------
724//
725// These wrap the core `SearchResult` / `ListResult` with precomputed
726// `summary_heading` / `summary_value` per hit — the same values the
727// markdown renderer emits — so the CLI's `--json` output doesn't
728// reimplement schema lead-section lookup. The MCP side carries no JSON
729// sidecar; these envelopes remain on the `memstead-cli search --json` /
730// `memstead-cli list --json` path.
731//
732// Snake-case field names are intentional: they match on-disk YAML and the
733// core `SearchHit` struct. Do not add `rename_all = "camelCase"`.
734
735/// Envelope wrapping a `SearchHit` with precomputed summary fields.
736#[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    /// Data-origin label of the hit's mem: `first-party` for a writable
743    /// workspace mem, `third-party` for a read-only mount (an installed
744    /// read-mem, an adopted foreign folder). Stamped here, once, so the
745    /// CLI `--json` and the MCP `structured_content` carry the same key.
746    pub origin: &'static str,
747}
748
749/// Envelope for a full `SearchResult`:
750/// `_-prefixed` engine-emitted counters at the top level, `facets`
751/// as a structured object (not a markdown blob), and the full per-hit
752/// shape (score, score_breakdown, matched_terms, expansion) inherited
753/// verbatim from `SearchHit` so the structured envelope is the
754/// branching surface — agents reading `structured_content` don't have
755/// to parse the text channel's rendered prose to recover scores or
756/// score components. CLI `--json` and MCP `structured_content` share
757/// this shape.
758#[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    /// Sum of estimated tokens across all matching entities (pre-pagination).
767    /// Mirrors `ListResultEnvelope.total_tokens` so the field has consistent
768    /// meaning across both surfaces — migration cost for agents is zero.
769    #[serde(rename = "_total_tokens")]
770    pub total_tokens: usize,
771    pub hits: Vec<SearchHitEnvelope<'a>>,
772    /// Faceted counts over the unpaginated hit set. Skipped on the
773    /// wire when the engine produced no facets (rare; the unified
774    /// engine always populates an empty `Facets::default()` for
775    /// shape stability).
776    #[serde(skip_serializing_if = "Option::is_none")]
777    pub facets: Option<&'a Facets>,
778    /// Always on the wire, `[]` when nothing warned: the envelope is one
779    /// stable shape, so a consumer reads `warnings` without testing for
780    /// the key first.
781    pub warnings: &'a Vec<crate::ops::WarningHint>,
782}
783
784/// Envelope for a full `ListResult`. The engine-meta counters carry the
785/// same `_`-prefixed wire keys as [`SearchResultEnvelope`] (and as both
786/// surfaces' markdown form) so an agent moving between `memstead list --json`
787/// and `memstead search --json` parses one envelope-meta convention. The
788/// `_` prefix reads as "engine-meta, not entity content".
789#[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    /// Always on the wire, `[]` when nothing warned (as on the search
801    /// envelope).
802    pub warnings: &'a Vec<crate::ops::WarningHint>,
803}
804
805/// Build the structured `memstead_entity` envelope. Identity fields
806/// (`_hash`, `id`, `mem`, `entity_type`, `title`, `_stub_kind`) come from the
807/// parsed `Entity` and live at the top level. Every schema-declared frontmatter
808/// key surfaces under a nested `metadata: {...}` map — its single home.
809/// Read a metadata
810/// value as `envelope.metadata.<key>`; generic consumers iterate the map
811/// without per-type branching. The prior shape additionally hoisted
812/// `level`/`stability`/`created_date`/`last_modified` to the top level,
813/// serialising those fields twice; that hoist is gone. The read-only
814/// identity triple (frontmatter `mem`/`id`/`type`, served as `mem`/`id`/`entity_type`) is excluded from the nested map
815/// — it appears only top-level — and underscore-prefixed internal keys
816/// (`_hash`, `_tokens*`, `_mem_schema`, `_stub_*`) live in dedicated
817/// top-level slots and never appear inside the nested map. `sections` and
818/// `relationships` round-trip the engine's internal IndexMap / Vec
819/// shapes verbatim. `_tokens` is computed from the rendered body
820/// (filter and opt-in inserts applied) so agents can pre-size before
821/// a follow-up `token_budget`-bounded read. `_mem_schema` rides
822/// when the workspace pinned a schema for the mem.
823///
824/// Per-section filtering applies — when `sections_filter` is
825/// `Some`, the structured `sections` map carries only the requested
826/// keys (matching the markdown projection). The unfiltered-base
827/// token cost surfaces as `_tokens_unfiltered_body` so agents can
828/// predict the cost of dropping the filter. The name avoids implying a
829/// monotonic relationship (`_tokens_unfiltered_body ≥ _tokens`) that the
830/// opt-in (`include_relations` / `include_context`) path can invert:
831/// opt-in inserts contribute to `_tokens` but not to this baseline. Stub
832/// entities ship every key with empty `sections` / `relationships`
833/// arrays.
834///
835/// The structured envelope is the contract for `memstead_entity`:
836/// agents read `_hash`, sections, and relations from typed fields
837/// rather than string-scraping the markdown frontmatter.
838#[allow(clippy::too_many_arguments)] // a pure builder: every arg is used, a params struct would churn 4 call sites for no clarity
839pub 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    // Declared aggregate signals — present exactly when the entity's
853    // type declares any (the schema author opted in by declaring; a
854    // reader who must ask for the signal is a reader who forgets to).
855    // Undeclared types keep their byte-identical envelope.
856    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    // Grounded labelling — present exactly when the mem's schema
865    // declares `relationships.labelling`; the label ships with its
866    // evidence, and the shape block exactly when `support` is
867    // declared.
868    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    // Data-origin trust class, rendered at the shared envelope layer so
876    // no read surface can compose an entity read without it. It was
877    // previously inserted post-hoc by the MCP handler alone, which left
878    // the CLI's `--json` envelope silently unlabelled — a script
879    // branching on trust class treated third-party content as
880    // first-party there (cold-start 0-8-0, F9/F13).
881    envelope.insert(
882        "origin".to_string(),
883        serde_json::Value::String(origin.as_wire().to_string()),
884    );
885    // An entity whose body ends inside an unterminated fence has absorbed the
886    // sections after it; they come back as `""`, and a reader with no marker
887    // cannot tell that from a section the author left blank. Rendered at the
888    // shared envelope layer for the same reason `origin` is: it was first
889    // written on the conformance axis alone, which is opt-in, so the plain
890    // read — the one an agent actually makes — still reported them as merely
891    // empty (found by the final grade of that fix).
892    //
893    // A marker, not a repair: the bytes are unchanged and no fence is closed.
894    // `_unread_sections` names the keys whose content is really sitting in
895    // `absorbed_into`, so a reader that branches on emptiness has something to
896    // branch on.
897    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    // `entity_type`, not `type`: one concept, one wire spelling. The wasm
929    // read surface has always served the serialized Entity's `entity_type`,
930    // and this envelope said `type` for the same read — the F7-adjacent
931    // split the 2026-08-28 wire batch closed. The FRONTMATTER key stays
932    // `type:` (on-disk storage format, not the wire), and the metadata
933    // read-only triple keeps refusing it under that name.
934    envelope.insert(
935        "entity_type".to_string(),
936        serde_json::Value::String(entity.entity_type.clone()),
937    );
938    // The `# H1` display title. Structural identity like `id`/`mem`/
939    // `entity_type`, so it lives top-level next to them; before this slot the
940    // structured envelope had no title at all and consumers had to
941    // parse the rendered markdown's H1 to recover it.
942    envelope.insert(
943        "title".to_string(),
944        serde_json::Value::String(entity.title.clone()),
945    );
946
947    // Metadata has exactly one home on the envelope — the nested
948    // `metadata` map. Scalars like `level`/`stability`/`created_date`/
949    // `last_modified` are NOT hoisted to the top level; agents read
950    // `envelope.metadata.<key>`. The nested map is authoritative because
951    // it carries every schema-declared frontmatter key (including
952    // type-specific fields a top-level hoist never covered).
953    //
954    // Identity keys stay top-level and are excluded here so they too
955    // appear exactly once: `_hash`, `id`, `mem`, `entity_type` are the
956    // entity's structural identity (inserted above), not free-form
957    // metadata. Frontmatter `mem`/`id`/`type` is the engine's read-only key triple
958    // (`READ_ONLY_METADATA_KEYS`); `_`-prefixed internal keys live in
959    // dedicated top-level slots (`_tokens*`, `_mem_schema`, `_stub_*`).
960    // Stub entities surface an empty `metadata: {}` so consumers don't
961    // branch on its presence.
962    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        // This measures the unfiltered base body cost without
982        // `include_relations` / `include_context` opt-in inserts.
983        // `_tokens` may exceed `_tokens_unfiltered_body` when opt-ins
984        // are active (the opt-in inserts contribute to `_tokens` but not
985        // to this baseline) — the field name avoids implying a monotonic
986        // relationship the opt-in path can invert.
987        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    // Resolve each relationship's `source` label against the store's
1018    // outgoing-edge index. A hardcoded `"explicit"` would disagree
1019    // with the stub-adoption
1020    // response's `incoming[].source` for alias-synthesised
1021    // REFERENCES edges (and was actively misleading because
1022    // REFERENCES carries `manual_authoring: forbidden` — no edge of
1023    // that rel-type can be authored explicitly). The store's
1024    // `EdgeSource` is the single source of truth; the markdown
1025    // round-trip (which doesn't encode source) is no longer
1026    // consulted for this field.
1027    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    // Every entry declares its direction explicitly. The authored
1039    // entries (the entity's own `## Relationships` section) are
1040    // outgoing; incoming edges — when the caller opted in — are
1041    // appended with `direction: "in"` and the other endpoint under
1042    // `from`. Before the marker existed the array was silently
1043    // one-directional: a consumer had no signal that "what depends on
1044    // this?" was unanswerable from the block (cold-start 0-8-0, F15).
1045    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
1117/// Build a `SearchResultEnvelope` borrowing from `result`. `origin_of`
1118/// resolves a mem name to its data-origin class (`Engine::mem_origin_class`
1119/// on a live engine); every hit carries the resolved label, so the two
1120/// surfaces that serialise this envelope never diverge on the key.
1121pub 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
1141/// Build a `ListResultEnvelope` borrowing from `result`; `origin_of` as on
1142/// [`build_search_envelope`].
1143pub 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
1174// ---------------------------------------------------------------------------
1175// Helpers
1176// ---------------------------------------------------------------------------
1177
1178/// Build the one-line summary for a search/list hit.
1179///
1180/// Resolves the hit's schema and uses its lead section (first required, or
1181/// first section if none are required) as the label. Never panics — unknown
1182/// schemas or schemas with no sections fall back to `**Summary**: —`.
1183fn hit_summary_line(hit: &SearchHit) -> String {
1184    let (heading, value) = hit_summary_pair(hit);
1185    format!("**{heading}**: {value}")
1186}
1187
1188/// Resolve `(heading, value)` for a hit's summary line — the single source of
1189/// truth for lead-section lookup. Used by both markdown rendering and the
1190/// structured-content envelope.
1191///
1192/// Prefers the engine-precomputed [`SearchHit::summary`] (resolved against the
1193/// hit's own mem schema at search time). Falls back to the global
1194/// `type_by_name` lookup only for hits built outside the search op (FFI/bridge
1195/// and test fixtures) — that fallback sees only the `default` schema, which is
1196/// why the engine resolves the pair where the per-mem schema is in hand.
1197fn 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
1204/// Resolve `(heading, value)` given a schema and the hit's section map.
1205fn 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
1215/// The lead-section `(heading, value)` for a hit given its resolved schema:
1216/// the first required section (or the first section when none are required),
1217/// with its value pulled from `sections`. Returns `("Summary", "—")` when the
1218/// type declares no sections, and an honest `"—"` value when the lead section
1219/// is absent/empty in this hit. The single source of truth shared by the
1220/// render-time fallback ([`summary_pair`]) and the search op, which calls it
1221/// with each hit's correctly-resolved per-mem schema.
1222pub(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
1237/// Convert a section key to a display heading via the simple
1238/// derivation: first char uppercased, underscores → spaces. Used as
1239/// a fallback when no schema-declared heading is available.
1240fn 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
1252/// Resolve the heading for `key` from the type's declared sections;
1253/// fall back to the key-derivation when the type is unknown or the
1254/// key is not declared (e.g. the `relationships` virtual surface, or
1255/// catch-all extra keys). The schema-declared heading is the on-disk
1256/// truth — the renderer must echo it so rendered text matches the
1257/// markdown file content.
1258fn 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
1265/// Search every built-in schema for `name`, returning the first match.
1266/// Caches the loaded schema list via `OnceLock` so subsequent renders
1267/// pay only the HashMap lookup cost.
1268///
1269/// Distinct from `memstead_schema::type_by_name`, which is limited to the
1270/// `default` schema — that helper exists for legacy short-name lookups
1271/// and is left unchanged here. Custom workspace schemas (not embedded
1272/// in the binary) still fall through to the key-derivation path.
1273fn 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
1285// ---------------------------------------------------------------------------
1286// Schema introspection rendering
1287// ---------------------------------------------------------------------------
1288
1289/// Render the full schema catalog as markdown — built-in default types.
1290pub fn render_type_catalog_markdown() -> String {
1291    render_type_catalog_lines(all_types())
1292}
1293
1294/// Render the type catalog for an arbitrary loaded [`Schema`].
1295/// Same shape as [`render_type_catalog_markdown`]; iterates the
1296/// schema's own types in name order so multi-mem workspaces can
1297/// describe the schema pinned by the writable mem, not the engine's
1298/// hard-coded built-in.
1299pub 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
1330/// Render a single type's definition as agent-friendly markdown.
1331pub fn render_type_info_markdown(schema: &TypeDefinition) -> String {
1332    render_type_info_markdown_in(schema, None)
1333}
1334
1335/// Like [`render_type_info_markdown`], with the parent [`memstead_schema::Schema`]
1336/// supplied so relationship rows can carry their schema-level authoring
1337/// posture. Without it, `memstead type` rendered `REFERENCES` beside 40
1338/// authorable rel-types with no marker, and the manual-authoring refusal
1339/// arrived only AFTER an agent had composed (and lost) an all-or-nothing
1340/// batch — the ban must be visible before the write.
1341pub 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    // Metadata fields
1363    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    // Sections
1370    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 &section.write_rules {
1383            lines.push(format!("  - Write rule: {rule}"));
1384        }
1385    }
1386    lines.push(String::new());
1387
1388    // Relationship types
1389    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        // Schema-level authoring posture, when the parent schema is in
1406        // hand: a rel-type the alias machinery owns (e.g. REFERENCES)
1407        // is marked here, BEFORE a write, instead of only refusing
1408        // after a batch is composed.
1409        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    // Default weight
1428    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    // Writing guidance (schema-level)
1436    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    // System context
1445    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    // Canonical exemplar — the engine-validated
1453    // few-shot entity, rendered in the mem markdown shape. The CLI's
1454    // full-depth type view matches `memstead_schema verbosity: full`.
1455    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
1492/// Render a [`PerEdgeDescription`] to its wire literal — bit-identical to
1493/// what the schema YAML accepts so consumers can echo the value back
1494/// without case fiddling. `forbidden` (the default) is emitted explicitly
1495/// rather than omitted so a schema without an explicit declaration still
1496/// surfaces the resolved posture on the wire.
1497pub 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
1505/// Stable wire string for the `manual_authoring` posture.
1506pub 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/// Verbosity selector for [`build_schema_payload`].
1515///
1516/// `Full` is the complete payload — every description, `when_to_use`,
1517/// write-rule, and writing-guidance string. `Lite` drops that long-form
1518/// prose and returns a structural skeleton: entity-type names with their
1519/// section keys and metadata-field shapes, relationship names with their
1520/// allowed endpoints. The skeleton keeps every *flag* an agent needs to
1521/// author a legal write — the alias-model pointer, required-section and
1522/// required-field markers, endpoint constraints, the manual-authoring
1523/// posture, the `acyclic` flag, and the per-edge-description posture — so
1524/// a lite caller can plan a write without round-tripping to full and
1525/// without walking into a write-time refusal. Full and lite emit the two
1526/// heavy arrays under *distinct keys* (`types` / `relationships` vs.
1527/// `types_summary` / `relationships_summary`), so a consumer decodes by
1528/// key presence rather than by branching on the request shape.
1529#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1530pub enum SchemaVerbosity {
1531    #[default]
1532    Full,
1533    Lite,
1534}
1535
1536impl SchemaVerbosity {
1537    /// Parse the wire token (`"full"` / `"lite"`). Returns `None` for an
1538    /// unrecognized token so the calling surface can raise a typed error
1539    /// naming the bad value rather than silently defaulting. An absent
1540    /// parameter maps to `Full` at the call site, not here.
1541    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    /// The wire token for this verbosity.
1550    pub fn as_wire(self) -> &'static str {
1551        match self {
1552            Self::Full => "full",
1553            Self::Lite => "lite",
1554        }
1555    }
1556}
1557
1558/// Trust origin of a schema (or the mem that pins it), decided at
1559/// adopt/write time and reported — never re-derived — on the read path.
1560///
1561/// `FirstParty` is an engine built-in or a schema authored/explicitly
1562/// trusted in this workspace. Its prose-instruction fields
1563/// (`system_context`, `write_rules`, `writing_guidance`, `when_to_use`,
1564/// prose `description`, `default_writing_guidance`) guide *authoring* in
1565/// this workspace and are served in full.
1566///
1567/// `ThirdParty` is a schema that arrived from outside this workspace
1568/// (registry-installed or adopted from a foreign folder/clone) and has
1569/// not been explicitly trusted. Memstead's value proposition pulls a
1570/// mem's schema directly into a consuming agent's context, where the
1571/// schema's free-text fields are framed *as instructions* ("System
1572/// context", "Writing guidance"). A third-party schema is therefore
1573/// served structural-only: [`build_schema_payload`] forces the
1574/// [`SchemaVerbosity::Lite`] skeleton regardless of the requested
1575/// verbosity, omitting every prose-instruction field. This is lossless
1576/// for the legitimate use case — the omitted fields only guide writing,
1577/// and a write never targets a foreign mem.
1578///
1579/// The class is unforgeable by a publisher: it is decided by *how* the
1580/// schema entered the workspace, not by any content the schema carries.
1581/// An unknown/ambiguous origin classifies `ThirdParty` — the safe
1582/// default (a stranger's prose is never served as first-party
1583/// instructions on the strength of a missing label).
1584#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1585pub enum OriginClass {
1586    /// Engine built-in, or authored/explicitly trusted in this workspace.
1587    FirstParty,
1588    /// Arrived from outside this workspace and not explicitly trusted.
1589    /// The safe default for an unlabelled/ambiguous origin.
1590    #[default]
1591    ThirdParty,
1592}
1593
1594impl OriginClass {
1595    /// The wire token for this origin (`"first-party"` / `"third-party"`),
1596    /// emitted on every schema read so a consuming host can quarantine
1597    /// non-first-party content.
1598    pub fn as_wire(self) -> &'static str {
1599        match self {
1600            Self::FirstParty => "first-party",
1601            Self::ThirdParty => "third-party",
1602        }
1603    }
1604
1605    /// Whether this origin must have its schema served structural-only
1606    /// (prose-instruction fields omitted) on the read path.
1607    pub fn is_third_party(self) -> bool {
1608        matches!(self, Self::ThirdParty)
1609    }
1610}
1611
1612/// Build the transport-neutral, rmcp-free JSON payload for a schema read
1613/// (`memstead_schema`). Shared by the MCP server and the HTTP surface
1614/// so every surface emits identical
1615/// schema-read bytes from one source. `used_by` lists the writable mems
1616/// whose pinned schema resolves to this one; `verbosity` toggles the full
1617/// payload versus the lightweight skeleton (see [`SchemaVerbosity`]).
1618///
1619/// `origin` ([`OriginClass`]) is reported on the wire as `origin` and
1620/// governs de-framing: a [`OriginClass::ThirdParty`] schema is served
1621/// structural-only — the requested `verbosity` is overridden to
1622/// [`SchemaVerbosity::Lite`] so none of its prose-instruction fields
1623/// (`system_context`, `write_rules`, `writing_guidance`, `when_to_use`,
1624/// prose `description`, `default_writing_guidance`) reach a consuming
1625/// agent as instructions. A `full`-verbosity request on a third-party
1626/// schema therefore still omits them — the override is one-directional.
1627/// Append a section's format declaration (plan 08) to its rendered
1628/// object — only the declared keys, so undeclared sections keep their
1629/// exact pre-plan shape. `format_severity` renders whenever a
1630/// `content` declaration exists (the default `block` is a legality
1631/// fact, not noise).
1632fn 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/// Unknown type names in a `types` selection passed to
1655/// [`build_schema_payload_scoped`] — the caller raises a typed refusal
1656/// naming the valid types (recovery-payload posture, never a silent
1657/// empty section).
1658#[derive(Debug, Clone)]
1659pub struct UnknownSchemaTypes {
1660    pub unknown: Vec<String>,
1661    pub known: Vec<String>,
1662}
1663
1664/// Token estimate for a serialized JSON payload — routed through the
1665/// house heuristic ([`crate::chunking::estimate_tokens`]) so "fits the
1666/// pipe" is judged by the same yardstick every budgeted surface uses.
1667fn 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
1673/// Default budget for the UNSCOPED full-verbosity schema reply, in
1674/// estimated (bytes/4) tokens — ~60 KB of JSON. Calibrated against the
1675/// primary client's ~25k real-token response cap: dense JSON tokenizes
1676/// well above bytes/4, so 15k estimated sits at the cap's edge. The
1677/// two measured packages land on the intended sides: `default@1.3.0`
1678/// (~52 KB) keeps serving in full — today's behaviour on today's reply
1679/// sizes — while `software@0.4.0` (60.2 KB, the observed harness spill,
1680/// 2026-08-18 WOENENN ingest) degrades visibly to the per-type steer
1681/// instead of overflowing the pipe.
1682pub 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    // Unscoped, unbudgeted — the classic shape every existing consumer
1691    // gets. Infallible by construction (no selection to refuse).
1692    build_schema_payload_scoped(schema, used_by, verbosity, origin, None, None)
1693        .expect("no type selection, no refusal")
1694}
1695
1696/// [`build_schema_payload`] with the serving-shape controls
1697/// (an earlier plana): `type_selection` scopes the heavy per-type
1698/// prose to the named types — the reply carries the full package-level
1699/// context, the selected types in full, and a `types_omitted` roster
1700/// naming what was not served (visible scope, never silent truncation).
1701/// An unknown name refuses with [`UnknownSchemaTypes`]. Under
1702/// [`SchemaVerbosity::Lite`] the selection filters the skeleton the
1703/// same way (coherent, though the full tier is the use case).
1704///
1705/// `token_budget` guards the UNSCOPED full reply: when the complete
1706/// payload's estimated tokens exceed the budget, the reply degrades
1707/// visibly — per-type prose drops to the lite `types_summary` skeleton,
1708/// `_schema_mode: "reduced"` is stamped, and `_hint` steers the caller
1709/// to per-type retrieval via `types`. A scoped request is what the
1710/// budget steers TOWARD, so the selection path is never re-degraded.
1711pub 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    // Validate the selection against the manifest roster before any
1722    // rendering — refuse-with-the-known-names beats a silent empty
1723    // `types` array.
1724    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    // De-frame third-party schemas: their prose-instruction fields only
1738    // guide authoring (which never targets a foreign mem), so omitting
1739    // them is lossless — and serving them would place a stranger's
1740    // free-text in the consuming agent's instruction context. The Lite
1741    // skeleton keeps every structural flag an agent needs to understand
1742    // and query the mem. The override is one-directional: a `full`
1743    // request cannot re-admit the prose for a third-party schema.
1744    let verbosity = if origin.is_third_party() {
1745        SchemaVerbosity::Lite
1746    } else {
1747        verbosity
1748    };
1749
1750    // `_default` is the schema's internal weight-fallback knob — it
1751    // sets the edge weight every `_default`-less rel-type inherits and
1752    // is *not* a usable rel-type on `memstead_relate` (the relate path
1753    // rejects it with `INVALID_REL_TYPE`). Surfacing it in the agent-
1754    // facing vocabulary cost one round-trip per
1755    // session as agents tried it and learned the asymmetry by trial,
1756    // so it is suppressed here: the schema response advertises only
1757    // the rel-types `memstead_relate` actually accepts. Schemas that
1758    // declare `_default` for weight purposes are unaffected — the
1759    // engine still consults it for `edge_weight` fallback.
1760    let relationships: Vec<serde_json::Value> = manifest
1761        .relationships
1762        .definitions
1763        .iter()
1764        .filter(|d| d.name != "_default")
1765        .map(|d| {
1766            // Surface the `acyclic` flag so agents can predict cycle-check
1767            // refusal from introspection without trial-and-error.
1768            // Combined with each type's `no_self_loop_relationships`
1769            // list (below), the schema response fully describes the
1770            // self-loop / long-cycle gates.
1771            //
1772            // Surface the `manual_authoring` posture so agents see at
1773            // introspection time which rel-types refuse explicit
1774            // `memstead_relate` (forbidden), warn softly (warn), or
1775            // admit explicit authoring (allow, default).
1776            //
1777            // Surface the source/target type pinning declared on the
1778            // schema's `RelationshipDefinition` so agents can pre-filter
1779            // rel-types for their `(from_type, to_type)` pair from
1780            // introspection instead of trial-and-error against
1781            // `INVALID_REL_SHAPE`. Field names mirror the
1782            // `INVALID_REL_SHAPE` `details.allowed_source_types` /
1783            // `details.allowed_target_types` payload so the agent
1784            // learns the contract once. Empty arrays = "any type
1785            // admitted" (no pinning).
1786            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            // Derivation declaration — a
1798            // behaviour-bearing flag (baseline recording, the
1799            // stale_derivations axis, duplicate-add re-baseline), so
1800            // it must be visible at introspection time. Emitted only
1801            // when true so undeclared schemas keep their bytes.
1802            if d.derivation {
1803                o["derivation"] = serde_json::json!(true);
1804            }
1805            o
1806        })
1807        .collect();
1808
1809    // Outbound cross-mem vocabulary, one entry per target schema.
1810    // Same shape as the YAML — `{ to_schema, definitions: [...] }` —
1811    // so consumers can decode the section symmetrically with the
1812    // intra-mem `relationships` array. `_default` filtering mirrors
1813    // the intra-mem block; the rest of the per-definition shape is
1814    // identical so a single decoder handles both.
1815    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    // Iterate type names in manifest-declared order so the output is
1843    // deterministic and matches the schema author's intent.
1844    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                    // Section-format declarations (plan 08) — a
1860                    // legality condition, so it must never be
1861                    // invisible in the schema response (rendered at
1862                    // BOTH verbosity levels via the lite projection
1863                    // below).
1864                    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                    // Surface schema-declared `default_value` so agents
1884                    // see what the create path fills in when a required
1885                    // field is omitted. Without this, the engine appears
1886                    // to silently default — `priority: mid` on a
1887                    // `coverage_gap` would land with no schema-side
1888                    // explanation of where the value came from.
1889                    if let Some(default) = &f.default_value {
1890                        obj.as_object_mut()
1891                            .unwrap()
1892                            .insert("default".into(), serde_json::json!(default));
1893                    }
1894                    // A declared `value_pattern` is the shape every write
1895                    // must match (per member on a csv-array field), so an
1896                    // agent forms a legal value from the skeleton alone.
1897                    if let Some(pattern) = &f.value_pattern {
1898                        obj.as_object_mut()
1899                            .unwrap()
1900                            .insert("pattern".into(), serde_json::json!(pattern));
1901                    }
1902                    // Surface the `filterable` posture so an agent constructs
1903                    // valid `filters` / `range_filters` from the schema body
1904                    // in one shot. Always present: `"equality"` accepts
1905                    // `filters`, `"range"` accepts `range_filters`, `null`
1906                    // means not filterable.
1907                    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            // Expose the per-type `no_self_loop_relationships` list so agents
1919            // can predict self-loop refusal. The engine refuses
1920            // `memstead_relate type=R from=X(type=T) to=X` whenever R
1921            // appears here, independent of R's `acyclic` flag.
1922            //
1923            // `required_outgoing` is the only declared legality condition
1924            // on an entity's outgoing edges: each block lists the
1925            // relationship-name alternatives and the cardinality bound,
1926            // in declaration order. Always present — a type with no
1927            // blocks emits an empty list, because an absent key would
1928            // read as "unknown" and send agents back to the authoring
1929            // YAML. Cardinality is rendered exactly as declared
1930            // (`at_least_one` — an open upper bound stays open, never
1931            // normalised into a number).
1932            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                    // Conditional blocks carry their trigger at both
1942                    // verbosity levels (the lite skeleton projects this
1943                    // object unchanged); unconditional blocks keep
1944                    // their byte-identical three-key shape.
1945                    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            // Declared `constraints` — like `required_outgoing`, a
1954            // legality/health condition that must never be invisible
1955            // in the schema response (a hidden legality condition is
1956            // a defect class of its own). Always present, empty list
1957            // for a type declaring none; each entry restates the
1958            // declaration with its `severity` (`warn` = health
1959            // finding, `block` = write-time refusal), in declaration
1960            // order, at BOTH verbosity levels.
1961            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                        // Echo the declaration's own shape: the
2012                        // single-name key stays byte-identical, a
2013                        // relation set rides under `rel_types`.
2014                        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            // Reachability obligations — like `required_outgoing`, a
2052            // health condition the schema response must not hide; the
2053            // declaration is echoed in its YAML shape. Emitted only
2054            // when declared so undeclared schemas keep their payload
2055            // bytes unchanged.
2056            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            // Aggregate-signal declarations — served behaviour (the
2061            // `_signals` read insert, the health axis, the crossing
2062            // warning) an agent must see at introspection time; the
2063            // declaration is echoed in its YAML shape. Emitted only
2064            // when declared.
2065            if !td.signals.is_empty() {
2066                obj["signals"] =
2067                    serde_json::to_value(&td.signals).expect("signal declarations serialize");
2068            }
2069            // Leaf declaration — a legality-relevant fact an agent
2070            // planning writes must see; emitted only when true so
2071            // undeclared schemas keep their payload bytes unchanged.
2072            if td.leaf {
2073                obj["leaf"] = serde_json::json!(true);
2074            }
2075            // Last-resort declaration — the schema's fallback type, the
2076            // one a writer picks only when no more specific type fits
2077            // (the `vital_signs` health axis counts what sits on it).
2078            // A planning agent must see it beside `leaf`; emitted only
2079            // when declared so undeclared schemas keep their bytes.
2080            if td.last_resort {
2081                obj["last_resort"] = serde_json::json!(true);
2082            }
2083            // The type's canonical exemplar —
2084            // engine-validated at install/seal, so what it teaches is
2085            // exactly what the validator accepts. Rides FULL mode only
2086            // (this array); the lite projection below drops it by
2087            // allowlist, so the per-session skeleton stays unchanged.
2088            // Relation targets are placeholder slugs by contract.
2089            //
2090            // The relation entries are emitted in the MUTATION
2091            // vocabulary (`target` / `rel_type`) — since the
2092            // 05-front-door/08 rider landed, that is also the authoring
2093            // spelling (legacy sealed content is translated at load),
2094            // so an agent copying this payload into `memstead_create`
2095            // gets a shape the write gate accepts.
2096            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    // Scalar fields present in BOTH modes. `ref` names the schema even
2130    // in the lite skeleton; `relationship_mode`, `community`, and
2131    // `used_by` are bounded and cheap.
2132    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        // Machine-readable trust origin, present in both modes. A
2141        // consuming host reads this to decide whether to treat the
2142        // schema as workspace instructions (`first-party`) or quarantine
2143        // it as untrusted (`third-party`). Additive — a client that
2144        // ignores it still decodes the rest of the payload unchanged.
2145        "origin": origin.as_wire(),
2146    });
2147    let obj = payload.as_object_mut().unwrap();
2148
2149    // Declared acyclicity sets — a legality condition on the relate
2150    // path (a cycle in a set's union subgraph refuses), so it ships in
2151    // BOTH modes; emitted only when declared so undeclared schemas
2152    // keep their payload bytes unchanged.
2153    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    // Grounded-labelling declaration — served behaviour (the
2161    // `_labelling` read insert and the `labelling` health axis) an
2162    // agent must see at introspection time; echoed in its YAML shape,
2163    // in BOTH modes, only when declared.
2164    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    // Schema-level prose — FULL mode only. An agent that asked for the
2172    // lite skeleton is orienting on structure; the human-readable
2173    // `description` / `when_to_use` is exactly the weight the lite cut
2174    // exists to drop. The schema `ref` still identifies the schema.
2175    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        // Schema-level `system_message`, wire-named `system_context` to
2185        // match the per-type key. Without this the manifest's voice/
2186        // posture prose is unreachable from the agent surface entirely
2187        // (its only other consumer is the `memstead type` CLI markdown).
2188        // Omitted when undeclared so existing schemas render unchanged.
2189        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    // One-line effect note for the per-type `no_self_loop_relationships`
2198    // arrays — present in BOTH modes, right where the field is read.
2199    // The retired `propagating_relationships` name misled outside
2200    // schema authors into declaring impact propagation; the renamed
2201    // key states the single functional effect. Top-level (not
2202    // per-type) so the note costs one key, not one per type.
2203    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    // Schema-level `alias_target_rel_type` pointer — names the rel-type
2219    // that body wiki-links `[[target]]` auto-emit through the
2220    // alias-synthesis pass. Present in BOTH modes: it governs whether an
2221    // unbacked wiki-link bakes an edge or refuses with
2222    // `WIKILINK_WITHOUT_RELATION`, so dropping it from lite would leave a
2223    // caller one round-trip from a write-time refusal. Schemas omitting
2224    // the field render with the key absent so existing agents don't see
2225    // a noisy `null`.
2226    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    // Surface `default_writing_guidance` at the top level so plugin-side
2234    // resolvers can concatenate the schema-generic prose with per-mem
2235    // additions without parsing schema YAML themselves. FULL mode only —
2236    // it is guidance prose. Field-by-field omission — a schema with
2237    // neither `avoid` nor `goal` declared emits no key at all (both
2238    // `Option<String>` inside an `Option<DefaultWritingGuidance>`).
2239    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    // The selection partitions the manifest-ordered type roster into
2256    // served and omitted halves. `types_omitted` is emitted whenever
2257    // any type was NOT served in the requested tier — the visible-scope
2258    // guarantee (a reader always sees what a reply does not carry).
2259    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        // Only surface the cross-mem block when the schema declares
2277        // outbound entries — keeps the response minimal for schemas
2278        // that don't speak cross-mem vocabulary.
2279        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                // Budget guard on the UNSCOPED full reply: when the
2303                // assembled payload exceeds the budget, degrade
2304                // visibly — the per-type prose drops to the lite
2305                // skeleton, the mode is stamped, and the hint steers
2306                // to per-type retrieval. Never silent truncation: the
2307                // caller sees `_schema_mode: "reduced"` plus the full
2308                // roster in `types_omitted`.
2309                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        // Lite relationship form: name + endpoint constraints
2344        // (`allowed_sources`/`allowed_targets`) + manual-authoring
2345        // posture + `acyclic` + per-edge-description posture — every flag
2346        // that governs a relate-path refusal (`INVALID_REL_SHAPE`,
2347        // `RELATION_MANUAL_AUTHORING_FORBIDDEN`, cycle check,
2348        // `MISSING_REQUIRED_DESCRIPTION`) — with the description /
2349        // when_to_use / weight prose dropped. The ~42 rel-types carry the
2350        // bulk of the bytes, so this is the load-bearing half of the cut.
2351        // Projected from the rich array so each field value has one source.
2352        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        // Lite cross-mem form mirrors the intra-mem lite shape:
2375        // name + endpoint pinning, prose dropped. Same emit-when-non-empty
2376        // rule as full mode.
2377        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        // Lite entity-type form — see [`lite_types_projection`]. The
2408        // selection filters the skeleton the same way it filters the
2409        // full tier, with the same visible `types_omitted` roster.
2410        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
2430/// Lite entity-type form: name + section keys (each with its
2431/// `required` marker) + metadata-field shapes (name, required,
2432/// `enum`, `default`) + `no_self_loop_relationships` +
2433/// `required_outgoing` — the structural minimum to author a
2434/// legal write — with the type/section prose (descriptions,
2435/// write_rules, writing_guidance, system_context) dropped.
2436/// `no_self_loop_relationships` rides along because it governs
2437/// the self-loop relate refusal (relate R X→X when type T lists
2438/// R), one of the refusals the lite view must let an
2439/// agent avoid. `required_outgoing` rides along because it is
2440/// the only declared legality condition on outgoing edges —
2441/// dropping it would make "enough to plan a legal write" false.
2442/// Projected from the rich array so each field value has one
2443/// source; also the degrade target for an over-budget unscoped
2444/// full reply.
2445fn 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                            // The format declaration is a
2458                            // legality condition — the lite
2459                            // skeleton carries it in full.
2460                            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                            // The declared `value_pattern` binds every
2491                            // written value (`INVALID_FIELD_VALUE` on a
2492                            // miss): a legality flag the skeleton must
2493                            // carry, or an agent that plans from it is
2494                            // refused on a shape it was never shown
2495                            // (B6 grader finding, 2026-09-02).
2496                            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            // Leaf declaration rides the lite skeleton too — it is
2513            // a legality-relevant per-type fact.
2514            if t.get("leaf") == Some(&serde_json::json!(true)) {
2515                o["leaf"] = serde_json::json!(true);
2516            }
2517            // The last-resort declaration rides the lite skeleton for
2518            // the same reason: a writer choosing a type must see which
2519            // one the schema names as its fallback.
2520            if t.get("last_resort") == Some(&serde_json::json!(true)) {
2521                o["last_resort"] = serde_json::json!(true);
2522            }
2523            // Reachability obligations ride whole — a health condition
2524            // the skeleton must not hide; key present only when the
2525            // full payload carries it.
2526            if let Some(mr) = t.get("must_reach") {
2527                o["must_reach"] = mr.clone();
2528            }
2529            // Signal declarations ride whole for the same reason.
2530            if let Some(sig) = t.get("signals") {
2531                o["signals"] = sig.clone();
2532            }
2533            o
2534        })
2535        .collect()
2536}
2537
2538/// Format a metadata field definition as a single bullet line.
2539fn 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            // Test fixtures exercise the render-time fallback (default-schema
2623            // lookup); the engine-precomputed path is set in the search op.
2624            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    /// The lite skeleton carries a field's `value_pattern` (wire key
2677    /// `pattern`, as in the full reply) and a type's `last_resort`
2678    /// declaration: both are legality-relevant facts the server
2679    /// instructions promise the skeleton shows, and an agent that
2680    /// planned a write from a skeleton without them was refused on a
2681    /// shape it never saw (B6 grader finding, 2026-09-02). A type
2682    /// declaring neither renders without either key, so schemas that
2683    /// do not use them keep their bytes.
2684    #[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        // The CLI `type` markdown says it too.
2803        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        // A stored `_hash` metadata key (frontmatter copied out of a read
2813        // response and written back) must not render as a second `_hash:`
2814        // line beside the computed one, and the reserved triple stays
2815        // structural — same predicate as the JSON envelope's metadata map.
2816        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        // The `ingest.inconsistency` schema declares `claim_a` with
2857        // heading "Claim A" — the simple key-derivation would produce
2858        // "Claim a", which would disagree with the on-disk markdown
2859        // emitted by the generator. The renderer must echo the
2860        // schema's declared heading verbatim.
2861        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        // The naive derivation would have produced lower-case `a`/`b`.
2891        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        // When the entity_type is not in any built-in schema (custom
2901        // workspace schemas, legacy entities), the renderer falls back
2902        // to the simple key→heading derivation.
2903        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    // Regression lock for deterministic section order. The invariant:
2930    // render_entity_body walks `entity.sections` in IndexMap insertion order,
2931    // so whatever order the parser/caller inserts is what ships. The parser
2932    // inserts in schema-declared order; this test deliberately inserts in
2933    // REVERSE schema order to prove the renderer honors insertion order
2934    // (not the schema's declared order directly).
2935    #[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    /// `_tokens_unfiltered_body` rides only when a section filter
2974    /// narrows the rendered output; it carries the unfiltered-base
2975    /// cost so agents can predict the cost of dropping the filter. The
2976    /// name avoids a monotonic-relationship implication
2977    /// that the opt-in path could invert.
2978    #[test]
2979    fn tokens_reflect_filtered_output() {
2980        let entity = test_entity();
2981
2982        // Full render — no filter
2983        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        // Filtered render — request only "identity"
2995        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        // Extract token values
3007        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    // -----------------------------------------------------------------------
3040    // Summary line — search rendering
3041    // -----------------------------------------------------------------------
3042
3043    #[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        // Memo hit with no "claim" section — renderer falls back to em-dash.
3102        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), &sections),
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    // -----------------------------------------------------------------------
3206    // Summary line — list rendering (symmetric)
3207    // -----------------------------------------------------------------------
3208
3209    #[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    // -----------------------------------------------------------------------
3297    // summary_pair — structured-content source of truth
3298    // -----------------------------------------------------------------------
3299
3300    #[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(), &sections),
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(), &sections),
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    // -----------------------------------------------------------------------
3340    // Envelope serialization — structured-content sidecar
3341    // -----------------------------------------------------------------------
3342
3343    #[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        // The top-level counters use the `_-prefixed` engine-emitted
3356        // shape so the wire signals "engine-authored metadata, not
3357        // user data".
3358        assert_eq!(value["_total"], 1);
3359        assert_eq!(value["_returned"], 1);
3360        assert_eq!(value["_offset"], 0);
3361        // The envelope is one stable shape: `warnings` is on the wire
3362        // as `[]` when nothing warned, never elided.
3363        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        // Flattened SearchHit fields present.
3373        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        // Mixed-schema result: one spec hit, one memo hit. Both summary pairs
3385        // must match what summary_pair produces for each schema.
3386        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        // `_`-prefixed engine-meta keys, matching the search envelope.
3418        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        // Search warnings ship as typed `WarningHint` entries (same
3429        // `{code, details, message}` envelope every other tool uses).
3430        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    // -----------------------------------------------------------------------
3445    // Per-hit and per-result fields that must appear in the Markdown body.
3446    // -----------------------------------------------------------------------
3447
3448    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"])), // duplicate, dedupe
3562                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    /// Every field the search-tool description promises must be rendered
3643    /// in Markdown. This test exercises all of them in one result and
3644    /// asserts they all appear.
3645    #[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    /// The envelope's `relationships[].source` field reads the store's
3697    /// `EdgeSource` discriminator rather than a hardcoded `"explicit"`,
3698    /// which would disagree with the stub-adoption
3699    /// response for alias-synthesised edges (and would be
3700    /// misleading because REFERENCES carries `manual_authoring:
3701    /// forbidden`).
3702    #[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    /// The envelope's read contract is structural (cold-start 0-8-0,
3757    /// F9/F13/F15): `origin` is present on every envelope, every
3758    /// relationship entry declares its `direction`, and incoming edges
3759    /// — when the caller passes them — appear as `direction: "in"`
3760    /// entries carrying the other endpoint under `from`. A consumer
3761    /// can therefore always tell whether the block is one-directional.
3762    #[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        // Without incoming: outgoing entries are direction-labelled.
3782        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        // With incoming: the other half of the neighbourhood appears,
3800        // direction-labelled, endpoint under `from`.
3801        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    /// A relationship whose store edge is missing
3829    /// (transitional drift, store-rebuild lag) falls back to
3830    /// `"explicit"` so the envelope doesn't crash. The fallback is
3831    /// the conservative label — agents already branch on it.
3832    #[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    /// Every schema-declared frontmatter key surfaces under the nested
3855    /// `metadata` map — its single home. The four
3856    /// formerly-hoisted scalars are not at the top level; the
3857    /// read-only identity triple (mem/id/type) and underscore-prefixed
3858    /// internal keys are excluded from the nested map.
3859    #[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        // Pre-fix the envelope dropped every non-promoted key.
3865        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        // Metadata scalars are NOT hoisted to the top level — the
3907        // nested map is their single home.
3908        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        // The entity's type stays top-level as identity, spelled
3925        // `entity_type` on the wire (2026-08-28 batch); the retired `type`
3926        // key is gone, not aliased.
3927        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        // Nested map carries every non-internal, non-identity frontmatter key.
3934        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        // Internal underscore-prefixed keys and the read-only identity
3944        // triple (mem/id/type) do NOT appear inside the nested map.
3945        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    /// Stub envelopes carry an
3958    /// empty `metadata: {}` map so consumers don't branch on the
3959    /// map's presence.
3960    #[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    /// A user-defined schema names a
3985    /// metadata field colliding with structured envelope slots
3986    /// (`sections`, `relationships`). The colliding name surfaces
3987    /// under `metadata.sections` / `metadata.relationships` without
3988    /// disturbing the top-level structured arrays — the nested map
3989    /// decouples user namespace from engine namespace.
3990    #[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        // Top-level structured slots stay structured.
4017        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        // User-supplied collisions land inside the nested map.
4026        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    /// `_tokens_unfiltered_body` on the structured envelope rides only
4032    /// when `full_tokens` is supplied (a section filter was active);
4033    /// the legacy `_tokens_full` name is not present as an alias.
4034    #[test]
4035    fn build_entity_envelope_unfiltered_body_token_field_name() {
4036        let entity = test_entity();
4037        // Filter-active path — field present under new name.
4038        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        // No-filter path — field absent under both names.
4056        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    // ------------------------------------------------------------------
4073    // Schema verbosity (lite vs. full) — Plan 01.
4074    // ------------------------------------------------------------------
4075
4076    /// Load the embedded `software` schema (~42 rel-types, 9 entity
4077    /// types, `alias_target_rel_type: REFERENCES`) — the heaviest builtin,
4078    /// so the lite cut has something to bite into.
4079    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    /// Exemplar serving: `verbosity: full`
4105    /// carries each type's exemplar (title, metadata, sections,
4106    /// relations with placeholder targets); the lite skeleton is
4107    /// BYTE-unchanged between the same schema with and without an
4108    /// exemplar — the per-session lite fetch never grows.
4109    #[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        // FULL serves the exemplar with the type.
4179        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        // FULL without an exemplar: no key (absent, not null).
4193        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        // LITE is byte-identical with and without the exemplar — the
4202        // skeleton every session fetches does not grow.
4203        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    /// A first-party schema labels its origin and serves its full prose
4229    /// under `full`. The origin field is additive and present in both
4230    /// verbosities so a consuming host can always read it.
4231    #[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        // First-party full keeps the prose-instruction fields.
4242        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        // The origin label rides the lite skeleton too.
4248        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    /// Declared constraints and `required_outgoing` severities are
4258    /// visible at BOTH verbosity levels — no legality condition may
4259    /// exist that the schema response omits. Complement: a type
4260    /// declaring none renders `constraints: []`, never an absent key.
4261    #[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        // All five constraint forms (requires_when, unique,
4344        // enum_from_neighbour, status_propagation here; form 4 is the
4345        // required_outgoing severity) must be visible with their
4346        // severity at both verbosity levels.
4347        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        // Section-format declarations render at BOTH verbosity
4398        // levels (plan 08 shares plan 07's no-hidden-legality rule).
4399        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        // Complement: a constraint-free builtin renders the
4528        // always-present empty list at both levels.
4529        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    /// A third-party schema is de-framed: a `full`-verbosity request is
4548    /// overridden to the structural-only skeleton, so NONE of the
4549    /// prose-instruction fields (`system_context`, `writing_guidance`,
4550    /// section `write_rules`, schema `description` / `when_to_use`,
4551    /// `default_writing_guidance`, rel `description` / `when_to_use`)
4552    /// reach a consuming agent — even though `full` was asked for. The
4553    /// structural skeleton (type/section/field/rel shape) survives so the
4554    /// mem stays understandable and queryable. This is the refusal
4555    /// complement: a `full` request cannot re-admit the prose.
4556    #[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        // Origin label.
4567        assert_eq!(full_requested["origin"], "third-party");
4568
4569        // Prose-bearing rich arrays are GONE despite the full request;
4570        // the structural-only summaries are present instead.
4571        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        // Schema-level prose-instruction fields dropped.
4589        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        // Per-type prose-instruction fields dropped.
4603        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        // Per-rel prose dropped.
4624        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        // A third-party schema served under `full` is byte-identical to
4636        // the same schema served under `lite` (modulo the origin label,
4637        // which is identical here) — the override fully collapses to Lite.
4638        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        // Full keeps today's contract: rich arrays + schema-level prose.
4661        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        // A full type entry keeps the prose the lite cut drops.
4682        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        // A full rel entry keeps its prose.
4687        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    /// The declared `required_outgoing` blocks appear per type — with
4694    /// their relationship lists and cardinality, in declaration order —
4695    /// at BOTH verbosity levels, and a type declaring none reports an
4696    /// empty list (never a missing key). The `project` built-in is the
4697    /// live fixture: `evidence` declares one block, `decision` (among
4698    /// others) declares none. The `no_self_loop_relationships_effect`
4699    /// note ships at both levels and claims nothing beyond the
4700    /// self-loop refusal.
4701    #[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                    // A type declaring no blocks reports the empty
4741                    // list, not a missing key.
4742                    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            // The effect note for no_self_loop_relationships ships at both
4750            // levels and states the single real effect.
4751            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    /// A conditional `required_outgoing` block's trigger (`when_field`
4767    /// / `when_value`) is visible at BOTH verbosity levels — no
4768    /// legality condition the schema response omits — while an
4769    /// unconditional block keeps its byte-identical three-key shape
4770    /// (no `when_*` keys at all).
4771    #[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    /// Declared `acyclic_sets` and a `status_propagation` relation
4822    /// set are visible at BOTH verbosity levels; a single-name
4823    /// propagation declaration keeps its `rel_type` key with no
4824    /// `rel_types`, and a schema without sets carries no
4825    /// `acyclic_sets` key at all.
4826    #[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        // A schema without sets carries no `acyclic_sets` key.
4896        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    /// The labelling declaration is visible at BOTH verbosity levels
4907    /// with attack set and support walk echoed whole; a schema
4908    /// declaring none carries no `labelling` key at all.
4909    #[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    /// Declared signals are visible at BOTH verbosity levels with the
4976    /// declaration echoed whole; a type declaring none carries no
4977    /// `signals` key at all.
4978    #[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    /// A declared `must_reach` obligation is visible at BOTH verbosity
5051    /// levels with the declaration echoed (relation set, direction,
5052    /// terminal types, depth); a type declaring none carries no
5053    /// `must_reach` key at all (undeclared schemas keep their payload
5054    /// bytes unchanged).
5055    #[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        // Heavy arrays under the distinct lite keys; rich keys absent.
5136        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        // Alias pointer + endpoint constraints survive the cut — every
5149        // flag an agent needs to author a legal write.
5150        assert_eq!(lite["alias_target_rel_type"], "REFERENCES");
5151
5152        // Schema-level prose dropped.
5153        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        // Every entity-type name carries its section keys (with `required`)
5167        // and field shapes — and NO type/section prose.
5168        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            // `no_self_loop_relationships` rides along — it governs the
5193            // self-loop relate refusal, a write-time refusal lite must let
5194            // an agent avoid.
5195            assert!(
5196                t.get("no_self_loop_relationships").is_some(),
5197                "lite type keeps no_self_loop_relationships"
5198            );
5199            // `required_outgoing` rides along — the only declared
5200            // legality condition on outgoing edges. Always an array,
5201            // never an absent key (absence would read as "unknown").
5202            assert!(
5203                t.get("required_outgoing").is_some_and(|v| v.is_array()),
5204                "lite type keeps required_outgoing as an array"
5205            );
5206            // Field shapes present (name + required), prose absent.
5207            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        // Every relationship name carries its allowed endpoints and the
5220        // refusal-governing flags — and NO description/when_to_use prose.
5221        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        // The cut drops prose, never an entity type or a rel-type — an
5275        // agent orienting on lite sees the full vocabulary.
5276        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    /// Criterion 4 of 04/02, on the surface an agent actually reads. The
5305    /// conformance axis knew, but it is opt-in; a plain `memstead_entity` /
5306    /// `memstead entity --json` returned the swallowed sections as `""` with
5307    /// nothing to distinguish them from sections the author left blank.
5308    #[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        // Including one whose empty section is genuinely just empty, and one
5337        // carrying a CLOSED fence: a marker that fired on either would make
5338        // every blank section look like data loss.
5339        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}