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.
272/// DELIBERATELY MEM-WIDE, unlike the three reporting consumers that
273/// consistency-sweep 03/01 scoped to one binding's population. This predicate
274/// gates whether a verdict may be red at all, so narrowing it would change a
275/// REFUSAL rather than a figure: a mem carrying another binding's anchors would
276/// begin counting as pre-binding for this one, and a red verdict it should
277/// have produced would go quiet. That is the exit-code contract, which 03/01's
278/// scope excludes.
279pub fn mem_predates_binding(engine: &Engine, resolved: &ResolvedIngest) -> bool {
280    // Existence only — `mem_anchors_resolved` would OBSERVE every anchor
281    // (hash live sources, enumerate file scopes) to answer a question the
282    // sidecar parse alone answers. On the status path this ran per binding
283    // per request and dominated the cost (2026-09-01 profile).
284    let no_anchors = !engine.mem_has_anchors(&resolved.destination_mem);
285    let prefix = format!("{}/", resolved.name);
286    let never_synced = engine
287        .mem_config_for(&resolved.destination_mem)
288        .map(|c| {
289            !c.sync_state
290                .keys()
291                .any(|k| k.starts_with(&prefix) && k.ends_with("#synced"))
292        })
293        .unwrap_or(true);
294    no_anchors && never_synced
295}
296
297/// Resolve the destination mem's writing guidance (schema defaults + per-mem
298/// additions / legacy) — shared by the discovery and one-shot briefs.
299fn dest_guidance(engine: &Engine, dest: &str) -> ResolvedGuidance {
300    let defaults = engine
301        .schema_for(dest)
302        .and_then(|schema| schema.manifest.default_writing_guidance.clone())
303        .map(|d| GuidanceDefaults {
304            goal: d.goal,
305            avoid: d.avoid,
306        })
307        .unwrap_or_default();
308
309    let mem_guidance = engine
310        .mem_config_for(dest)
311        .map(|config| {
312            let get = |key: &str| {
313                config
314                    .write_guidance
315                    .get(key)
316                    .and_then(|v| v.as_str())
317                    .map(str::to_string)
318            };
319            MemGuidance {
320                goal_additions: get("goal_additions"),
321                avoid_additions: get("avoid_additions"),
322                legacy_goal: get("goal"),
323                legacy_avoid: get("avoid"),
324            }
325        })
326        .unwrap_or_default();
327
328    resolve_writing_guidance(&defaults, &mem_guidance)
329}
330
331/// The `--medium-type` flag value for a medium — the wire spelling a
332/// caller can paste back into `projection init`.
333fn medium_type_wire(t: crate::pipeline::MediumType) -> &'static str {
334    use crate::pipeline::MediumType as M;
335    match t {
336        M::Codebase => "codebase",
337        M::Filesystem => "filesystem",
338        M::Git => "git",
339        M::Graph => "graph",
340        M::Web => "web",
341    }
342}
343
344/// Primary source names whose medium base does not exist on disk. Only
345/// path-namespace media can be checked this way; a `web` or `graph`
346/// pointer is out of scope and never reported absent.
347fn absent_source_names(resolved: &ResolvedIngest, workspace_root: &Path) -> Vec<String> {
348    resolved
349        .sources
350        .iter()
351        .filter_map(|s| match s {
352            ResolvedSource::Primary(p) => Some(p),
353            ResolvedSource::Reference { .. } => None,
354        })
355        .filter(|p| {
356            matches!(
357                p.medium_type,
358                crate::pipeline::MediumType::Codebase
359                    | crate::pipeline::MediumType::Filesystem
360                    | crate::pipeline::MediumType::Git
361            ) && !super::cursor::medium_base(&p.pointer, workspace_root).exists()
362        })
363        .map(|p| p.name.clone())
364        .collect()
365}
366
367/// A schema pin the reader can copy verbatim into `allow-create` and
368/// `mem init`. Prefers one already in use in this workspace, so a mem
369/// created by following a remedy speaks its neighbours' vocabulary; falls
370/// back to the newest builtin `default` generation when the workspace has
371/// no mem yet (the shape a fresh `mem-repo init` leaves behind). The
372/// version is resolved from the registry rather than written literally, so
373/// a schema generation bump cannot leave this remedy naming a stale pin.
374fn suggested_schema_pin(engine: &Engine, writable: &[&str]) -> String {
375    writable
376        .iter()
377        .find_map(|m| engine.schema_pin(m))
378        .map(|r| r.as_display())
379        .or_else(|| {
380            memstead_schema::SchemaRegistry::builtin()
381                .available_versions("default")
382                .into_iter()
383                .max()
384                .map(|v| format!("default@{v}"))
385        })
386        // Unreachable with a sane binary: the builtin catalogue always
387        // carries `default`. A placeholder is still better than a pin that
388        // does not exist.
389        .unwrap_or_else(|| "<name@version>".to_string())
390}
391
392/// The note the Destination block carries when the destination mem is not
393/// in this workspace — and the remedy that actually works in the shape the
394/// reader is standing in. `memstead mem init` is mem-repo-only, so naming
395/// it unconditionally hands a filesystem-mem reader (the shape `memstead
396/// quickstart` produces) a command that refuses; there, the binding is
397/// simply pointed at the wrong mem and repointing it is the whole fix.
398fn absent_destination_note(
399    engine: &Engine,
400    resolved: &ResolvedIngest,
401    binding_id: &str,
402    workspace_root: &Path,
403) -> Option<String> {
404    let dest = resolved.destination_mem.as_str();
405    if engine.schema_pin(dest).is_some() {
406        return None;
407    }
408    let mut writable: Vec<&str> = engine
409        .mem_router()
410        .writable_mems()
411        .iter()
412        .map(String::as_str)
413        .collect();
414    writable.sort_unstable();
415    let remedy = if crate::workspace_store::is_mem_repo_shaped(workspace_root) {
416        // `mem init` is refused by default: a mem-repo workspace creates
417        // nothing until a `[[mem_management.create]]` rule admits the name.
418        // Naming the second step only would hand the reader a command that
419        // refuses `MEM_PATH_NOT_ALLOWED` on a workspace fresh from
420        // `mem-repo init` — which is the workspace this brief most often
421        // renders against.
422        let admitted =
423            crate::mem_management::CreateRuleSet::new(engine.settings().mem_create_rules.clone())
424                .ok()
425                .is_some_and(|set| set.matches(std::path::Path::new(dest)));
426        // Both steps name the SAME concrete pin. A placeholder here would be
427        // the one point on the first-session path where the reader must fetch
428        // vocabulary from somewhere else; and naming a pin on the rule while
429        // letting `mem init` fall back to its own default would refuse when
430        // the two disagree.
431        let pin = suggested_schema_pin(engine, &writable);
432        if admitted {
433            format!("Create it before writing: `memstead mem init {dest} --schema {pin}`.")
434        } else {
435            format!(
436                "Creating it takes two steps — this workspace admits no mem name yet, \
437                 so `memstead mem init` alone refuses: `memstead workspace allow-create \
438                 '{dest}' --schema {pin}`, then `memstead mem init {dest} --schema {pin}`."
439            )
440        }
441    } else if writable.is_empty() {
442        "This workspace has no writable mem to point it at.".to_string()
443    } else {
444        // Re-declare rather than hand-edit. The record's LOCATION decides
445        // the binding id and the mem whose anchors resolve — editing
446        // `destination_mem` in place leaves the record under the wrong mem
447        // folder, and every anchored write the brief mandates still refuses
448        // with INVALID_ANCHOR. Naming the field alone would be a remedy the
449        // reader could follow exactly and still be stuck.
450        let stem = binding_id.rsplit('/').next().unwrap_or(binding_id);
451        let redeclare = resolved
452            .sources
453            .iter()
454            .find_map(|s| match s {
455                crate::ingest::resolve::ResolvedSource::Primary(p) => Some(p),
456                crate::ingest::resolve::ResolvedSource::Reference { .. } => None,
457            })
458            .map(|p| {
459                format!(
460                    " Re-declare it against that mem: `rm .memstead/projections/{binding_id}.json` \
461                     then `memstead projection init --mem {} --source {} --medium-type {} \
462                     --name {}`.",
463                    writable.first().copied().unwrap_or("<mem>"),
464                    p.pointer,
465                    medium_type_wire(p.medium_type),
466                    // `--name` is not optional here: a `.` pointer (the
467                    // `quickstart --repo .` layout) derives no stem and
468                    // refuses PROJECTION_INVALID_NAME without it.
469                    stem,
470                )
471            })
472            .unwrap_or_default();
473        format!(
474            "This is a filesystem-mem workspace, which holds one mem and cannot \
475             add another, so this binding names a mem that can never exist here.{redeclare} \
476             Editing `destination_mem` alone is not enough — the record's folder \
477             decides which mem's anchors resolve."
478        )
479    };
480    Some(format!(
481        "**This mem does not exist in this workspace yet.** {remedy} Until then, \
482         every mutation this brief asks for will refuse."
483    ))
484}
485
486/// Assemble the discovery brief from the engine's live view of the
487/// destination mem: its schema defaults, per-mem writing-guidance additions,
488/// pinned schema ref, paired-process-mem existence, and the source cursor.
489fn render_discovery(engine: &Engine, resolved: &ResolvedIngest, workspace_root: &Path) -> String {
490    let dest = &resolved.destination_mem;
491    let guidance = dest_guidance(engine, dest);
492    let dest_schema = engine.schema_pin(dest).map(|r| r.as_display());
493    let process_mem = build_process_mem(engine, resolved);
494
495    // Changed-slice preface from live source state (empty when nothing has
496    // moved → the brief is byte-identical to a plain roam).
497    let cursor = compute_source_cursor(engine, resolved, workspace_root);
498    let preface = render_changed_slice(&cursor);
499
500    let dest_note = absent_destination_note(engine, resolved, &resolved.name, workspace_root);
501    let absent = absent_source_names(resolved, workspace_root);
502    assemble_discovery_brief(
503        resolved,
504        &guidance,
505        &process_mem,
506        dest_schema.as_deref(),
507        dest_note.as_deref(),
508        &absent,
509        &preface,
510    )
511}
512
513/// Assemble the one-shot lens brief — no changed-slice, no paired process mem;
514/// the destination-set / routing / idempotency / report lens block instead.
515fn render_one_shot(engine: &Engine, resolved: &ResolvedIngest) -> String {
516    let dest = &resolved.destination_mem;
517    let guidance = dest_guidance(engine, dest);
518    let dest_schema = engine.schema_pin(dest).map(|r| r.as_display());
519    let dest_purpose = engine
520        .mem_config_for(dest)
521        .and_then(|c| c.description.clone());
522    let process_mem = build_process_mem(engine, resolved); // skipped = true for one-shot
523
524    assemble_one_shot_brief(
525        resolved,
526        &guidance,
527        &process_mem,
528        dest_schema.as_deref(),
529        // The one-shot lens has no workspace root in hand; its destination
530        // set is validated by the lens block itself.
531        None,
532        &[],
533        dest_purpose.as_deref(),
534    )
535}
536
537/// Resolve the paired-process-mem view from live workspace state. Read-only:
538/// a missing process mem is reported absent rather than auto-created (mutation
539/// belongs to the orchestration layer, not brief rendering).
540fn build_process_mem(engine: &Engine, resolved: &ResolvedIngest) -> ProcessMemInfo {
541    let skipped = resolved.mode == BuildMode::OneShot;
542    // One resolution mechanism (agent-trust plan 14): the
543    // destination's declaration wins, the ingest-name convention is
544    // the fallback. A declared-but-unmounted process mem is a stated
545    // notice, never a silent fallback to derivation.
546    let resolution = crate::ingest::resolve::resolve_process_mem(
547        engine,
548        &resolved.destination_mem,
549        &resolved.name,
550    );
551    let leaf = resolution.mem.clone();
552    let present = !skipped && resolution.mounted;
553    let notice = (!skipped && resolution.declared && !resolution.mounted).then(|| {
554        format!(
555            "destination `{}` declares process mem `{}`, which is not mounted",
556            resolved.destination_mem, resolution.mem
557        )
558    });
559    ProcessMemInfo {
560        present,
561        skipped,
562        notice,
563        mem_label: if resolution.declared {
564            leaf.clone()
565        } else {
566            format!("ingest/{leaf}")
567        },
568        leaf_name: leaf,
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575    use crate::binding::BuildMode;
576    use crate::ingest::resolve::Source;
577    use crate::pipeline::{IngestTrigger, MediumType};
578
579    fn ingest_with(sources: Vec<ResolvedSource>) -> ResolvedIngest {
580        ResolvedIngest {
581            name: "ing".to_string(),
582            mode: BuildMode::Discovery,
583            trigger: IngestTrigger::Loop,
584            batch_size: 20,
585            deny_paths: vec![],
586            projection_ref: "m/p".to_string(),
587            projection_mem: "m".to_string(),
588            projection_name: "p".to_string(),
589            intent: None,
590            sources,
591            destination_mem: "m".to_string(),
592            rules: None,
593            post_actions: None,
594        }
595    }
596
597    fn primary(facet: &str, preparation: Option<&str>) -> ResolvedSource {
598        ResolvedSource::Primary(Source {
599            name: facet.to_string(),
600            medium_type: MediumType::Codebase,
601            pointer: String::new(),
602            change_detection: None,
603            scope: vec![],
604            engagement: None,
605            preparation: preparation.map(str::to_string),
606        })
607    }
608
609    /// An ingest whose source declares a preparation the registry does not
610    /// know is refused (unsupported / skip) rather than rendered — the same
611    /// rule `validate_binding` applies, mirrored for a hand-edited record.
612    /// A registered preparation passes, and the message speaks of sources,
613    /// never of the retired facet noun.
614    #[test]
615    fn unregistered_preparation_is_refused_registered_passes() {
616        assert_eq!(
617            preparation_refusal(&ingest_with(vec![primary("f", None)])),
618            None
619        );
620        assert_eq!(
621            preparation_refusal(&ingest_with(vec![ResolvedSource::Reference {
622                mem: "e".to_string()
623            }])),
624            None
625        );
626        assert_eq!(
627            preparation_refusal(&ingest_with(vec![primary(
628                "claims",
629                Some(crate::preparation::ENTITY_LOAD_BEARING),
630            )])),
631            None,
632            "a registered preparation is not refused at render"
633        );
634        let msg = preparation_refusal(&ingest_with(vec![primary(
635            "manuals",
636            Some("pdf-to-markdown"),
637        )]))
638        .unwrap();
639        assert_eq!(
640            msg,
641            format!(
642                "> **[ingest] Ingest \"ing\" is unsupported: source \"manuals\" declares preparation \"pdf-to-markdown\", which is not in this engine's preparation registry (registered: {}). Skipping.**\n",
643                crate::preparation::registered_identifiers().join(", ")
644            )
645        );
646        assert!(msg.contains("entity-load-bearing, dated-entries, code-map"));
647        assert!(!msg.contains("facet"));
648    }
649}