Skip to main content

memstead_base/ingest/
render.rs

1//! Top-level run-brief rendering — the one engine entry point every
2//! consuming surface calls (the CLI via `memstead projection brief`), so the
3//! brief a client emits is byte-identical to the CLI's **by construction**
4//! (a single code path), not by parallel re-implementation.
5//!
6//! Given a loaded [`Engine`], the workspace root, and an ingest name, it
7//! loads the four-primitive config, resolves the ingest, and — for discovery
8//! mode — assembles the full brief: writing guidance from the destination
9//! mem's schema + config, the paired-process-mem view, and the changed-slice
10//! preface from live source state.
11
12use std::path::Path;
13
14use crate::Engine;
15use crate::binding::{Binding, BuildMode};
16use crate::pipeline_store::{BindingConfigs, load_pipeline_configs};
17
18use super::brief::{
19    ProcessMemInfo, assemble_discovery_brief, assemble_one_shot_brief, render_changed_slice,
20    render_sync_brief, render_verify_brief,
21};
22use super::check_path::write_active_binding_file;
23use super::cursor::compute_source_cursor;
24use super::findings::{FindingClass, current_findings};
25use super::guidance::{GuidanceDefaults, MemGuidance, ResolvedGuidance, resolve_writing_guidance};
26use super::prune::prune_proposals;
27use super::resolve::{ResolveError, ResolvedIngest, ResolvedSource, resolve_binding_run};
28
29/// Why [`render_ingest_brief`] could not produce a brief.
30#[derive(Debug, thiserror::Error)]
31pub enum RenderBriefError {
32    /// The four-primitive pipeline config could not be loaded.
33    #[error("could not load pipeline config: {0}")]
34    ConfigLoad(String),
35    /// The ingest (or a reference it names) could not be resolved.
36    #[error(transparent)]
37    Resolve(#[from] ResolveError),
38    /// The binding declares no `build` operation, so the build path (brief) is
39    /// refused (D6/AC4). The message carries the one-command remedy
40    /// `memstead projection enable build <binding>`, which — run verbatim —
41    /// makes the same brief succeed.
42    #[error(
43        "binding '{binding}' has no build operation — enable it with \
44         `memstead projection enable build {binding}`"
45    )]
46    BuildOperationAbsent {
47        /// The binding id whose build block is absent.
48        binding: String,
49    },
50    /// The durable findings store could not be read while rendering a verify /
51    /// sync brief (group C). The brief needs the open findings; a malformed
52    /// store surfaces here rather than silently rendering an empty findings set.
53    #[error("could not read findings store for '{binding}': {detail}")]
54    FindingsRead {
55        /// The binding id whose findings store failed to read.
56        binding: String,
57        /// The underlying store error, stringified.
58        detail: String,
59    },
60}
61
62/// If any primary source declares a preparation the engine's registry
63/// ([`crate::preparation`]) does not know, return the unsupported-and-skipped
64/// message; `None` when every declared preparation is registered (or none
65/// is declared). Mirrors [`crate::binding::validate_binding`]'s registry
66/// rule for a record that acquired an unknown identifier by hand — accepted
67/// at rest, refused here rather than run over content the engine cannot
68/// prepare — so the two refusal paths carry one semantics.
69fn preparation_refusal(resolved: &ResolvedIngest) -> Option<String> {
70    resolved.sources.iter().find_map(|s| match s {
71        ResolvedSource::Primary(p) => p
72            .preparation
73            .as_deref()
74            .filter(|prep| !crate::preparation::is_registered(prep))
75            .map(|prep| {
76                format!(
77                    "> **[ingest] Ingest \"{}\" is unsupported: source \"{}\" declares \
78                     preparation \"{}\", which is not in this engine's preparation registry \
79                     (registered: {}). Skipping.**\n",
80                    resolved.name,
81                    p.name,
82                    prep,
83                    crate::preparation::registered_identifiers().join(", ")
84                )
85            }),
86        ResolvedSource::Reference { .. } => None,
87    })
88}
89
90/// The mode string used in messages (`discovery` / `one-shot`).
91pub fn mode_name(mode: BuildMode) -> &'static str {
92    match mode {
93        BuildMode::Discovery => "discovery",
94        BuildMode::OneShot => "one-shot",
95    }
96}
97
98/// Locate a binding by the CLI argument. The canonical form is the
99/// binding id `<mem>/<stem>` (D3) — the shape `projection brief` / `--all`
100/// selection use. As a transition bridge, a slash-free legacy argument (the
101/// old flat ingest stem, e.g. `engine-graph`) is also matched against each
102/// binding's `<mem>-<stem>` dashed form, so `memstead projection brief engine-graph`
103/// keeps rendering the migrated `engine/graph` binding without a router change.
104/// Returns the canonical binding id and the binding.
105fn find_binding<'a>(
106    configs: &'a BindingConfigs,
107    arg: &str,
108) -> Result<(String, &'a Binding), ResolveError> {
109    // Exact canonical id: `<mem>/<stem>`.
110    if let Some(r) = configs
111        .bindings
112        .iter()
113        .find(|r| format!("{}/{}", r.mem, r.name) == arg)
114    {
115        return Ok((format!("{}/{}", r.mem, r.name), &r.config));
116    }
117    // Transition bridge: a slash-free legacy stem → `<mem>-<stem>` dashed form.
118    if !arg.contains('/')
119        && let Some(r) = configs
120            .bindings
121            .iter()
122            .find(|r| format!("{}-{}", r.mem, r.name) == arg)
123    {
124        return Ok((format!("{}/{}", r.mem, r.name), &r.config));
125    }
126    Err(ResolveError::BindingNotFound {
127        name: arg.to_string(),
128        available: configs
129            .bindings
130            .iter()
131            .map(|r| format!("{}/{}", r.mem, r.name))
132            .collect(),
133    })
134}
135
136/// Render the run-brief for a binding — the Markdown prompt an agent consumes.
137/// The single engine entry point behind every consuming surface. `ingest_name` is
138/// the canonical binding id (or a legacy flat-ingest stem — see [`find_binding`]).
139///
140/// `consume` mirrors the scheduler's peek/consume split (decision 12,
141/// backlog-sweep plan 03) onto derived caches: a peek (`false`) is a
142/// pure read that leaves every cache byte-identical, while a consuming
143/// render (`true`) additionally publishes this binding as the ACTIVE
144/// one for deny enforcement (`projection check-path`). Without this, a
145/// peek of binding A repointed enforcement so a later consuming run of
146/// binding B was briefly guarded by A's denies.
147pub fn render_ingest_brief(
148    engine: &Engine,
149    workspace_root: &Path,
150    ingest_name: &str,
151    consume: bool,
152) -> Result<String, RenderBriefError> {
153    let configs = load_pipeline_configs(workspace_root)
154        .map_err(|e| RenderBriefError::ConfigLoad(e.to_string()))?;
155    let (binding_id, binding) = find_binding(&configs, ingest_name)?;
156
157    // D6/AC4: the build path (brief) refuses when the binding declares no build
158    // operation, carrying the one-command `projection enable build` remedy —
159    // rather than fabricating a default build the operator never declared.
160    if binding.operations.build.is_none() {
161        return Err(RenderBriefError::BuildOperationAbsent {
162            binding: binding_id,
163        });
164    }
165
166    let resolved = resolve_binding_run(&binding_id, binding)?;
167
168    // Publish this binding as the ACTIVE one for the deny enforcement path
169    // (`projection check-path` resolves "active" through this pointer) —
170    // stale-safe (remove-then-write), overwrite-always, before any mode branch
171    // so the channel is live for every consumed brief and never pins a
172    // previous binding. Only the id is published; the deny list itself is
173    // read fresh from the binding record on every check. Best-effort engine
174    // cache, not a tracked mutation. Consuming renders only: a peek changes
175    // no state a later actor depends on — derived caches included.
176    if consume {
177        write_active_binding_file(workspace_root, &binding_id);
178    }
179
180    // Refuse an ingest whose source declares a preparation the registry does
181    // not know (a hand-edited record — every edit path refuses it earlier):
182    // reported unsupported and skipped rather than run against content the
183    // engine cannot prepare. A registered preparation passes.
184    if let Some(message) = preparation_refusal(&resolved) {
185        return Ok(message);
186    }
187
188    match resolved.mode {
189        BuildMode::Discovery => Ok(render_discovery(engine, &resolved, workspace_root)),
190        BuildMode::OneShot => Ok(render_one_shot(engine, &resolved)),
191    }
192}
193
194/// Render the **verify brief** (C1) for a binding — the measurement +
195/// capped-adjudication prompt an agent consumes. The one engine entry point
196/// behind the CLI (`projection brief --verify`), mirroring
197/// [`render_ingest_brief`]. Read-only on the destination mem: it borrows
198/// `&Engine` (shared), reads the durable findings store for the backlog count,
199/// and renders. It emits **no** destination-mutation instruction (C1) — the
200/// refusal is carried by [`render_verify_brief`] itself.
201pub fn render_verify_brief_for(
202    engine: &Engine,
203    workspace_root: &Path,
204    binding_id: &str,
205) -> Result<String, RenderBriefError> {
206    let configs = load_pipeline_configs(workspace_root)
207        .map_err(|e| RenderBriefError::ConfigLoad(e.to_string()))?;
208    let (binding_id, binding) = find_binding(&configs, binding_id)?;
209    let resolved = resolve_binding_run(&binding_id, binding)?;
210
211    let (_key, findings) =
212        current_findings(engine, workspace_root, binding, &resolved).map_err(|e| {
213            RenderBriefError::FindingsRead {
214                binding: binding_id.clone(),
215                detail: e.to_string(),
216            }
217        })?;
218    let backlog = findings
219        .iter()
220        .filter(|f| f.class == FindingClass::QueuedForAdjudication)
221        .count();
222    Ok(render_verify_brief(&resolved, backlog))
223}
224
225/// Render the **sync brief** (C2/C3) for a binding — the *single* channel
226/// through which maintenance-writing work reaches an agent. The one engine entry
227/// point behind the CLI (`projection brief --sync`). It assembles both
228/// inputs in one render: the live cursor slice ([`compute_source_cursor`]) and
229/// the open findings the verify pass recorded (`current(key)`), plus the adopt
230/// framing when the mem predates its binding (E1). Read-only on the destination
231/// mem (shared `&Engine`) — every repair happens only when an agent acts on this
232/// brief through the normal MCP mutation surface.
233pub fn render_sync_brief_for(
234    engine: &Engine,
235    workspace_root: &Path,
236    binding_id: &str,
237) -> Result<String, RenderBriefError> {
238    let configs = load_pipeline_configs(workspace_root)
239        .map_err(|e| RenderBriefError::ConfigLoad(e.to_string()))?;
240    let (binding_id, binding) = find_binding(&configs, binding_id)?;
241    let resolved = resolve_binding_run(&binding_id, binding)?;
242
243    let cursor = compute_source_cursor(engine, &resolved, workspace_root);
244    let (_key, findings) =
245        current_findings(engine, workspace_root, binding, &resolved).map_err(|e| {
246            RenderBriefError::FindingsRead {
247                binding: binding_id.clone(),
248                detail: e.to_string(),
249            }
250        })?;
251    // Prune proposals (group F) ride the sync brief — the sole channel through
252    // which a prune removal reaches the mem (F3/A5). Read-only gather.
253    let prune = prune_proposals(engine, workspace_root, binding, &resolved);
254    let adopt = mem_predates_binding(engine, &resolved);
255    Ok(render_sync_brief(
256        &resolved, &cursor, &findings, &prune, adopt,
257    ))
258}
259
260/// Whether the destination mem predates its binding — the adopt / onboarding
261/// signal (E1). True when the mem carries **no** anchors and the binding has
262/// **no** recorded `#synced` baseline for any facet: there is nothing to diff
263/// against and nothing anchored yet, so 0% anchored is expected (a first sync),
264/// not drift. A genuinely-fresh mem legitimately gets the same first-sync
265/// framing — the signal is deliberately generic.
266///
267/// The single canonical adopt predicate: the sync brief ([`render_sync_brief_for`]),
268/// the tier-1 fidelity report ([`super::report::compute_fidelity_report`]), and the
269/// status rollup ([`super::status::projection_rollup`]) all read it, so onboarding
270/// framing and the no-red-verdict-from-pre-binding-history refusal stay in lockstep
271/// across every surface.
272pub fn mem_predates_binding(engine: &Engine, resolved: &ResolvedIngest) -> bool {
273    let no_anchors = engine
274        .mem_anchors_resolved(&resolved.destination_mem)
275        .is_empty();
276    let prefix = format!("{}/", resolved.name);
277    let never_synced = engine
278        .mem_config_for(&resolved.destination_mem)
279        .map(|c| {
280            !c.sync_state
281                .keys()
282                .any(|k| k.starts_with(&prefix) && k.ends_with("#synced"))
283        })
284        .unwrap_or(true);
285    no_anchors && never_synced
286}
287
288/// Resolve the destination mem's writing guidance (schema defaults + per-mem
289/// additions / legacy) — shared by the discovery and one-shot briefs.
290fn dest_guidance(engine: &Engine, dest: &str) -> ResolvedGuidance {
291    let defaults = engine
292        .schema_for(dest)
293        .and_then(|schema| schema.manifest.default_writing_guidance.clone())
294        .map(|d| GuidanceDefaults {
295            goal: d.goal,
296            avoid: d.avoid,
297        })
298        .unwrap_or_default();
299
300    let mem_guidance = engine
301        .mem_config_for(dest)
302        .map(|config| {
303            let get = |key: &str| {
304                config
305                    .write_guidance
306                    .get(key)
307                    .and_then(|v| v.as_str())
308                    .map(str::to_string)
309            };
310            MemGuidance {
311                goal_additions: get("goal_additions"),
312                avoid_additions: get("avoid_additions"),
313                legacy_goal: get("goal"),
314                legacy_avoid: get("avoid"),
315            }
316        })
317        .unwrap_or_default();
318
319    resolve_writing_guidance(&defaults, &mem_guidance)
320}
321
322/// The `--medium-type` flag value for a medium — the wire spelling a
323/// caller can paste back into `projection init`.
324fn medium_type_wire(t: crate::pipeline::MediumType) -> &'static str {
325    use crate::pipeline::MediumType as M;
326    match t {
327        M::Codebase => "codebase",
328        M::Filesystem => "filesystem",
329        M::Git => "git",
330        M::Graph => "graph",
331        M::Web => "web",
332    }
333}
334
335/// Primary source names whose medium base does not exist on disk. Only
336/// path-namespace media can be checked this way; a `web` or `graph`
337/// pointer is out of scope and never reported absent.
338fn absent_source_names(resolved: &ResolvedIngest, workspace_root: &Path) -> Vec<String> {
339    resolved
340        .sources
341        .iter()
342        .filter_map(|s| match s {
343            ResolvedSource::Primary(p) => Some(p),
344            ResolvedSource::Reference { .. } => None,
345        })
346        .filter(|p| {
347            matches!(
348                p.medium_type,
349                crate::pipeline::MediumType::Codebase
350                    | crate::pipeline::MediumType::Filesystem
351                    | crate::pipeline::MediumType::Git
352            ) && !super::cursor::medium_base(&p.pointer, workspace_root).exists()
353        })
354        .map(|p| p.name.clone())
355        .collect()
356}
357
358/// A schema pin the reader can copy verbatim into `allow-create` and
359/// `mem init`. Prefers one already in use in this workspace, so a mem
360/// created by following a remedy speaks its neighbours' vocabulary; falls
361/// back to the newest builtin `default` generation when the workspace has
362/// no mem yet (the shape a fresh `mem-repo init` leaves behind). The
363/// version is resolved from the registry rather than written literally, so
364/// a schema generation bump cannot leave this remedy naming a stale pin.
365fn suggested_schema_pin(engine: &Engine, writable: &[&str]) -> String {
366    writable
367        .iter()
368        .find_map(|m| engine.schema_pin(m))
369        .map(|r| r.as_display())
370        .or_else(|| {
371            memstead_schema::SchemaRegistry::builtin()
372                .available_versions("default")
373                .into_iter()
374                .max()
375                .map(|v| format!("default@{v}"))
376        })
377        // Unreachable with a sane binary: the builtin catalogue always
378        // carries `default`. A placeholder is still better than a pin that
379        // does not exist.
380        .unwrap_or_else(|| "<name@version>".to_string())
381}
382
383/// The note the Destination block carries when the destination mem is not
384/// in this workspace — and the remedy that actually works in the shape the
385/// reader is standing in. `memstead mem init` is mem-repo-only, so naming
386/// it unconditionally hands a filesystem-mem reader (the shape `memstead
387/// quickstart` produces) a command that refuses; there, the binding is
388/// simply pointed at the wrong mem and repointing it is the whole fix.
389fn absent_destination_note(
390    engine: &Engine,
391    resolved: &ResolvedIngest,
392    binding_id: &str,
393    workspace_root: &Path,
394) -> Option<String> {
395    let dest = resolved.destination_mem.as_str();
396    if engine.schema_pin(dest).is_some() {
397        return None;
398    }
399    let mut writable: Vec<&str> = engine
400        .mem_router()
401        .writable_mems()
402        .iter()
403        .map(String::as_str)
404        .collect();
405    writable.sort_unstable();
406    let remedy = if crate::workspace_store::is_mem_repo_shaped(workspace_root) {
407        // `mem init` is refused by default: a mem-repo workspace creates
408        // nothing until a `[[mem_management.create]]` rule admits the name.
409        // Naming the second step only would hand the reader a command that
410        // refuses `MEM_PATH_NOT_ALLOWED` on a workspace fresh from
411        // `mem-repo init` — which is the workspace this brief most often
412        // renders against.
413        let admitted =
414            crate::mem_management::CreateRuleSet::new(engine.settings().mem_create_rules.clone())
415                .ok()
416                .is_some_and(|set| set.matches(std::path::Path::new(dest)));
417        // Both steps name the SAME concrete pin. A placeholder here would be
418        // the one point on the first-session path where the reader must fetch
419        // vocabulary from somewhere else; and naming a pin on the rule while
420        // letting `mem init` fall back to its own default would refuse when
421        // the two disagree.
422        let pin = suggested_schema_pin(engine, &writable);
423        if admitted {
424            format!("Create it before writing: `memstead mem init {dest} --schema {pin}`.")
425        } else {
426            format!(
427                "Creating it takes two steps — this workspace admits no mem name yet, \
428                 so `memstead mem init` alone refuses: `memstead workspace allow-create \
429                 '{dest}' --schema {pin}`, then `memstead mem init {dest} --schema {pin}`."
430            )
431        }
432    } else if writable.is_empty() {
433        "This workspace has no writable mem to point it at.".to_string()
434    } else {
435        // Re-declare rather than hand-edit. The record's LOCATION decides
436        // the binding id and the mem whose anchors resolve — editing
437        // `destination_mem` in place leaves the record under the wrong mem
438        // folder, and every anchored write the brief mandates still refuses
439        // with INVALID_ANCHOR. Naming the field alone would be a remedy the
440        // reader could follow exactly and still be stuck.
441        let stem = binding_id.rsplit('/').next().unwrap_or(binding_id);
442        let redeclare = resolved
443            .sources
444            .iter()
445            .find_map(|s| match s {
446                crate::ingest::resolve::ResolvedSource::Primary(p) => Some(p),
447                crate::ingest::resolve::ResolvedSource::Reference { .. } => None,
448            })
449            .map(|p| {
450                format!(
451                    " Re-declare it against that mem: `rm .memstead/projections/{binding_id}.json` \
452                     then `memstead projection init --mem {} --source {} --medium-type {} \
453                     --name {}`.",
454                    writable.first().copied().unwrap_or("<mem>"),
455                    p.pointer,
456                    medium_type_wire(p.medium_type),
457                    // `--name` is not optional here: a `.` pointer (the
458                    // `quickstart --repo .` layout) derives no stem and
459                    // refuses PROJECTION_INVALID_NAME without it.
460                    stem,
461                )
462            })
463            .unwrap_or_default();
464        format!(
465            "This is a filesystem-mem workspace, which holds one mem and cannot \
466             add another, so this binding names a mem that can never exist here.{redeclare} \
467             Editing `destination_mem` alone is not enough — the record's folder \
468             decides which mem's anchors resolve."
469        )
470    };
471    Some(format!(
472        "**This mem does not exist in this workspace yet.** {remedy} Until then, \
473         every mutation this brief asks for will refuse."
474    ))
475}
476
477/// Assemble the discovery brief from the engine's live view of the
478/// destination mem: its schema defaults, per-mem writing-guidance additions,
479/// pinned schema ref, paired-process-mem existence, and the source cursor.
480fn render_discovery(engine: &Engine, resolved: &ResolvedIngest, workspace_root: &Path) -> String {
481    let dest = &resolved.destination_mem;
482    let guidance = dest_guidance(engine, dest);
483    let dest_schema = engine.schema_pin(dest).map(|r| r.as_display());
484    let process_mem = build_process_mem(engine, resolved);
485
486    // Changed-slice preface from live source state (empty when nothing has
487    // moved → the brief is byte-identical to a plain roam).
488    let cursor = compute_source_cursor(engine, resolved, workspace_root);
489    let preface = render_changed_slice(&cursor);
490
491    let dest_note = absent_destination_note(engine, resolved, &resolved.name, workspace_root);
492    let absent = absent_source_names(resolved, workspace_root);
493    assemble_discovery_brief(
494        resolved,
495        &guidance,
496        &process_mem,
497        dest_schema.as_deref(),
498        dest_note.as_deref(),
499        &absent,
500        &preface,
501    )
502}
503
504/// Assemble the one-shot lens brief — no changed-slice, no paired process mem;
505/// the destination-set / routing / idempotency / report lens block instead.
506fn render_one_shot(engine: &Engine, resolved: &ResolvedIngest) -> String {
507    let dest = &resolved.destination_mem;
508    let guidance = dest_guidance(engine, dest);
509    let dest_schema = engine.schema_pin(dest).map(|r| r.as_display());
510    let dest_purpose = engine
511        .mem_config_for(dest)
512        .and_then(|c| c.description.clone());
513    let process_mem = build_process_mem(engine, resolved); // skipped = true for one-shot
514
515    assemble_one_shot_brief(
516        resolved,
517        &guidance,
518        &process_mem,
519        dest_schema.as_deref(),
520        // The one-shot lens has no workspace root in hand; its destination
521        // set is validated by the lens block itself.
522        None,
523        &[],
524        dest_purpose.as_deref(),
525    )
526}
527
528/// Resolve the paired-process-mem view from live workspace state. Read-only:
529/// a missing process mem is reported absent rather than auto-created (mutation
530/// belongs to the orchestration layer, not brief rendering).
531fn build_process_mem(engine: &Engine, resolved: &ResolvedIngest) -> ProcessMemInfo {
532    let skipped = resolved.mode == BuildMode::OneShot;
533    // One resolution mechanism (agent-trust plan 14): the
534    // destination's declaration wins, the ingest-name convention is
535    // the fallback. A declared-but-unmounted process mem is a stated
536    // notice, never a silent fallback to derivation.
537    let resolution = crate::ingest::resolve::resolve_process_mem(
538        engine,
539        &resolved.destination_mem,
540        &resolved.name,
541    );
542    let leaf = resolution.mem.clone();
543    let present = !skipped && resolution.mounted;
544    let notice = (!skipped && resolution.declared && !resolution.mounted).then(|| {
545        format!(
546            "destination `{}` declares process mem `{}`, which is not mounted",
547            resolved.destination_mem, resolution.mem
548        )
549    });
550    ProcessMemInfo {
551        present,
552        skipped,
553        notice,
554        mem_label: if resolution.declared {
555            leaf.clone()
556        } else {
557            format!("ingest/{leaf}")
558        },
559        leaf_name: leaf,
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566    use crate::binding::BuildMode;
567    use crate::ingest::resolve::Source;
568    use crate::pipeline::{IngestTrigger, MediumType};
569
570    fn ingest_with(sources: Vec<ResolvedSource>) -> ResolvedIngest {
571        ResolvedIngest {
572            name: "ing".to_string(),
573            mode: BuildMode::Discovery,
574            trigger: IngestTrigger::Loop,
575            batch_size: 20,
576            deny_paths: vec![],
577            projection_ref: "m/p".to_string(),
578            projection_mem: "m".to_string(),
579            projection_name: "p".to_string(),
580            intent: None,
581            sources,
582            destination_mem: "m".to_string(),
583            rules: None,
584            post_actions: None,
585        }
586    }
587
588    fn primary(facet: &str, preparation: Option<&str>) -> ResolvedSource {
589        ResolvedSource::Primary(Source {
590            name: facet.to_string(),
591            medium_type: MediumType::Codebase,
592            pointer: String::new(),
593            change_detection: None,
594            scope: vec![],
595            engagement: None,
596            preparation: preparation.map(str::to_string),
597        })
598    }
599
600    /// An ingest whose source declares a preparation the registry does not
601    /// know is refused (unsupported / skip) rather than rendered — the same
602    /// rule `validate_binding` applies, mirrored for a hand-edited record.
603    /// A registered preparation passes, and the message speaks of sources,
604    /// never of the retired facet noun.
605    #[test]
606    fn unregistered_preparation_is_refused_registered_passes() {
607        assert_eq!(
608            preparation_refusal(&ingest_with(vec![primary("f", None)])),
609            None
610        );
611        assert_eq!(
612            preparation_refusal(&ingest_with(vec![ResolvedSource::Reference {
613                mem: "e".to_string()
614            }])),
615            None
616        );
617        assert_eq!(
618            preparation_refusal(&ingest_with(vec![primary(
619                "claims",
620                Some(crate::preparation::ENTITY_LOAD_BEARING),
621            )])),
622            None,
623            "a registered preparation is not refused at render"
624        );
625        let msg = preparation_refusal(&ingest_with(vec![primary(
626            "manuals",
627            Some("pdf-to-markdown"),
628        )]))
629        .unwrap();
630        assert_eq!(
631            msg,
632            format!(
633                "> **[ingest] Ingest \"ing\" is unsupported: source \"manuals\" declares preparation \"pdf-to-markdown\", which is not in this engine's preparation registry (registered: {}). Skipping.**\n",
634                crate::preparation::registered_identifiers().join(", ")
635            )
636        );
637        assert!(msg.contains("entity-load-bearing, dated-entries, code-map"));
638        assert!(!msg.contains("facet"));
639    }
640}