Skip to main content

memstead_base/ingest/
brief.rs

1//! Run-brief rendering — the engine-side assembly of the Markdown brief an
2//! ingest agent consumes as its prompt.
3//!
4//! The brief is a **rendered string** by deliberate design: an agent reads
5//! it as a prompt, so a rendered Markdown contract (matching the plugin's
6//! `inject.mjs` stdout) is the natural boundary, and parity between clients
7//! is checked on the rendered bytes. Each block function returns a string
8//! ending in a blank line (or the empty string), and the full brief is the
9//! truthy blocks concatenated.
10//!
11//! All three modes are assembled here: [`assemble_discovery_brief`] (with the
12//! header blocks [`render_situation`], [`render_intent`],
13//! [`render_goal_and_avoid`], [`render_operative_data`]),
14//! and [`assemble_one_shot_brief`] — plus the
15//! changed-slice preface ([`render_changed_slice`], rendered from a
16//! [`SourceCursor`]).
17
18use super::guidance::ResolvedGuidance;
19use super::resolve::{ResolvedIngest, ResolvedSource};
20use super::slice::{NoSignalReason, Slice};
21use crate::binding::BuildMode;
22use crate::pipeline::{MediumType, PatternMode};
23
24/// Per-class cap on the rendered changed slice — mirrors the plugin's
25/// `SLICE_CAP`. Beyond it a `…and N more` line stands in.
26const SLICE_CAP: usize = 25;
27
28/// The schema every `ingest/<name>` process mem pins. (The historical
29/// plugin-side twin of this constant is retired — this is the single
30/// authority.)
31pub const PROCESS_MEM_SCHEMA: &str = "ingest@0.5.0";
32
33/// The paired-process-mem state the brief blocks read — the engine-side of
34/// the plugin's `processMem` object. Whether a process mem is present /
35/// skipped (one-shot) / failed-to-create is decided by the orchestration
36/// glue; the blocks render from this resolved view.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ProcessMemInfo {
39    /// A paired process mem exists and is usable.
40    pub present: bool,
41    /// No process mem is paired (one-shot ingests are ephemeral by design).
42    pub skipped: bool,
43    /// Auto-creation was attempted and failed; the notice explains why.
44    pub notice: Option<String>,
45    /// The process mem's leaf name (the ingest name) — its searchable id.
46    pub leaf_name: String,
47    /// The process mem's org-path label, `ingest/<name>`.
48    pub mem_label: String,
49}
50
51/// The mode string the situation block prints (`discovery` / `one-shot`) —
52/// the same tokens the plugin uses.
53fn mode_label(mode: BuildMode) -> &'static str {
54    match mode {
55        BuildMode::Discovery => "discovery",
56        BuildMode::OneShot => "one-shot",
57    }
58}
59
60/// The medium-type label a source line prints — the lowercase medium `type`.
61fn medium_type_label(t: MediumType) -> &'static str {
62    match t {
63        MediumType::Codebase => "codebase",
64        MediumType::Filesystem => "filesystem",
65        MediumType::Graph => "graph",
66        MediumType::Git => "git",
67        MediumType::Web => "web",
68    }
69}
70
71/// Render the `## Goal` and `## Failure modes to avoid` blocks from resolved
72/// guidance, matching the plugin's `goalAndAvoidBlock`. Each present field
73/// contributes a header, a blank line, its trimmed prose, and a trailing
74/// blank line; the block ends in a blank line. With neither field present
75/// this yields `"\n"` (the plugin's `lines.join('\n') + '\n'` for the
76/// no-pass-through case).
77///
78/// Pass-through-only guidance (a schema declaring `granularity`/`stack`/… but
79/// no goal/avoid) is not yet rendered here — that fallback
80/// (`renderResolvedGuidance`) lands with the pass-through modelling.
81pub fn render_goal_and_avoid(guidance: &ResolvedGuidance) -> String {
82    let mut lines: Vec<String> = Vec::new();
83
84    if let Some(goal) = guidance
85        .goal
86        .as_deref()
87        .map(str::trim)
88        .filter(|s| !s.is_empty())
89    {
90        lines.push("## Goal".to_string());
91        lines.push(String::new());
92        lines.push(goal.to_string());
93        lines.push(String::new());
94    }
95    if let Some(avoid) = guidance
96        .avoid
97        .as_deref()
98        .map(str::trim)
99        .filter(|s| !s.is_empty())
100    {
101        lines.push("## Failure modes to avoid".to_string());
102        lines.push(String::new());
103        lines.push(avoid.to_string());
104        lines.push(String::new());
105    }
106
107    format!("{}\n", lines.join("\n"))
108}
109
110/// Render the opening `## Situation` block — loop semantics, the mutation
111/// mandate, the context-budget signal, and the paired-process-mem line.
112/// Byte-for-byte the plugin's `situationBlock`.
113pub fn render_situation(resolved: &ResolvedIngest, process_mem: &ProcessMemInfo) -> String {
114    let mode = mode_label(resolved.mode);
115    let name = &resolved.name;
116    let mut lines: Vec<String> = Vec::new();
117    lines.push("## Situation".to_string());
118    lines.push(String::new());
119    lines.push(format!(
120        "You are running one iteration of `{name}` ({mode} mode) inside a loop. \
121         Each iteration is a fresh agent with no memory of prior runs; the destination \
122         graph persists between runs and is your continuity. Backoff is mechanical — \
123         when nothing has changed since the last run, the loop skips this ingest silently. \
124         Reporting \"no changes\" is therefore a valid outcome."
125    ));
126    lines.push(String::new());
127    lines.push(
128        "Mutating the destination is this run's mandate: within the destination mem(s) and \
129         paired process mem named under Operative data, create, update, relate, and delete \
130         entities without asking. Project-level instructions that make entity creation/deletion \
131         ask-first govern interactive dev sessions, not ingest iterations — parking creatable \
132         work as a coverage_gap because of that rule defeats the loop. Mems outside the declared \
133         destinations remain off-limits."
134            .to_string(),
135    );
136    lines.push(String::new());
137    lines.push(
138        "Context budget is finite. The `PreCompact` hook fires near the limit and asks you to \
139         stop and report. Multiple cycles inside one run are fine when context allows; depth on \
140         a coherent area beats breadth across unrelated ones."
141            .to_string(),
142    );
143    lines.push(String::new());
144    if process_mem.present {
145        lines.push(format!(
146            "A paired process mem `{}` (schema `{PROCESS_MEM_SCHEMA}`) carries destination-quality \
147             debt prior runs could not address. Its entries are objective claims about destination \
148             state — read them on orientation, write to it when this run also cannot fix some debt, \
149             delete entries the destination has since resolved. Call \
150             `memstead_schema(name={PROCESS_MEM_SCHEMA})` once for the type vocabulary and write rules.",
151            process_mem.mem_label
152        ));
153    } else if let Some(notice) = &process_mem.notice {
154        lines.push(format!(
155            "Note: paired process mem `{}` could not be auto-created — {notice}. The run continues \
156             without it; the operator can retry with `memstead mem init {name} --org-path ingest \
157             --schema {PROCESS_MEM_SCHEMA}`.",
158            process_mem.mem_label
159        ));
160    } else if process_mem.skipped {
161        lines.push(format!(
162            "No process mem is paired with this ingest (mode={mode}; one-shot ingests are \
163             by-design ephemeral)."
164        ));
165    }
166    lines.push(String::new());
167    format!("{}\n", lines.join("\n"))
168}
169
170/// Render the `## About the source` block from the projection's intent, or
171/// the empty string when there is no intent. Byte-for-byte the plugin's
172/// `intentBlock`.
173pub fn render_intent(resolved: &ResolvedIngest) -> String {
174    match resolved
175        .intent
176        .as_deref()
177        .map(str::trim)
178        .filter(|s| !s.is_empty())
179    {
180        Some(intent) => format!("## About the source\n\n{intent}\n\n"),
181        None => String::new(),
182    }
183}
184
185/// Render the `## Operative data` block — the sources (with their scope), the
186/// destination (with its schema), and the paired process mem. Byte-for-byte
187/// the plugin's `operativeDataBlock`. `destination_schema` is the schema ref
188/// the destination mem pins (from `memMeta`), rendered when present.
189///
190/// A source facet's `domains` (web mediums) is not rendered — the engine's
191/// facet scope models allow/deny paths only; the domains slot lands with web
192/// medium support.
193pub fn render_operative_data(
194    resolved: &ResolvedIngest,
195    process_mem: &ProcessMemInfo,
196    destination_schema: Option<&str>,
197    destination_note: Option<&str>,
198    absent_sources: &[String],
199) -> String {
200    let mut lines: Vec<String> = Vec::new();
201    lines.push("## Operative data".to_string());
202    lines.push(String::new());
203
204    // Sources
205    if !resolved.sources.is_empty() {
206        lines.push("### Sources".to_string());
207        lines.push(String::new());
208        let mut reference_mems: Vec<String> = Vec::new();
209        for source in &resolved.sources {
210            match source {
211                ResolvedSource::Primary(p) => {
212                    // Name first, medium type demoted to annotation — the
213                    // provenance section instructs `source` = the declared
214                    // NAME, so this section must teach the same token
215                    // (plan 03a: an agent copying this bullet verbatim
216                    // must not earn an INVALID_ANCHOR).
217                    lines.push(format!(
218                        "- **{}** ({}, primary) — `{}`",
219                        p.name,
220                        medium_type_label(p.medium_type),
221                        p.pointer
222                    ));
223                    // Same obligation as the destination note: an agent
224                    // told to read a tree that is not there has been sent
225                    // on work it cannot do, and cannot tell that from a
226                    // source that is merely empty.
227                    if absent_sources.iter().any(|n| n == &p.name) {
228                        lines.push(
229                            "  - **This source does not resolve to anything on disk.** \
230                             Nothing can be read from it until the path exists or the \
231                             binding's pointer is corrected."
232                                .to_string(),
233                        );
234                    }
235                    let allows: Vec<&str> = p
236                        .scope
237                        .iter()
238                        .filter(|r| r.mode == PatternMode::Allow)
239                        .map(|r| r.path.as_str())
240                        .collect();
241                    let denies: Vec<&str> = p
242                        .scope
243                        .iter()
244                        .filter(|r| r.mode == PatternMode::Deny)
245                        .map(|r| r.path.as_str())
246                        .collect();
247                    // Scope is medium-shaped, and so is the label. A graph
248                    // source selects entities, so calling its selectors
249                    // "Paths" sent the agent looking for a glob tool over a
250                    // mem — which does not exist. The changed slice alone is
251                    // a delta with no baseline; the reference-mem block below
252                    // is the precedent for directing an agent at a mem's
253                    // contents without dumping them, so a primary graph
254                    // source gets the same executable instruction.
255                    let is_graph = p.medium_type == MediumType::Graph;
256                    let (allow_label, deny_label) = if is_graph {
257                        ("Entities", "Excluding")
258                    } else {
259                        ("Paths", "Ignore")
260                    };
261                    if !allows.is_empty() {
262                        lines.push(format!("  - {allow_label}: {}", allows.join(", ")));
263                    }
264                    if !denies.is_empty() {
265                        lines.push(format!("  - {deny_label}: {}", denies.join(", ")));
266                    }
267                    // A scope pattern still in the retired workspace-relative
268                    // dialect selects nothing under the pointer join. The
269                    // brief is the one surface a binding running only build
270                    // and sync ever reads, so the warning must land HERE —
271                    // the verify report and the `--full` refusal reach only
272                    // bindings that verify.
273                    for note in super::cursor::scope_migration_notes(p) {
274                        let rewrite = match &note.suggested {
275                            Some(s) => format!(" — rewrite it as `{s}`"),
276                            None => String::new(),
277                        };
278                        lines.push(format!(
279                            "  - **Scope pattern `{}` is written against the workspace root \
280                             rather than the source pointer, so it selects nothing**{rewrite}.",
281                            note.pattern
282                        ));
283                    }
284                    if is_graph {
285                        lines.push(format!(
286                            "  - Read the source baseline with `memstead_search mem={}` \
287                             (add `entity_type=` to match a `type:` selector). The changed \
288                             slice below is a delta against the last pass — it is not the \
289                             whole source, and an entity absent from it may still be \
290                             unprojected.",
291                            p.pointer
292                        ));
293                    }
294                }
295                ResolvedSource::Reference { mem } => {
296                    lines.push(format!("- **graph** (reference) — mem: {mem}"));
297                    reference_mems.push(mem.clone());
298                }
299            }
300        }
301        lines.push(String::new());
302        if !reference_mems.is_empty() {
303            lines.push(
304                "Sources tagged `(reference)` are read-only context for cross-mem edges — search \
305                 them, never write into them. Only `(primary)` sources are ingested into the \
306                 destination."
307                    .to_string(),
308            );
309            lines.push(String::new());
310            let mem_list = reference_mems
311                .iter()
312                .map(|v| format!("`memstead_search mem={v}`"))
313                .collect::<Vec<_>>()
314                .join(", ");
315            lines.push(format!(
316                "**Cross-mem references:** consult {mem_list} before authoring cross-mem edges. \
317                 The target entity must exist — a wiki-link or relationship to a missing target \
318                 either auto-stubs (silent) or fails authorization (`CROSS_MEM_RELATION`)."
319            ));
320            lines.push(String::new());
321        }
322    }
323
324    // Destination — four-primitive projections carry exactly one, no role.
325    lines.push("### Destination".to_string());
326    lines.push(String::new());
327    let schema_bit = destination_schema
328        .map(|s| format!(" — schema: `{s}`"))
329        .unwrap_or_default();
330    lines.push(format!("- **{}**{schema_bit}", resolved.destination_mem));
331    // No pinned schema means the engine could not resolve the destination as
332    // a mem of this workspace — a binding scaffolded before its mem exists,
333    // which `projection init` deliberately allows. Say so here rather than
334    // describing a destination that is not there: the brief's mandate is to
335    // mutate this mem, and an agent that discovers its absence on the first
336    // create has been told something untrue by the surface that sent it.
337    // The caller supplies this: whether the destination resolves, and what
338    // to do about it, both depend on the workspace shape — which this
339    // renderer cannot see. A remedy naming a command that refuses in the
340    // reader's own workspace is the defect this note exists to prevent.
341    if let Some(note) = destination_note {
342        lines.push(format!("  - {note}"));
343    }
344    lines.push(String::new());
345
346    // Paired process mem
347    if process_mem.present {
348        lines.push("### Paired process mem".to_string());
349        lines.push(String::new());
350        lines.push(format!(
351            "- **{}** — schema: `{PROCESS_MEM_SCHEMA}`. Inspect via `memstead_overview` / \
352             `memstead_search mem={}`.",
353            process_mem.mem_label, process_mem.leaf_name
354        ));
355        lines.push(String::new());
356    }
357
358    format!("{}\n", lines.join("\n"))
359}
360
361/// One baseline token a facet's cursor advances to after a full pass — the
362/// `(sync_state key, medium-typed token)` pair the engine records via the
363/// `set_mem_sync_state` writer. Produced by the cursor; the brief no longer
364/// renders it as an operator command (the agent runs `projection advance`,
365/// which computes and records the token engine-side — D4/D7).
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct SyncCommand {
368    /// The sync-state key, `"<binding-id>/<facet>#synced"` (D4).
369    pub key: String,
370    /// The opaque new-baseline token.
371    pub token: String,
372}
373
374/// A source whose change detection produced **no usable signal** this pass,
375/// with the classified [`NoSignalReason`]. Rendered as a distinct per-source
376/// note in the changed-slice preface, so the agent can tell a *blind* source
377/// (no baseline comparison happened) from a *genuinely-unchanged* one (checked,
378/// did not move — which stays silent).
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct NoSignalNote {
381    /// The source's label — the facet ref (primary) or mem id (reference), the
382    /// same token the `<ingest>/<label>` sync-state key is built from.
383    pub source: String,
384    /// Why detection produced no signal.
385    pub reason: NoSignalReason,
386    /// The source's medium, when it is a primary source. Carried so the
387    /// remedy the note prints is one this medium actually accepts — a
388    /// medium-agnostic remedy told a graph source's agent to write `**/*`,
389    /// which the engine then refuses as not an entity selector. `None` for a
390    /// reference mem, which has no facet scope to remedy.
391    pub medium_type: Option<MediumType>,
392}
393
394/// The combined source-cursor across a projection's source facets — the
395/// engine-side of the plugin's `cursor` object that `changedSliceBlock`
396/// consumes. Assembled by [`super::cursor::compute_source_cursor`] from the
397/// per-facet [`super::slice::SliceOutcome`]s.
398#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct SourceCursor {
400    /// The combined changed slice across all source facets.
401    pub union: Slice,
402    /// New-baseline commands for facets that changed.
403    pub write_commands: Vec<SyncCommand>,
404    /// New-baseline commands for facets seen for the first time (reseed).
405    pub reseed: Vec<SyncCommand>,
406    /// Per-source no-signal notes — sources whose detection could not produce a
407    /// slice this pass (unscoped facet, `signal:none`, git failure, missing
408    /// graph snapshot). Rendered distinctly from changed/reseed; a
409    /// genuinely-unchanged source contributes nothing here, so an all-unchanged
410    /// brief still renders no preface (byte-identical to a plain roam).
411    pub no_signal: Vec<NoSignalNote>,
412    /// Whether any facet reported changes (drives the "source moved" copy).
413    pub any_changes: bool,
414    /// Whether any facet's slice was degraded (mtime memo miss → full scan).
415    pub degraded: bool,
416    /// Ingest `deny_paths` entries that matched **no file** anywhere the agent
417    /// can reach (the project tree). A zero-selecting deny is surfaced as a
418    /// rendered warning rather than silently no-op'ing — it catches typos and
419    /// un-migrated legacy bare names (which, as globs, match nothing). Never a
420    /// hard error: the ingest still runs, the entry just does nothing. The
421    /// scaffold's own default hygiene entries are exempt at collection
422    /// (`cursor::dead_deny_entries`) — the engine never calls its own output
423    /// a typo.
424    pub dead_denies: Vec<String>,
425    /// The destination mem whose `sync_state` the baseline tokens live on.
426    pub dest_mem: String,
427    /// The canonical binding id `<mem>/<stem>` (D3) — rendered into the
428    /// `memstead projection advance <binding-id> …` line the changed-slice
429    /// preface now emits instead of a raw `mem set-sync-state` command (D4/D7).
430    pub binding_id: String,
431    /// Touchpoint B: one ordered delivery sequence per primary source that
432    /// declares a delivery preparation. Their unit ids also ride `union`
433    /// (the advance gate accepts them); the class lists never repeat them,
434    /// because a class list is alphabetical and a sequence is not.
435    pub delivery: Vec<DeliverySequence>,
436}
437
438/// One unit of a [`DeliverySequence`], as presented.
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct DeliveredUnit {
441    /// The unit's artifact id, `<path>#<key>` ([`crate::preparation::unit_id`]).
442    pub id: String,
443    /// The unit's intrinsic order key; the sequence sorts by it, then by id.
444    pub order_key: String,
445    /// How the unit changed (every unit of a first delivery is `Added`).
446    pub change: crate::preparation::UnitChange,
447    /// Already disposed in the binding's in-progress advance store, so it is
448    /// counted but not re-presented.
449    pub disposed: bool,
450}
451
452/// The ordered delivery sequence of one source under a delivery preparation
453/// (touchpoint B of [`crate::preparation`]): the same source state yields the
454/// same sequence on every pass, first run and change run alike.
455#[derive(Debug, Clone, PartialEq, Eq)]
456pub struct DeliverySequence {
457    /// The source's declared name.
458    pub source: String,
459    /// The declared delivery preparation identifier.
460    pub preparation: String,
461    /// No baseline existed: every unit of the source is delivered, in order.
462    pub first_run: bool,
463    /// For at least one changed file no baseline content was retrievable,
464    /// so every unit of that file is listed rather than only the changed ones.
465    pub degraded: bool,
466    /// How many not-yet-disposed units to present this pass (the build
467    /// operation's `batch_size`; `0` presents all).
468    pub batch: usize,
469    /// Every delivered unit, in the total order.
470    pub units: Vec<DeliveredUnit>,
471}
472
473/// Single-quote a value for the emitted shell command, escaping embedded
474/// single quotes. The digest token is JSON (contains `"` and `:`), so it
475/// must be quoted to survive the shell. Mirrors the plugin's `shellQuote`.
476fn shell_quote(s: &str) -> String {
477    format!("'{}'", s.replace('\'', "'\\''"))
478}
479
480/// Render one changed-slice class (Deleted / Modified / Added), capped at
481/// [`SLICE_CAP`] with a `…and N more` overflow line.
482/// Render one delivery sequence: the not-yet-disposed units in the total
483/// order, numbered by their position in that order (so a unit keeps its
484/// number across the passes of one delivery while earlier units are
485/// disposed), capped at the sequence's batch with the remainder counted,
486/// never reshuffled.
487fn render_delivery_sequence(lines: &mut Vec<String>, seq: &DeliverySequence) {
488    use crate::preparation::UnitChange;
489    lines.push(format!(
490        "### Delivery sequence: `{}` (`{}`)\n",
491        seq.source, seq.preparation
492    ));
493    let opening = if seq.first_run {
494        "First delivery of this source: every unit, in the source's own order."
495    } else {
496        "The units that changed since the last pass, at their positions in the source's own \
497         order."
498    };
499    lines.push(format!(
500        "{opening} Work them top to bottom: the order derives from the units' own keys, never \
501         from discovery or directory order, it is identical on every pass, and a unit assumes \
502         only the units numbered before it. Address a unit as `<path>#<key>` in anchors and \
503         dispositions.\n"
504    ));
505    if seq.degraded {
506        lines.push(
507            "_(No baseline content was retrievable for one or more changed files, so every unit \
508             of those files is listed; precision is coarser this pass only.)_\n"
509                .to_string(),
510        );
511    }
512    let pending: Vec<(usize, &DeliveredUnit)> = seq
513        .units
514        .iter()
515        .enumerate()
516        .filter(|(_, u)| !u.disposed)
517        .collect();
518    let disposed = seq.units.len() - pending.len();
519    let shown = if seq.batch == 0 {
520        pending.len()
521    } else {
522        pending.len().min(seq.batch)
523    };
524    for (position, unit) in &pending[..shown] {
525        let label = match unit.change {
526            UnitChange::Added => "new",
527            UnitChange::Modified => "changed",
528            UnitChange::Deleted => "deleted",
529        };
530        lines.push(format!("{}. `{}` ({label})", position + 1, unit.id));
531    }
532    if pending.len() > shown {
533        lines.push(format!(
534            "- …and {} more, presented in order once these are disposed",
535            pending.len() - shown
536        ));
537    }
538    if disposed > 0 {
539        lines.push(format!(
540            "_({disposed} unit{} of this sequence already disposed this pass.)_",
541            if disposed == 1 { "" } else { "s" }
542        ));
543    }
544    if pending.is_empty() {
545        lines.push(
546            "_(Every unit of this sequence is disposed; the baseline advances when the pass \
547             completes.)_"
548                .to_string(),
549        );
550    }
551    lines.push(String::new());
552}
553
554fn render_slice_class(lines: &mut Vec<String>, label: &str, paths: &[String]) {
555    if paths.is_empty() {
556        return;
557    }
558    let shown = paths.len().min(SLICE_CAP);
559    lines.push(format!("**{label}:**"));
560    for path in &paths[..shown] {
561        lines.push(format!("- `{path}`"));
562    }
563    if paths.len() > shown {
564        lines.push(format!(
565            "- …and {} more {}",
566            paths.len() - shown,
567            label.to_lowercase()
568        ));
569    }
570    lines.push(String::new());
571}
572
573/// The one-line explanation the brief prints for a [`NoSignalReason`] — each
574/// reason renders as distinct text, so the agent can tell the no-signal
575/// conditions apart (and all apart from a genuinely-unchanged source, which
576/// renders nothing at all).
577fn no_signal_reason_text(reason: NoSignalReason, medium: Option<MediumType>) -> &'static str {
578    match reason {
579        // The remedy is medium-shaped, because scope is. Naming a path glob at
580        // a graph source sent the agent to write the one thing the engine
581        // refuses — the brief instructing a write it would then reject.
582        NoSignalReason::Unscoped => match medium {
583            Some(MediumType::Graph) => {
584                "unscoped facet (no allow patterns) — nothing is monitored; write `*` in the \
585                 facet scope to watch the whole mem, or `type:<entity_type>` / `id:<glob>` \
586                 to narrow it (a graph source selects entities, not paths)"
587            }
588            _ => {
589                "unscoped facet (no allow patterns) — nothing is monitored; write `**/*` in the \
590                 facet scope to watch the whole medium"
591            }
592        },
593        NoSignalReason::DetectionNone => {
594            "`signal:none` — change detection is disabled for this source (declared `none`)"
595        }
596        NoSignalReason::GitUnavailable => {
597            "git signal unavailable — no work tree, an unreadable `HEAD`, or an unknown baseline; \
598             a full re-roam is warranted this pass"
599        }
600        NoSignalReason::GraphSnapshotMissing => {
601            "graph snapshot missing — the source mem has no comparable baseline this pass"
602        }
603    }
604}
605
606/// Render the `## Source changes since the last sync` preface — the changed
607/// slice to steer at first, any no-signal sources, plus the `projection advance`
608/// "record your dispositions LAST" section. Extends the plugin's `changedSliceBlock`
609/// with the no-signal notes. Returns the empty string when nothing changed,
610/// nothing needs reseeding, and every source is genuinely unchanged (no
611/// no-signal notes) — making the brief byte-identical to a plain roam.
612pub fn render_changed_slice(cursor: &SourceCursor) -> String {
613    if !cursor.any_changes
614        && cursor.reseed.is_empty()
615        && cursor.no_signal.is_empty()
616        && cursor.dead_denies.is_empty()
617    {
618        return String::new();
619    }
620    let mut lines: Vec<String> = Vec::new();
621    lines.push("## Source changes since the last sync\n".to_string());
622
623    if cursor.any_changes {
624        lines.push(
625            "The source moved since this graph was last synced. Steer this pass at these changed \
626             artifacts **first** — they are where the graph is most likely now wrong.\n"
627                .to_string(),
628        );
629        // Delivery sequences first: for a source under a delivery
630        // preparation the order IS the steering, and their unit ids never
631        // repeat in the alphabetical class lists below.
632        for seq in &cursor.delivery {
633            render_delivery_sequence(&mut lines, seq);
634        }
635        let unit_ids: std::collections::BTreeSet<&str> = cursor
636            .delivery
637            .iter()
638            .flat_map(|s| s.units.iter().map(|u| u.id.as_str()))
639            .collect();
640        let without_units = |v: &[String]| -> Vec<String> {
641            v.iter()
642                .filter(|p| !unit_ids.contains(p.as_str()))
643                .cloned()
644                .collect()
645        };
646        // Deletions first — cheapest, highest-signal drift.
647        render_slice_class(&mut lines, "Deleted", &without_units(&cursor.union.deleted));
648        render_slice_class(
649            &mut lines,
650            "Modified",
651            &without_units(&cursor.union.modified),
652        );
653        render_slice_class(&mut lines, "Added", &without_units(&cursor.union.added));
654        if cursor.degraded {
655            lines.push(
656                "_(Precise change history for one or more facets was unavailable, so its full \
657                 current file set is listed above. Detection still fired from the durable baseline; \
658                 targeting is coarser this pass only.)_\n"
659                    .to_string(),
660            );
661        }
662    }
663
664    if !cursor.reseed.is_empty() {
665        let keys = cursor
666            .reseed
667            .iter()
668            .map(|r| format!("`{}`", r.key))
669            .collect::<Vec<_>>()
670            .join(", ");
671        let it = if cursor.reseed.len() == 1 {
672            "it"
673        } else {
674            "them"
675        };
676        lines.push(format!(
677            "No usable sync baseline exists for {keys} — none was recorded, or the recorded one \
678             is not a commit of the source's repo (foreign or garbage-collected). Treating the \
679             current source state as the baseline. No priority slice from {it} this pass; \
680             proceed as usual.\n"
681        ));
682    }
683
684    if !cursor.no_signal.is_empty() {
685        lines.push(
686            "Some sources produced **no change signal** this pass — detection could not compare \
687             them against a baseline, so they were not steered (roam them as usual). This is \
688             distinct from a source that was checked and had not moved:\n"
689                .to_string(),
690        );
691        for note in &cursor.no_signal {
692            lines.push(format!(
693                "- `{}`: {}",
694                note.source,
695                no_signal_reason_text(note.reason, note.medium_type)
696            ));
697        }
698        lines.push(String::new());
699    }
700
701    if !cursor.dead_denies.is_empty() {
702        lines.push(
703            "**Warning — some `deny_paths` entries match nothing.** The following ingest \
704             `deny_paths` selected **no file** in the project tree, so they exclude nothing from \
705             the slice and hide nothing from the ingest agent. This is usually a typo or a legacy \
706             bare name that never migrated to the workspace-relative glob dialect (e.g. `dev` → \
707             `dev/**`, `VISION.md` → `**/VISION.md`). Fix or remove them:\n"
708                .to_string(),
709        );
710        for entry in &cursor.dead_denies {
711            lines.push(format!("- `{entry}`"));
712        }
713        lines.push(String::new());
714    }
715
716    // Disposition-record instruction — the agent's FINAL step. The advance is
717    // resumable and non-stalling (D7): a partial pass is honored on disk, and a
718    // source that moves mid-pass re-presents (remaining + new) without losing
719    // recorded work. The agent runs `projection advance`, which computes and
720    // records the new baseline token engine-side — the brief no longer renders a
721    // raw `mem set-sync-state` command (D4). The block appears whenever there is
722    // a baseline to advance (a changed facet or a first-sync reseed).
723    let has_baseline_to_advance = !cursor.write_commands.is_empty() || !cursor.reseed.is_empty();
724    if has_baseline_to_advance {
725        lines.push("### Recording your dispositions (do this LAST)\n".to_string());
726        lines.push(
727            "Only after you have worked the changed artifacts above — and only for the artifacts \
728             you actually judged — record a disposition for each, so the next pass targets just \
729             what changes next. This advance is resumable and non-stalling: a partial pass is \
730             honored, and if the source moves mid-pass the remaining slice re-presents \
731             (remaining + new) without losing your recorded work.\n"
732                .to_string(),
733        );
734        lines.push(
735            "Anchored work disposes itself: at advance time, every listed artifact that an \
736             anchor in the destination mem references is marked `worked` automatically (an \
737             explicit disposition you pass wins over the auto-mark). Supply dispositions only \
738             for the residue — artifacts you skipped, judged out of intent, or worked without \
739             anchors. The gate accepts only artifact ids listed above — an unknown id refuses \
740             the whole call. When every artifact is disposed, the sync baseline advances \
741             automatically. Run:\n"
742                .to_string(),
743        );
744        lines.push("```sh".to_string());
745        lines.push(format!(
746            "memstead projection advance {} --dispositions {}",
747            cursor.binding_id,
748            shell_quote(r#"{"<artifact>": "<disposition>", ...}"#)
749        ));
750        lines.push("```".to_string());
751        lines.push(
752            "If you were interrupted before finishing, that is fine — your recorded dispositions \
753             persist, and the next run re-presents only what is left.\n"
754                .to_string(),
755        );
756    }
757
758    format!("{}\n", lines.join("\n"))
759}
760
761/// Assemble the discovery-mode brief — situation, about-the-source, goal/avoid,
762/// operative-data, and the changed-slice preface — concatenating the truthy
763/// blocks, matching the plugin's `parts.filter(Boolean).join('')`.
764/// `changed_slice_preface` is the rendered changed-slice block (empty when
765/// the source has not moved, making the brief byte-identical to a plain roam).
766/// Render the `## Provenance — anchor your writes` block — the build-brief
767/// instruction to attach `anchors[]` to every entity mutation. Rendered by the
768/// engine, never by skill prose: a binary old enough to reject the parameter
769/// never renders the instruction, so the brief cannot version-skew against its
770/// own mutation surface (the reason the plugin-side capability gate exists for
771/// skill-carried prose). The element shape is taught by the mutation tools'
772/// own descriptions; the brief carries only the job.
773pub fn render_anchor_instruction(resolved: &ResolvedIngest) -> String {
774    let mut block = "## Provenance — anchor your writes\n\n\
775     Attach an `anchors` list to every `memstead_create` / `memstead_update`, naming the \
776     source artifact(s) the entity is drawn from (the mutation tools document the element \
777     shape). Anchored writes are what verify measures coverage and drift against, and — on \
778     cursor-driven passes — what the advance gate auto-marks `worked`; an unanchored write \
779     leaves the fidelity report and the disposition window blind to your work.\n\n"
780        .to_string();
781    // Name the producing entry point: each anchor's `source` carries the
782    // binding source NAME it came from, so a discovery run is measurable
783    // per entry point (which entry carries, which delivers nothing).
784    let primary_names: Vec<&str> = resolved
785        .sources
786        .iter()
787        .filter_map(|s| match s {
788            crate::ingest::resolve::ResolvedSource::Primary(src) => Some(src.name.as_str()),
789            crate::ingest::resolve::ResolvedSource::Reference { .. } => None,
790        })
791        .collect();
792    if !primary_names.is_empty() {
793        block.push_str(&format!(
794            "Set each anchor's `source` to the binding source name you drew the artifact \
795             from — this binding declares: {}. The name selects the pointer the \
796             artifact path is joined onto, so the wrong one usually refuses \
797             `INVALID_ANCHOR` (the path resolves under no candidate join). A name \
798             outside the list is NOT itself refused when the path happens to \
799             resolve workspace-relative — that tolerance exists for anchors whose \
800             binding was later renamed — so getting it right is on you, not on a \
801             gate.\n\n",
802            primary_names
803                .iter()
804                .map(|n| format!("`{n}`"))
805                .collect::<Vec<_>>()
806                .join(", ")
807        ));
808    }
809    // The url grain: the engine never fetches, so the observation is the
810    // author's, and so is the stability call — a page that may change reads
811    // `unstable` (a hash break is a recheck, not drift); an immutable
812    // document must say so to be adjudicated.
813    block.push_str(
814        "For a web document use `grain: url` with the URL as `artifact` and pass the retrieved \
815         text as `content` so the engine records its hash (the engine never fetches). Set \
816         `hash_stability: stable` on an IMMUTABLE document — a dated PDF, an archived page, a \
817         versioned standard — so a later changed hash reads as `drifted`; leave the default \
818         `unstable` for a living page, where a change is only a `recheck`. Url rows are \
819         re-adjudicated when someone supplies a fresh observation (`memstead verify-anchors \
820         --observations`), and every surface shows how long each has gone unobserved.\n\n",
821    );
822    // A source under a preparation hashes a PREPARED form, which no agent
823    // computes by hand: say so, and say what to do instead.
824    for source in &resolved.sources {
825        let crate::ingest::resolve::ResolvedSource::Primary(src) = source else {
826            continue;
827        };
828        let Some(prep) = src
829            .preparation
830            .as_deref()
831            .and_then(crate::preparation::lookup)
832        else {
833            continue;
834        };
835        let what = match prep.id {
836            crate::preparation::CODE_MAP => {
837                "the file's interface digest (imports, exports, signatures; comments, \
838                 formatting and bodies invisible), and a `tree` anchor the code map of every \
839                 scoped file under it"
840            }
841            crate::preparation::DATED_ENTRIES => {
842                "the unit's own text for a `<path>#<key>` span, the file's bytes otherwise"
843            }
844            crate::preparation::ENTITY_LOAD_BEARING => "the entity's load-bearing sections",
845            _ => prep.description,
846        };
847        block.push_str(&format!(
848            "Anchors on `{}` hash a prepared form (`{}`): {what}. Never compute `hash` \
849             yourself for this source — leave it empty (verify records it on first \
850             observation), or for a `file` or `span` anchor pass the artifact's `content` \
851             and the engine hashes the prepared form (a `tree` anchor takes no content).\n\n",
852            src.name, prep.id
853        ));
854    }
855    block
856}
857
858#[allow(clippy::too_many_arguments)]
859pub fn assemble_discovery_brief(
860    resolved: &ResolvedIngest,
861    guidance: &ResolvedGuidance,
862    process_mem: &ProcessMemInfo,
863    destination_schema: Option<&str>,
864    destination_note: Option<&str>,
865    absent_sources: &[String],
866    changed_slice_preface: &str,
867) -> String {
868    let parts = [
869        render_situation(resolved, process_mem),
870        render_intent(resolved),
871        render_goal_and_avoid(guidance),
872        render_operative_data(
873            resolved,
874            process_mem,
875            destination_schema,
876            destination_note,
877            absent_sources,
878        ),
879        render_anchor_instruction(resolved),
880        changed_slice_preface.to_string(),
881    ];
882    parts
883        .into_iter()
884        .filter(|p| !p.is_empty())
885        .collect::<Vec<_>>()
886        .join("")
887}
888
889/// Render the `## Mode: one-shot — lens routing` block — the destination-set
890/// table, optional routing rule, idempotency contract, end-of-run report
891/// template, and optional archive note. Byte-for-byte the plugin's
892/// `oneShotLensBlock`. `destination_schema` / `destination_purpose` describe
893/// the ingest's single destination (four-primitive projections have one).
894pub fn render_one_shot_lens(
895    resolved: &ResolvedIngest,
896    destination_schema: Option<&str>,
897    destination_purpose: Option<&str>,
898) -> String {
899    let cell = |s: &str| s.replace('|', "\\|").replace('\n', " ");
900    let mut lines: Vec<String> = vec![
901        "## Mode: one-shot — lens routing".to_string(),
902        String::new(),
903        "A lens iterates entities once and writes per-destination, then exits. The agent decides \
904         per-entity which destinations to target (Routing rule). Re-runs use `memstead_update`; \
905         never duplicate."
906            .to_string(),
907        String::new(),
908    ];
909
910    lines.push("### Destination set".to_string());
911    lines.push(String::new());
912    lines.push("| Mem | Schema | Purpose |".to_string());
913    lines.push("|-------|--------|---------|".to_string());
914    let schema = destination_schema.unwrap_or("(none)");
915    let purpose = destination_purpose
916        .filter(|s| !s.is_empty())
917        .unwrap_or("(no purpose declared)");
918    lines.push(format!(
919        "| {} | {} | {} |",
920        cell(&resolved.destination_mem),
921        cell(schema),
922        cell(purpose)
923    ));
924    lines.push(String::new());
925
926    if let Some(routing) = resolved
927        .rules
928        .as_ref()
929        .and_then(|r| r.get("routing"))
930        .and_then(|v| v.as_str())
931        .map(str::trim)
932        .filter(|s| !s.is_empty())
933    {
934        lines.push("### Routing rule".to_string());
935        lines.push(String::new());
936        lines.push("```".to_string());
937        lines.push(routing.to_string());
938        lines.push("```".to_string());
939        lines.push(String::new());
940    }
941
942    lines.push("### Idempotency".to_string());
943    lines.push(String::new());
944    lines.push("- Search the destination before writing; route changes through `memstead_update` against the existing entity if present.".to_string());
945    lines.push("- Skip writes when the lifted content matches what is already there (record as `skipped: already-up-to-date`).".to_string());
946    lines.push(
947        "- Use `memstead_create` only when no entity for that concept exists yet.".to_string(),
948    );
949    lines.push(String::new());
950
951    lines.push("### End-of-run report".to_string());
952    lines.push(String::new());
953    lines.push("After every destination is processed, emit one block per destination on stdout, in Destination-set order:".to_string());
954    lines.push(String::new());
955    lines.push("```".to_string());
956    lines.push(format!("### Report: {}", resolved.name));
957    lines.push(String::new());
958    lines.push("Destination: <mem>".to_string());
959    lines.push("  created: <count>".to_string());
960    lines.push("  updated: <count>".to_string());
961    lines.push("  skipped: <count>".to_string());
962    lines.push("  failed:  <count>".to_string());
963    lines.push("  failures:".to_string());
964    lines.push("    - <entity-key>: <error verbatim>".to_string());
965    lines.push("  skipped-detail:".to_string());
966    lines.push("    - <entity-key>: <one-line reason>".to_string());
967    lines.push("```".to_string());
968    lines.push(String::new());
969    lines.push("Per-destination commits are independent — partial success is the accepted failure mode. No rollback.".to_string());
970    lines.push(String::new());
971
972    let archive = resolved
973        .post_actions
974        .as_ref()
975        .and_then(|p| p.get("archive_source"))
976        .and_then(serde_json::Value::as_bool)
977        .unwrap_or(false);
978    if archive {
979        lines.push("### Archive after run".to_string());
980        lines.push(String::new());
981        lines.push("After the report has been emitted, archive the source planning mem — `post_actions.archive_source` is set on this ingest.".to_string());
982        lines.push(String::new());
983    }
984
985    format!("{}\n", lines.join("\n"))
986}
987
988/// Assemble the one-shot brief — situation, about-the-source, goal/avoid,
989/// operative-data, and the lens-routing block. Mirrors the plugin's one-shot
990/// `parts`. A one-shot ingest has no paired process mem, so `process_mem`
991/// should carry `skipped = true`.
992#[allow(clippy::too_many_arguments)]
993pub fn assemble_one_shot_brief(
994    resolved: &ResolvedIngest,
995    guidance: &ResolvedGuidance,
996    process_mem: &ProcessMemInfo,
997    destination_schema: Option<&str>,
998    destination_note: Option<&str>,
999    absent_sources: &[String],
1000    destination_purpose: Option<&str>,
1001) -> String {
1002    let parts = [
1003        render_situation(resolved, process_mem),
1004        render_intent(resolved),
1005        render_goal_and_avoid(guidance),
1006        render_operative_data(
1007            resolved,
1008            process_mem,
1009            destination_schema,
1010            destination_note,
1011            absent_sources,
1012        ),
1013        render_anchor_instruction(resolved),
1014        render_one_shot_lens(resolved, destination_schema, destination_purpose),
1015    ];
1016    parts
1017        .into_iter()
1018        .filter(|p| !p.is_empty())
1019        .collect::<Vec<_>>()
1020        .join("")
1021}
1022
1023// ---------------------------------------------------------------------------
1024// Verify + sync briefs (group C) — the measure/repair surface beside the build
1025// briefs. Verify MEASURES (no destination mutation of any kind, C1); sync is the
1026// SOLE maintenance writer, carrying BOTH the cursor slice and the open findings
1027// in one brief (C2) with the whole of `/reconcile`'s absorbed judgment (C3). A
1028// rule-by-rule absorption map records where each retired reconcile rule now
1029// lives (bundle plan `05-verify-sync-engine`, C4).
1030// ---------------------------------------------------------------------------
1031
1032use super::findings::{Finding, FindingClass, FindingTarget};
1033use super::prune::{PruneDisposition, PruneProposal};
1034
1035/// Per-class cap on the rendered open-findings list — mirrors [`SLICE_CAP`].
1036const FINDINGS_CAP: usize = SLICE_CAP;
1037
1038/// Render the **verify brief** (C1) — the measurement + capped-adjudication
1039/// prompt an agent consumes to *measure* a binding's fidelity.
1040///
1041/// **Refusal (C1), structural:** this function emits **no destination-mutation
1042/// instruction of any kind**. It tells the agent what to measure and adjudicate,
1043/// never what to write into the destination mem — every repair is recorded as a
1044/// finding for the sync brief ([`render_sync_brief`]) to act on. There is no
1045/// create / update / relate / delete instruction anywhere in the rendered text.
1046pub fn render_verify_brief(resolved: &ResolvedIngest, backlog: usize) -> String {
1047    let mut lines: Vec<String> = vec![
1048        "## Verify — measure fidelity, do not mutate".to_string(),
1049        String::new(),
1050    ];
1051    lines.push(format!(
1052        "You are measuring the fidelity of `{}` — how faithfully the destination mem \
1053         `{}` still matches its source. This pass **only measures**: read the source \
1054         and the mem's anchors, judge whether the graph still holds, and record what \
1055         you find. **You** write nothing into the destination mem — the run itself \
1056         records its findings store, backfills observed anchor hashes, and writes a \
1057         `#verified` baseline, which is engine bookkeeping, not your edits.",
1058        resolved.name, resolved.destination_mem
1059    ));
1060    lines.push(String::new());
1061
1062    lines.push(
1063        "Anchors may carry a `source` naming the binding entry point that produced them — \
1064         note it when recording findings, so fidelity stays measurable per source."
1065            .to_string(),
1066    );
1067    lines.push(String::new());
1068
1069    lines.push("### Adjudicate the queued findings (capped)".to_string());
1070    lines.push(String::new());
1071    if backlog == 0 {
1072        lines.push(
1073            "No findings are queued for adjudication this pass. Spot-check the resolving \
1074             anchors and the uncovered-artifact sample the fidelity report lists, and \
1075             record any drift you observe as a finding."
1076                .to_string(),
1077        );
1078    } else {
1079        lines.push(format!(
1080            "{backlog} finding(s) are queued for adjudication. Working up to the per-run \
1081             adjudication cap (an operations knob — the remainder stays queued and \
1082             re-presents on a later pass), take each queued finding and compare the \
1083             anchored source content against what the entity records. Classify it: still \
1084             accurate, or drifted. **Record the verdict — this is a measurement, not a \
1085             repair.** A drift you record becomes a finding the sync pass repairs; you do \
1086             not fix it here."
1087        ));
1088    }
1089    lines.push(String::new());
1090
1091    lines.push("### Out of scope for verify — no mutation".to_string());
1092    lines.push(String::new());
1093    lines.push(
1094        "Verify writes **no entity content**. Do not update a \
1095         `specifies` / `constraints` section, do not create or delete an entity, do not \
1096         add or remove a relationship. When measurement shows the graph is wrong, that \
1097         is a **finding** — the sync brief (`memstead projection brief --sync`) is the \
1098         one place those repairs are made. Leave every fix to it. (The run itself does \
1099         record its findings store, backfill observed anchor hashes, and write a \
1100         `#verified` baseline — engine bookkeeping, not your edits.)"
1101            .to_string(),
1102    );
1103    lines.push(String::new());
1104
1105    format!("{}\n", lines.join("\n"))
1106}
1107
1108/// A compact `entity → artifact` (or bare artifact) label for a finding target.
1109fn finding_target_label(target: &FindingTarget) -> String {
1110    match target {
1111        FindingTarget::Anchor { entity, artifact } => format!("`{entity}` → `{artifact}`"),
1112        FindingTarget::Artifact { artifact } => format!("`{artifact}`"),
1113    }
1114}
1115
1116/// Render one class-grouped findings section, capped at [`FINDINGS_CAP`] with a
1117/// `…and N more` overflow line. Skips an empty group entirely.
1118fn render_findings_group(
1119    lines: &mut Vec<String>,
1120    heading: &str,
1121    guidance: &str,
1122    items: &[&Finding],
1123) {
1124    if items.is_empty() {
1125        return;
1126    }
1127    lines.push(format!("### {heading}"));
1128    lines.push(String::new());
1129    lines.push(guidance.to_string());
1130    lines.push(String::new());
1131    let shown = items.len().min(FINDINGS_CAP);
1132    for f in &items[..shown] {
1133        lines.push(format!(
1134            "- {} — {}",
1135            finding_target_label(&f.target),
1136            f.detail
1137        ));
1138    }
1139    if items.len() > shown {
1140        lines.push(format!("- …and {} more", items.len() - shown));
1141    }
1142    lines.push(String::new());
1143}
1144
1145/// Render the open-findings block for the sync brief (C2) — the findings
1146/// `findings_store.current(key)` returned, grouped by class, each carrying the
1147/// conservative repair guidance the reconcile rules (C3) mandate. Empty string
1148/// when there are no open findings. `binding_id` feeds the buildable
1149/// `projection exclude` line in the uncovered group's guidance.
1150fn render_open_findings(findings: &[Finding], binding_id: &str) -> String {
1151    if findings.is_empty() {
1152        return String::new();
1153    }
1154    let mut lines: Vec<String> = vec![
1155        "## Open findings to repair".to_string(),
1156        String::new(),
1157        "The verify pass recorded these against the current source state. Repair them \
1158         conservatively (see the rules below); a finding you judge already correct needs \
1159         no write."
1160            .to_string(),
1161        String::new(),
1162    ];
1163
1164    let group = |class: FindingClass| -> Vec<&Finding> {
1165        findings.iter().filter(|f| f.class == class).collect()
1166    };
1167
1168    // Drifted / wrong — the anchored content changed: update only what moved
1169    // (conservatism rule "never rewrite unchanged sections").
1170    render_findings_group(
1171        &mut lines,
1172        "Drifted — the anchored content changed",
1173        "The source the entity describes moved. Update the affected section to match — \
1174         only the part that changed. If the entity is still accurate, leave it. Either \
1175         way, reset the anchor on the entity in ONE update call: `anchors_unset` the \
1176         row, then write it fresh in the same call's `anchors` (same artifact, grain, \
1177         class and source, no hash) — the next verify backfills the freshly observed \
1178         hash and the drift clears. A hashless re-declare WITHOUT the unset keeps the \
1179         stored baseline by design and clears nothing, and updating the entity alone, \
1180         or advancing the baseline, leaves the anchor drifted just the same.",
1181        &group(FindingClass::Drifted),
1182    );
1183    render_findings_group(
1184        &mut lines,
1185        "Wrong — an adjudicated content mismatch",
1186        "Adjudication found the entity no longer matches its source. Correct the \
1187         mismatched section; do not rewrite what still holds.",
1188        &group(FindingClass::Wrong),
1189    );
1190    // Unresolvable anchor — the artifact is gone: delete only if the concept is
1191    // removed entirely (conservatism rule "no deletion unless concept removed").
1192    render_findings_group(
1193        &mut lines,
1194        "Unresolvable anchor — the artifact is gone",
1195        "The source artifact an anchor references is no longer present. Delete the entity \
1196         **only** if the concept is removed entirely; otherwise leave it. Concept-level \
1197         removals are a prune concern with its own never-clobber / conflict-flag rules — \
1198         do not delete on a hunch here.",
1199        &group(FindingClass::UnresolvableAnchor),
1200    );
1201    // Uncovered — a source artifact with no entity: create only for a clearly-new
1202    // concept (conservatism rule "no new entities unless clearly-new concept").
1203    // The third disposition — deliberately not modeled — routes to `projection
1204    // exclude`, the verb whose gate accepts a stable artifact (`advance` gates on
1205    // the changed slice, so a stable uncovered artifact is undispositionable
1206    // there; three campaign runs hit that wall before this line existed).
1207    let uncovered_guidance = format!(
1208        "An in-scope source artifact has no anchor in the mem. Create an entity for it \
1209         **only** if it is a clearly-new concept with no existing entity; otherwise \
1210         extend the entity that already owns the concept, or leave it for a discovery \
1211         build. A third answer is legitimate: the artifact is mined and deliberately \
1212         warrants no entity. Record that with a rationale — it stops presenting here \
1213         from the next brief on:\n\n```bash\nmemstead projection exclude {binding_id} \
1214         --exclusions '{{\"<artifact>\": \"<rationale>\"}}'\n```"
1215    );
1216    render_findings_group(
1217        &mut lines,
1218        "Uncovered — a source artifact with no entity",
1219        &uncovered_guidance,
1220        &group(FindingClass::Uncovered),
1221    );
1222    // Queued — not yet adjudicated: verify owns these, not sync.
1223    render_findings_group(
1224        &mut lines,
1225        "Queued for adjudication — not yet judged",
1226        "These are not adjudicated yet — that is the verify pass's job, not sync's. \
1227         **Skip them here**; they become repairable only after verify classifies them as \
1228         drifted.",
1229        &group(FindingClass::QueuedForAdjudication),
1230    );
1231
1232    format!("{}\n", lines.join("\n"))
1233}
1234
1235/// Render the prune-proposals block for the sync brief (group F) — the deletion
1236/// proposals prune surfaced, each with its guarantee-appropriate treatment.
1237/// Empty string when there are no proposals.
1238///
1239/// **F3 / A5, structural:** every proposal here is exactly that — a *proposal*.
1240/// Nothing in this text (nor anywhere in the engine) deletes an entity; the
1241/// removal reaches the mem **only** when the agent acts on this brief through the
1242/// MCP mutation surface. `authored` entities never reach this block (prune
1243/// excludes them upstream); `derived` entities are flagged with their inputs,
1244/// never proposed for deletion.
1245fn render_prune_proposals(proposals: &[PruneProposal]) -> String {
1246    if proposals.is_empty() {
1247        return String::new();
1248    }
1249    let mut lines: Vec<String> = vec![
1250        "## Prune — proposed removals (you decide; nothing is auto-deleted)".to_string(),
1251        String::new(),
1252        "The source removed the artifacts these entities describe. Each item below is a \
1253         **proposal**: prune writes nothing — you enact (or reject) the removal through the \
1254         normal MCP mutation surface. An `authored` entity is never proposed here; a `derived` \
1255         entity is flagged, never proposed for deletion."
1256            .to_string(),
1257        String::new(),
1258    ];
1259
1260    let group = |d: PruneDisposition| -> Vec<&PruneProposal> {
1261        proposals.iter().filter(|p| p.disposition == d).collect()
1262    };
1263
1264    // Clean-delete — never-clobber, base retrieved, merge clean: a confident
1265    // (still agent-enacted) delete proposal.
1266    let clean = group(PruneDisposition::CleanDelete);
1267    if !clean.is_empty() {
1268        lines.push("### Clean delete — never-clobber three-way merge is clean".to_string());
1269        lines.push(String::new());
1270        lines.push(
1271            "The source base leg was retrievable and the three-way merge found no model-side \
1272             divergence, so removal is safe. **Confirm, then delete via the mutation surface** — \
1273             this is still your call, not an auto-delete."
1274                .to_string(),
1275        );
1276        lines.push(String::new());
1277        let shown = clean.len().min(FINDINGS_CAP);
1278        for p in &clean[..shown] {
1279            lines.push(format!(
1280                "- `{}` — source artifact(s) gone: {}",
1281                p.entity,
1282                artifact_list(&p.artifacts)
1283            ));
1284        }
1285        if clean.len() > shown {
1286            lines.push(format!("- …and {} more", clean.len() - shown));
1287        }
1288        lines.push(String::new());
1289    }
1290
1291    // Conflict-flag — both sides presented, never an auto-write over an edit.
1292    let conflict = group(PruneDisposition::ConflictFlag);
1293    if !conflict.is_empty() {
1294        lines.push("### Conflict-flag — decide, never overwrite a model-side edit".to_string());
1295        lines.push(String::new());
1296        lines.push(
1297            "No retrievable base leg to merge against (a non-git source, or an anchor with no \
1298             pinned version). **Both sides are shown — decide deliberately.** If the concept is \
1299             truly gone, delete via the mutation surface; if the model side was edited on \
1300             purpose, keep it. Prune never overwrites a model-side edit for you."
1301                .to_string(),
1302        );
1303        lines.push(String::new());
1304        let shown = conflict.len().min(FINDINGS_CAP);
1305        for p in &conflict[..shown] {
1306            lines.push(format!(
1307                "- `{}` — **source side:** artifact(s) gone: {}; **model side:** the entity is \
1308                 still present (may carry edits) — you decide.",
1309                p.entity,
1310                artifact_list(&p.artifacts)
1311            ));
1312        }
1313        if conflict.len() > shown {
1314            lines.push(format!("- …and {} more", conflict.len() - shown));
1315        }
1316        lines.push(String::new());
1317    }
1318
1319    // Derived-flagged — flagged with inputs, never proposed for deletion (F3).
1320    let derived = group(PruneDisposition::DerivedFlagged);
1321    if !derived.is_empty() {
1322        lines.push("### Derived — flagged, NOT proposed for deletion".to_string());
1323        lines.push(String::new());
1324        lines.push(
1325            "These entities were **derived** from other inputs. A derived entity is flagged, \
1326             never auto-proposed for deletion — its inputs may still hold even though one source \
1327             artifact vanished. Re-examine the inputs before removing anything."
1328                .to_string(),
1329        );
1330        lines.push(String::new());
1331        let shown = derived.len().min(FINDINGS_CAP);
1332        for p in &derived[..shown] {
1333            let inputs = if p.derived_inputs.is_empty() {
1334                "(no recorded inputs)".to_string()
1335            } else {
1336                artifact_list(&p.derived_inputs)
1337            };
1338            lines.push(format!(
1339                "- `{}` — derived from: {}; source artifact(s) gone: {}.",
1340                p.entity,
1341                inputs,
1342                artifact_list(&p.artifacts)
1343            ));
1344        }
1345        if derived.len() > shown {
1346            lines.push(format!("- …and {} more", derived.len() - shown));
1347        }
1348        lines.push(String::new());
1349    }
1350
1351    format!("{}\n", lines.join("\n"))
1352}
1353
1354/// A compact backtick-joined artifact list.
1355fn artifact_list(artifacts: &[String]) -> String {
1356    if artifacts.is_empty() {
1357        return "(none)".to_string();
1358    }
1359    artifacts
1360        .iter()
1361        .map(|a| format!("`{a}`"))
1362        .collect::<Vec<_>>()
1363        .join(", ")
1364}
1365
1366/// Render the sync brief's `## Situation` block — the sole-maintenance-writer
1367/// mandate and the commits-nothing / engine-commits-per-mutation posture (C3).
1368fn render_sync_situation(resolved: &ResolvedIngest) -> String {
1369    format!(
1370        "## Sync — repair the graph to match the source\n\n\
1371         You are running the sync pass for `{}`. Sync is the graph's **sole maintenance \
1372         writer**: the only place the destination mem `{}` is repaired to match its \
1373         source. Two inputs steer this pass — the source changes since the last sync, and \
1374         the open verify findings — both below. Work them: update, create, relate, and \
1375         (rarely) delete entities so the graph again matches the source.\n\n\
1376         Every mutation routes through the normal MCP mutation surface, and the engine \
1377         commits each one **per-mutation** to the mem's own gitdir. You **stage nothing \
1378         and commit nothing yourself** — not the graph, not the code. Sync commits \
1379         nothing.\n\n",
1380        resolved.name, resolved.destination_mem
1381    )
1382}
1383
1384/// Render the adopt / onboarding block (C3's first-sync/adopt framing; E1's
1385/// brief half): a mem that predates its binding is onboarding, expected-0%, with
1386/// the concrete backfill path — never a failure or red verdict.
1387fn render_adopt_framing(resolved: &ResolvedIngest) -> String {
1388    format!(
1389        "## First sync — adopting `{}`\n\n\
1390         This mem predates its binding: it has no anchors and no prior sync baseline, so \
1391         **0% anchored is expected — this is onboarding, not a failure.** Do not read it \
1392         as drift or a red verdict. There is no cursor to diff against, so the baseline is \
1393         the **current** source HEAD — do **not** replay the whole history; treat the \
1394         current source state as the starting point, and this is a **first sync**.\n\n\
1395         **Backfill path:** run `memstead projection verify {}` to enumerate the in-scope \
1396         source artifacts that carry no entity yet, then cover the clearly-new concepts \
1397         among them through the normal MCP mutation surface — the same conservative rules \
1398         below apply. Backfilling is incremental: a partial pass is fine, and the next \
1399         sync continues where you left off.\n\n",
1400        resolved.destination_mem, resolved.name
1401    )
1402}
1403
1404/// Render the **stale-claim search** block — the bounded step that closes the
1405/// slice-blinkering blind spot: a changed fact can be claimed by entities
1406/// whose anchors lie entirely outside the changed slice, so steering repairs
1407/// at slice-anchored entities alone leaves those claims standing falsified.
1408///
1409/// The shape is deliberately bounded, and the prose binds itself to **the
1410/// changed facts extracted from the slice**: a cosmetic change (formatting,
1411/// comments, moves that alter no fact) yields an empty fact set, and an empty
1412/// fact set instructs nothing — no whole-mem sweep, no live-verify of every
1413/// entity, no rewrite license. Rendered only when the cursor carries actual
1414/// changed artifacts (never for reseed-only / no-signal-only passes).
1415fn render_stale_claim_search(resolved: &ResolvedIngest) -> String {
1416    format!(
1417        "## Stale claims beyond the slice — search, then judge\n\n\
1418         A changed fact can be claimed by an entity whose anchors are all outside the \
1419         changed slice — anchor-steered repairs alone would leave that claim standing \
1420         falsified. Extract the **changed facts** from the changed artifacts above: \
1421         renamed identifiers, changed values or defaults, changed behaviors (e.g. an \
1422         exit code, a flag's meaning), removed or moved concepts. For each changed \
1423         fact, search the destination mem `{}` for claims about it (`memstead_search` \
1424         and its variants — try the new name, the old name/value, and close synonyms), \
1425         and judge **only** the entities whose claims actually mention a changed fact: \
1426         repair a claim the change falsifies, leave everything else untouched.\n\n\
1427         This is a bounded fact-search, not a live-verify of every entity and not a \
1428         rewrite license. If the changes carry no factual claims (formatting, \
1429         comments, cosmetic moves), the fact set is empty and this step ends with no \
1430         search and no edits.\n\n",
1431        resolved.destination_mem
1432    )
1433}
1434
1435/// Render the sync brief's conservatism block — the whole of `/reconcile`'s
1436/// absorbed judgment (C3): the five conservatism rules, edge-removal
1437/// conservatism, and rationale-not-changelog.
1438fn render_sync_conservatism() -> String {
1439    let lines: Vec<&str> = vec![
1440        "## How to repair — be conservative",
1441        "",
1442        "Repair only what the source changes and the findings above actually justify:",
1443        "",
1444        // The five conservatism rules.
1445        "- **Unsure whether an entity is affected — skip it.** A missed update is a later \
1446         finding; a wrong rewrite is damage.",
1447        "- **Do not create a new entity unless the change clearly introduces a new concept \
1448         with no existing entity.** Prefer updating the entity that already owns the \
1449         concept.",
1450        "- **Do not delete an entity unless the change removes the concept entirely.** \
1451         Deletions a prune pass surfaces follow prune's own never-clobber / conflict-flag \
1452         rules — never delete on a hunch here.",
1453        "- **Never rewrite a section that has not changed** — touch only the part the \
1454         change or finding actually affects.",
1455        "- **No speculative edges — add only relationships the diff literally introduces** \
1456         (a new `use` / `import` / dependency you can point at in the change).",
1457        // Edge-removal conservatism.
1458        "- **A dropped dependency FLAGS, it does not auto-remove.** If the change removes an \
1459         import or dependency, leave the matching edge intact and note it for a later \
1460         audit — removals are ambiguous (temporary refactor vs. permanent cut), and a \
1461         stale edge is less damaging than an erased real one. **Edge removal is out of \
1462         scope for sync.**",
1463        // Rationale-not-changelog.
1464        "- **Rationale is reasoning, not a changelog.** When you record why a change was \
1465         made, append the *reasoning* (why this approach, which trade-offs) — never \
1466         `[commit <hash>]` log-style entries.",
1467        "",
1468    ];
1469
1470    format!("{}\n", lines.join("\n"))
1471}
1472
1473/// Render the **sync brief** (C2/C3) — the *single* channel through which
1474/// maintenance-writing work reaches an agent.
1475///
1476/// One brief carries **both** inputs: the cursor slice (`cursor`, rendered via
1477/// [`render_changed_slice`], which also carries the first-sync reseed framing and
1478/// the disposition-recording step) and the open verify findings (`findings`, the
1479/// store's `current(key)` slice). It absorbs the whole of `/reconcile`'s judgment
1480/// (C3): the five conservatism rules, edge-removal conservatism,
1481/// rationale-not-changelog, the commits-nothing / engine-commits-per-mutation
1482/// posture, and — when `adopt` is set — the first-sync/adopt onboarding framing
1483/// (E1's brief half). A rule-by-rule absorption map records where each retired
1484/// reconcile rule now lives (bundle plan `05-verify-sync-engine`, C4).
1485///
1486/// A slice that carries actual changed artifacts additionally renders the
1487/// bounded **stale-claim search** step ([`render_stale_claim_search`]) — the
1488/// beyond-the-slice fact search that catches claims falsified by the change in
1489/// entities whose anchors never intersect the slice.
1490///
1491/// Prune proposals (group F) ride this same brief — F3's single-writer
1492/// invariant: every prune removal reaches the mem only via an agent acting on
1493/// this sync brief. They are rendered as proposals only; nothing is auto-deleted.
1494///
1495/// When nothing has moved, no findings are open, no prune proposals exist, and
1496/// this is not an adopt pass, the brief renders a compact "nothing to sync" note
1497/// instead of the repair machinery — a valid, silent outcome mirroring the build
1498/// brief's no-op roam.
1499pub fn render_sync_brief(
1500    resolved: &ResolvedIngest,
1501    cursor: &SourceCursor,
1502    findings: &[Finding],
1503    prune: &[PruneProposal],
1504    adopt: bool,
1505) -> String {
1506    let preface = render_changed_slice(cursor);
1507    let open_findings = render_open_findings(findings, &resolved.name);
1508    let prune_block = render_prune_proposals(prune);
1509    let has_work =
1510        adopt || !preface.is_empty() || !open_findings.is_empty() || !prune_block.is_empty();
1511
1512    let mut parts: Vec<String> = vec![render_sync_situation(resolved)];
1513
1514    if !has_work {
1515        parts.push(
1516            "## Nothing to sync\n\nThe source has not moved since the last sync, no \
1517             verify findings are open, and no prune proposals stand. There is nothing to \
1518             repair this pass — reporting \"no changes\" is a valid outcome.\n\n"
1519                .to_string(),
1520        );
1521        return parts
1522            .into_iter()
1523            .filter(|p| !p.is_empty())
1524            .collect::<Vec<_>>()
1525            .join("");
1526    }
1527
1528    if adopt {
1529        parts.push(render_adopt_framing(resolved));
1530    }
1531    parts.push(preface);
1532    // The stale-claim search rides only a slice that carries actual changed
1533    // artifacts — its facts are extracted FROM those artifacts, so a pass
1534    // with no changes (findings-only, reseed-only, prune-only) renders none.
1535    if cursor.any_changes {
1536        parts.push(render_stale_claim_search(resolved));
1537    }
1538    parts.push(open_findings);
1539    parts.push(prune_block);
1540    parts.push(render_anchor_instruction(resolved));
1541    parts.push(render_sync_conservatism());
1542
1543    parts
1544        .into_iter()
1545        .filter(|p| !p.is_empty())
1546        .collect::<Vec<_>>()
1547        .join("")
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use super::*;
1553    use crate::ingest::resolve::Source;
1554    use crate::pipeline::{IngestTrigger, PatternEntry};
1555
1556    fn guidance(goal: Option<&str>, avoid: Option<&str>) -> ResolvedGuidance {
1557        ResolvedGuidance {
1558            goal: goal.map(str::to_string),
1559            avoid: avoid.map(str::to_string),
1560        }
1561    }
1562
1563    /// Goal and avoid both present: two headers, trimmed prose, block ends in
1564    /// a blank line — byte-for-byte the plugin's `goalAndAvoidBlock`.
1565    #[test]
1566    fn renders_goal_and_avoid_blocks() {
1567        let out = render_goal_and_avoid(&guidance(Some("  build coverage  "), Some("no stubs")));
1568        assert_eq!(
1569            out,
1570            "## Goal\n\nbuild coverage\n\n## Failure modes to avoid\n\nno stubs\n\n"
1571        );
1572    }
1573
1574    /// Goal only: a single header block ending in a blank line.
1575    #[test]
1576    fn renders_goal_only() {
1577        assert_eq!(
1578            render_goal_and_avoid(&guidance(Some("build coverage"), None)),
1579            "## Goal\n\nbuild coverage\n\n"
1580        );
1581    }
1582
1583    /// Avoid only: a single header block ending in a blank line.
1584    #[test]
1585    fn renders_avoid_only() {
1586        assert_eq!(
1587            render_goal_and_avoid(&guidance(None, Some("no stubs"))),
1588            "## Failure modes to avoid\n\nno stubs\n\n"
1589        );
1590    }
1591
1592    /// Neither present (and no pass-through): a lone newline, matching the
1593    /// plugin's `lines.join('\n') + '\n'` on an empty block.
1594    #[test]
1595    fn empty_guidance_yields_a_newline() {
1596        assert_eq!(render_goal_and_avoid(&guidance(None, None)), "\n");
1597        // An all-whitespace field is treated as absent.
1598        assert_eq!(render_goal_and_avoid(&guidance(Some("   "), None)), "\n");
1599    }
1600
1601    fn primary(medium_type: MediumType, scope: Vec<PatternEntry>) -> ResolvedSource {
1602        ResolvedSource::Primary(Source {
1603            name: "f".to_string(),
1604            medium_type,
1605            pointer: "../src".to_string(),
1606            change_detection: None,
1607            scope,
1608            engagement: None,
1609            preparation: None,
1610        })
1611    }
1612
1613    fn resolved(name: &str, intent: Option<&str>, sources: Vec<ResolvedSource>) -> ResolvedIngest {
1614        ResolvedIngest {
1615            name: name.to_string(),
1616            mode: BuildMode::Discovery,
1617            trigger: IngestTrigger::Loop,
1618            batch_size: 20,
1619            deny_paths: vec![],
1620            projection_ref: format!("{name}/p"),
1621            projection_mem: name.to_string(),
1622            projection_name: "p".to_string(),
1623            intent: intent.map(str::to_string),
1624            sources,
1625            destination_mem: name.to_string(),
1626            rules: None,
1627            post_actions: None,
1628        }
1629    }
1630
1631    fn process_present(name: &str) -> ProcessMemInfo {
1632        ProcessMemInfo {
1633            present: true,
1634            skipped: false,
1635            notice: None,
1636            leaf_name: name.to_string(),
1637            mem_label: format!("ingest/{name}"),
1638        }
1639    }
1640
1641    fn allow(path: &str) -> PatternEntry {
1642        PatternEntry {
1643            path: path.to_string(),
1644            mode: PatternMode::Allow,
1645        }
1646    }
1647
1648    fn deny(path: &str) -> PatternEntry {
1649        PatternEntry {
1650            path: path.to_string(),
1651            mode: PatternMode::Deny,
1652        }
1653    }
1654
1655    /// The about-the-source block trims the intent; no intent → empty string.
1656    #[test]
1657    fn renders_intent() {
1658        let r = resolved("macos", Some("  Swift app source.  "), vec![]);
1659        assert_eq!(
1660            render_intent(&r),
1661            "## About the source\n\nSwift app source.\n\n"
1662        );
1663        let none = resolved("macos", None, vec![]);
1664        assert_eq!(render_intent(&none), "");
1665    }
1666
1667    /// The situation block prints the name/mode, the three fixed paragraphs,
1668    /// and the present-process-mem line, ending in a blank line.
1669    #[test]
1670    fn renders_situation_with_present_process_mem() {
1671        let r = resolved("macos", None, vec![]);
1672        let out = render_situation(&r, &process_present("macos"));
1673        assert!(out.starts_with("## Situation\n\nYou are running one iteration of `macos` (discovery mode) inside a loop."));
1674        assert!(out.contains("Mutating the destination is this run's mandate:"));
1675        assert!(out.contains("The `PreCompact` hook fires near the limit"));
1676        assert!(out.contains("A paired process mem `ingest/macos` (schema `ingest@0.5.0`) carries destination-quality debt"));
1677        assert!(
1678            out.ends_with("write rules.\n\n"),
1679            "block ends in a blank line"
1680        );
1681    }
1682
1683    /// The skipped (one-shot) and failed-to-create process-mem branches each
1684    /// render their own note.
1685    #[test]
1686    fn situation_process_mem_branches() {
1687        let mut r = resolved("os", None, vec![]);
1688        r.mode = BuildMode::OneShot;
1689        let skipped = ProcessMemInfo {
1690            present: false,
1691            skipped: true,
1692            notice: None,
1693            leaf_name: "os".to_string(),
1694            mem_label: "ingest/os".to_string(),
1695        };
1696        assert!(
1697            render_situation(&r, &skipped)
1698                .contains("No process mem is paired with this ingest (mode=one-shot;")
1699        );
1700
1701        let failed = ProcessMemInfo {
1702            present: false,
1703            skipped: false,
1704            notice: Some("engine offline".to_string()),
1705            leaf_name: "os".to_string(),
1706            mem_label: "ingest/os".to_string(),
1707        };
1708        let out = render_situation(&resolved("os", None, vec![]), &failed);
1709        assert!(out.contains("could not be auto-created — engine offline."));
1710        assert!(out.contains("memstead mem init os --org-path ingest --schema ingest@0.5.0"));
1711    }
1712
1713    /// Operative data: a primary source with paths/ignore, a reference mem
1714    /// with its cross-mem note, the destination with its schema, and the
1715    /// paired process mem — byte-for-byte the plugin's block.
1716    #[test]
1717    fn renders_operative_data_full() {
1718        let r = resolved(
1719            "macos",
1720            None,
1721            vec![
1722                primary(
1723                    MediumType::Codebase,
1724                    vec![allow("src/**/*.swift"), deny("src/gen/**")],
1725                ),
1726                ResolvedSource::Reference {
1727                    mem: "engine".to_string(),
1728                },
1729            ],
1730        );
1731        let out = render_operative_data(
1732            &r,
1733            &process_present("macos"),
1734            Some("macos-code@0.1.0"),
1735            None,
1736            &[],
1737        );
1738        let expected = "\
1739## Operative data
1740
1741### Sources
1742
1743- **f** (codebase, primary) — `../src`
1744  - Paths: src/**/*.swift
1745  - Ignore: src/gen/**
1746- **graph** (reference) — mem: engine
1747
1748Sources tagged `(reference)` are read-only context for cross-mem edges — search them, never write into them. Only `(primary)` sources are ingested into the destination.
1749
1750**Cross-mem references:** consult `memstead_search mem=engine` before authoring cross-mem edges. The target entity must exist — a wiki-link or relationship to a missing target either auto-stubs (silent) or fails authorization (`CROSS_MEM_RELATION`).
1751
1752### Destination
1753
1754- **macos** — schema: `macos-code@0.1.0`
1755
1756### Paired process mem
1757
1758- **ingest/macos** — schema: `ingest@0.5.0`. Inspect via `memstead_overview` / `memstead_search mem=macos`.
1759\n";
1760        assert_eq!(out, expected);
1761    }
1762
1763    /// Operative data without references or a destination schema: no cross-mem
1764    /// note, a bare destination line.
1765    #[test]
1766    fn renders_operative_data_minimal() {
1767        let r = resolved("g", None, vec![primary(MediumType::Filesystem, vec![])]);
1768        let skipped = ProcessMemInfo {
1769            present: false,
1770            skipped: true,
1771            notice: None,
1772            leaf_name: "g".to_string(),
1773            mem_label: "ingest/g".to_string(),
1774        };
1775        let out = render_operative_data(&r, &skipped, None, Some("**absent** — probe"), &[]);
1776        // The bullet carries the pointer: an agent told to read a source
1777        // must be able to see WHICH tree it was pointed at.
1778        assert!(out.contains("- **f** (filesystem, primary) — `"));
1779        assert!(!out.contains("Cross-mem references"), "no reference note");
1780        assert!(out.contains("### Destination\n\n- **g**\n"));
1781        // The caller decides the destination note — this renderer only
1782        // places it, because the remedy depends on the workspace shape.
1783        assert!(
1784            out.contains("**absent** — probe"),
1785            "the caller's destination note must be rendered: {out}",
1786        );
1787        assert!(
1788            !out.contains("Paired process mem"),
1789            "skipped process mem omitted"
1790        );
1791    }
1792
1793    /// A source whose scope still speaks the retired workspace-relative
1794    /// dialect is warned about IN THE BRIEF — the operative-data block, the
1795    /// one surface a binding running only build and sync ever reads. Without
1796    /// it the notes reach only the verify report and the `--full` refusal,
1797    /// and such a binding is never told its scope selects nothing.
1798    #[test]
1799    fn operative_data_warns_on_retired_scope_dialect() {
1800        let r = resolved(
1801            "g",
1802            None,
1803            // Pointer `../src` (the helper's default): one pattern in the
1804            // retired dialect (begins with the pointer), one converged.
1805            vec![primary(
1806                MediumType::Filesystem,
1807                vec![allow("../src/**/*.md"), allow("notes/**")],
1808            )],
1809        );
1810        let skipped = ProcessMemInfo {
1811            present: false,
1812            skipped: true,
1813            notice: None,
1814            leaf_name: "g".to_string(),
1815            mem_label: "ingest/g".to_string(),
1816        };
1817        let out = render_operative_data(&r, &skipped, None, None, &[]);
1818        assert!(
1819            out.contains("workspace root"),
1820            "the block names the retired dialect: {out}"
1821        );
1822        assert!(
1823            out.contains("../src/**/*.md"),
1824            "the offending pattern is named: {out}"
1825        );
1826        assert!(
1827            out.contains("`**/*.md`"),
1828            "the mechanical rewrite is offered: {out}"
1829        );
1830
1831        // A converged scope renders no warning.
1832        let clean = resolved(
1833            "g",
1834            None,
1835            vec![primary(MediumType::Filesystem, vec![allow("**/*.md")])],
1836        );
1837        let out2 = render_operative_data(&clean, &skipped, None, None, &[]);
1838        assert!(
1839            !out2.contains("workspace root"),
1840            "no warning without a retired-dialect pattern: {out2}"
1841        );
1842    }
1843
1844    /// The discovery assembly concatenates the truthy blocks in order; an
1845    /// empty changed-slice preface (source unmoved) drops out.
1846    #[test]
1847    fn assembles_discovery_brief() {
1848        let r = resolved(
1849            "macos",
1850            Some("Swift source."),
1851            vec![primary(MediumType::Codebase, vec![allow("src/**")])],
1852        );
1853        let g = guidance(Some("build coverage"), None);
1854        let pm = process_present("macos");
1855        let brief = assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], "");
1856
1857        // Blocks appear in order and the empty preface is dropped.
1858        let sit = brief.find("## Situation").unwrap();
1859        let src = brief.find("## About the source").unwrap();
1860        let goal = brief.find("## Goal").unwrap();
1861        let op = brief.find("## Operative data").unwrap();
1862        let anchors = brief.find("## Provenance — anchor your writes").unwrap();
1863        assert!(
1864            sit < src && src < goal && goal < op && op < anchors,
1865            "blocks in brief order"
1866        );
1867        assert!(
1868            !brief.contains("## Source changes"),
1869            "no changed-slice block when preface empty"
1870        );
1871
1872        // A non-empty preface is appended verbatim at the end.
1873        let with_slice = assemble_discovery_brief(
1874            &r,
1875            &g,
1876            &pm,
1877            Some("s@1"),
1878            None,
1879            &[],
1880            "## Source changes\n\n…\n\n",
1881        );
1882        assert!(with_slice.ends_with("## Source changes\n\n…\n\n"));
1883    }
1884
1885    fn slice(deleted: &[&str], modified: &[&str], added: &[&str]) -> Slice {
1886        Slice {
1887            deleted: deleted.iter().map(|s| s.to_string()).collect(),
1888            modified: modified.iter().map(|s| s.to_string()).collect(),
1889            added: added.iter().map(|s| s.to_string()).collect(),
1890        }
1891    }
1892
1893    fn cmd(key: &str, token: &str) -> SyncCommand {
1894        SyncCommand {
1895            key: key.to_string(),
1896            token: token.to_string(),
1897        }
1898    }
1899
1900    fn note(source: &str, reason: NoSignalReason) -> NoSignalNote {
1901        NoSignalNote {
1902            medium_type: None,
1903            source: source.to_string(),
1904            reason,
1905        }
1906    }
1907
1908    /// The provenance block names a prepared-form source and scopes the
1909    /// `content` advice to file and span anchors; a binding without a
1910    /// preparation carries no such paragraph.
1911    #[test]
1912    fn anchor_instruction_names_prepared_form_sources() {
1913        let mut resolved = resolved("home", None, vec![primary(MediumType::Codebase, vec![])]);
1914        let plain = render_anchor_instruction(&resolved);
1915        assert!(!plain.contains("hash a prepared form"));
1916        if let Some(ResolvedSource::Primary(src)) = resolved.sources.first_mut() {
1917            src.preparation = Some(crate::preparation::CODE_MAP.to_string());
1918        }
1919        let prepared = render_anchor_instruction(&resolved);
1920        assert!(
1921            prepared.contains("hash a prepared form (`code-map`)"),
1922            "{prepared}"
1923        );
1924        assert!(prepared.contains("interface digest"));
1925        assert!(prepared.contains("for a `file` or `span` anchor pass the artifact's `content`"));
1926        assert!(prepared.contains("a `tree` anchor takes no content"));
1927    }
1928
1929    /// A delivery sequence renders in its total order, numbered by position,
1930    /// capped at the batch with the remainder counted, disposed units
1931    /// subtracted but counted, and its unit ids kept out of the alphabetical
1932    /// class lists (a file-level id in the same slice still lists there).
1933    #[test]
1934    fn changed_slice_renders_delivery_sequences_in_order() {
1935        use crate::preparation::UnitChange;
1936        let unit = |id: &str, order: &str, change: UnitChange, disposed: bool| DeliveredUnit {
1937            id: id.to_string(),
1938            order_key: order.to_string(),
1939            change,
1940            disposed,
1941        };
1942        let units = vec![
1943            unit(
1944                "log/b.md#2026-08-20T00:00:00",
1945                "2026-08-20T00:00:00",
1946                UnitChange::Added,
1947                true,
1948            ),
1949            unit(
1950                "log/a.md#2026-08-21T00:00:00",
1951                "2026-08-21T00:00:00",
1952                UnitChange::Deleted,
1953                false,
1954            ),
1955            unit(
1956                "log/b.md#2026-08-22T00:00:00",
1957                "2026-08-22T00:00:00",
1958                UnitChange::Modified,
1959                false,
1960            ),
1961            unit(
1962                "log/a.md#2026-08-23T00:00:00",
1963                "2026-08-23T00:00:00",
1964                UnitChange::Added,
1965                false,
1966            ),
1967        ];
1968        let cursor = SourceCursor {
1969            // `slice(deleted, modified, added)`.
1970            union: slice(
1971                &["log/a.md#2026-08-21T00:00:00"],
1972                &["log/b.md#2026-08-22T00:00:00"],
1973                &[
1974                    "log/a.md#2026-08-23T00:00:00",
1975                    "log/b.md#2026-08-20T00:00:00",
1976                    "other/x.rs",
1977                ],
1978            ),
1979            write_commands: vec![],
1980            reseed: vec![],
1981            no_signal: vec![],
1982            any_changes: true,
1983            degraded: false,
1984            dead_denies: vec![],
1985            dest_mem: "home".to_string(),
1986            binding_id: "home/log".to_string(),
1987            delivery: vec![DeliverySequence {
1988                source: "log".to_string(),
1989                preparation: "dated-entries".to_string(),
1990                first_run: false,
1991                degraded: true,
1992                batch: 2,
1993                units,
1994            }],
1995        };
1996        let out = render_changed_slice(&cursor);
1997        assert!(
1998            out.contains("### Delivery sequence: `log` (`dated-entries`)"),
1999            "{out}"
2000        );
2001        assert!(out.contains("The units that changed since the last pass"));
2002        assert!(out.contains("No baseline content was retrievable"));
2003        let listed: Vec<&str> = out
2004            .lines()
2005            .filter(|l| l.starts_with(|c: char| c.is_ascii_digit()))
2006            .collect();
2007        assert_eq!(
2008            listed,
2009            vec![
2010                "2. `log/a.md#2026-08-21T00:00:00` (deleted)",
2011                "3. `log/b.md#2026-08-22T00:00:00` (changed)",
2012            ],
2013            "positions are total-order positions; the disposed first unit is skipped"
2014        );
2015        assert!(out.contains("…and 1 more, presented in order once these are disposed"));
2016        assert!(out.contains("1 unit of this sequence already disposed"));
2017        // The class lists carry only the file-level id.
2018        assert!(out.contains("**Added:**\n- `other/x.rs`\n"), "{out}");
2019        assert!(!out.contains("**Modified:**"));
2020        assert!(!out.contains("**Deleted:**"));
2021    }
2022
2023    /// No changes and no reseed → the block is empty (brief stays a plain roam).
2024    #[test]
2025    fn changed_slice_empty_when_nothing_moved() {
2026        let cursor = SourceCursor {
2027            union: slice(&[], &[], &[]),
2028            write_commands: vec![],
2029            reseed: vec![],
2030            no_signal: vec![],
2031            any_changes: false,
2032            degraded: false,
2033            dead_denies: vec![],
2034            dest_mem: "engine".to_string(),
2035            binding_id: "engine/graph".to_string(),
2036            delivery: vec![],
2037        };
2038        assert_eq!(render_changed_slice(&cursor), "");
2039    }
2040
2041    /// A zero-selecting deny entry surfaces as a rendered warning even when
2042    /// nothing else moved — it is never a silent no-op. The entry name and the
2043    /// migration hint both appear.
2044    #[test]
2045    fn changed_slice_renders_dead_deny_warning() {
2046        let cursor = SourceCursor {
2047            union: slice(&[], &[], &[]),
2048            write_commands: vec![],
2049            reseed: vec![],
2050            no_signal: vec![],
2051            any_changes: false,
2052            degraded: false,
2053            dead_denies: vec!["dev".to_string(), "typo/**".to_string()],
2054            dest_mem: "engine".to_string(),
2055            binding_id: "engine/graph".to_string(),
2056            delivery: vec![],
2057        };
2058        let out = render_changed_slice(&cursor);
2059        assert!(out.contains("deny_paths` entries match nothing"));
2060        assert!(out.contains("- `dev`"));
2061        assert!(out.contains("- `typo/**`"));
2062    }
2063
2064    /// A changed pass renders deleted-first, then the recording block — built
2065    /// here from single-line literals transcribed from the plugin so any
2066    /// line-continuation drift in the impl is caught.
2067    #[test]
2068    fn changed_slice_renders_slice_and_recording() {
2069        let cursor = SourceCursor {
2070            union: slice(&["a.rs"], &["b.rs"], &[]),
2071            write_commands: vec![cmd("engine-graph/source", "HEADSHA")],
2072            reseed: vec![],
2073            no_signal: vec![],
2074            any_changes: true,
2075            degraded: false,
2076            dead_denies: vec![],
2077            dest_mem: "engine".to_string(),
2078            binding_id: "engine/graph".to_string(),
2079            delivery: vec![],
2080        };
2081        let expected_lines = [
2082            "## Source changes since the last sync\n",
2083            "The source moved since this graph was last synced. Steer this pass at these changed artifacts **first** — they are where the graph is most likely now wrong.\n",
2084            "**Deleted:**",
2085            "- `a.rs`",
2086            "",
2087            "**Modified:**",
2088            "- `b.rs`",
2089            "",
2090            "### Recording your dispositions (do this LAST)\n",
2091            "Only after you have worked the changed artifacts above — and only for the artifacts you actually judged — record a disposition for each, so the next pass targets just what changes next. This advance is resumable and non-stalling: a partial pass is honored, and if the source moves mid-pass the remaining slice re-presents (remaining + new) without losing your recorded work.\n",
2092            "Anchored work disposes itself: at advance time, every listed artifact that an anchor in the destination mem references is marked `worked` automatically (an explicit disposition you pass wins over the auto-mark). Supply dispositions only for the residue — artifacts you skipped, judged out of intent, or worked without anchors. The gate accepts only artifact ids listed above — an unknown id refuses the whole call. When every artifact is disposed, the sync baseline advances automatically. Run:\n",
2093            "```sh",
2094            r#"memstead projection advance engine/graph --dispositions '{"<artifact>": "<disposition>", ...}'"#,
2095            "```",
2096            "If you were interrupted before finishing, that is fine — your recorded dispositions persist, and the next run re-presents only what is left.\n",
2097        ];
2098        assert_eq!(
2099            render_changed_slice(&cursor),
2100            format!("{}\n", expected_lines.join("\n"))
2101        );
2102    }
2103
2104    /// The reseed-only path names the first-sync keys and still emits the
2105    /// recording block (the reseed baselines).
2106    #[test]
2107    fn changed_slice_reseed_only() {
2108        let cursor = SourceCursor {
2109            union: slice(&[], &[], &[]),
2110            write_commands: vec![],
2111            reseed: vec![cmd("ing/f", "TOK")],
2112            no_signal: vec![],
2113            any_changes: false,
2114            degraded: false,
2115            dead_denies: vec![],
2116            dest_mem: "d".to_string(),
2117            binding_id: "d/p".to_string(),
2118            delivery: vec![],
2119        };
2120        let out = render_changed_slice(&cursor);
2121        assert!(out.starts_with("## Source changes since the last sync\n\n"));
2122        assert!(out.contains(
2123            "No usable sync baseline exists for `ing/f` — none was recorded, or the recorded one is not a commit of the source's repo (foreign or garbage-collected). Treating the current source state as the baseline. No priority slice from it this pass; proceed as usual."
2124        ));
2125        assert!(out.contains(
2126            r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2127        ));
2128        assert!(
2129            !out.contains("The source moved"),
2130            "no 'moved' copy when only reseeding"
2131        );
2132    }
2133
2134    /// Every no-signal reason renders a distinct, named note under the preface,
2135    /// distinguishable from one another and from a genuinely-unchanged source
2136    /// (which renders nothing). With no changes and no reseed there is no
2137    /// recording block, but the preface is non-empty — a source's blindness is
2138    /// visible. `signal:none` renders literally.
2139    #[test]
2140    fn changed_slice_renders_no_signal_reasons_distinguishably() {
2141        let cursor = SourceCursor {
2142            union: slice(&[], &[], &[]),
2143            write_commands: vec![],
2144            reseed: vec![],
2145            no_signal: vec![
2146                note("code-facet", NoSignalReason::Unscoped),
2147                note("plan-facet", NoSignalReason::DetectionNone),
2148                note("git-facet", NoSignalReason::GitUnavailable),
2149                note("ref-mem", NoSignalReason::GraphSnapshotMissing),
2150            ],
2151            any_changes: false,
2152            degraded: false,
2153            dead_denies: vec![],
2154            dest_mem: "d".to_string(),
2155            binding_id: "d/p".to_string(),
2156            delivery: vec![],
2157        };
2158        let out = render_changed_slice(&cursor);
2159        assert!(out.starts_with("## Source changes since the last sync\n"));
2160        assert!(out.contains("Some sources produced **no change signal**"));
2161        // Each source is named and carries its own distinct reason text.
2162        assert!(out.contains("- `code-facet`: unscoped facet (no allow patterns)"));
2163        assert!(
2164            out.contains("- `plan-facet`: `signal:none`"),
2165            "detection-none renders the literal signal:none state"
2166        );
2167        assert!(out.contains("- `git-facet`: git signal unavailable"));
2168        assert!(out.contains("- `ref-mem`: graph snapshot missing"));
2169        // The four reason texts are mutually distinct.
2170        let texts = [
2171            no_signal_reason_text(NoSignalReason::Unscoped, None),
2172            no_signal_reason_text(NoSignalReason::DetectionNone, None),
2173            no_signal_reason_text(NoSignalReason::GitUnavailable, None),
2174            no_signal_reason_text(NoSignalReason::GraphSnapshotMissing, None),
2175        ];
2176        for (i, a) in texts.iter().enumerate() {
2177            for b in &texts[i + 1..] {
2178                assert_ne!(a, b, "each no-signal reason must render distinctly");
2179            }
2180        }
2181        // No baseline to advance → no recording block, no "moved" copy.
2182        assert!(!out.contains("### Recording your dispositions"));
2183        assert!(!out.contains("The source moved"));
2184    }
2185
2186    /// A changed source and a no-signal source coexist: the changed slice AND
2187    /// the no-signal note both render in the one preface, and the changed
2188    /// source still emits its recording command.
2189    #[test]
2190    fn changed_slice_mixes_changes_and_no_signal() {
2191        let cursor = SourceCursor {
2192            union: slice(&[], &["b.rs"], &[]),
2193            write_commands: vec![cmd("ing/f", "HEAD")],
2194            reseed: vec![],
2195            no_signal: vec![note("other", NoSignalReason::Unscoped)],
2196            any_changes: true,
2197            degraded: false,
2198            dead_denies: vec![],
2199            dest_mem: "d".to_string(),
2200            binding_id: "d/p".to_string(),
2201            delivery: vec![],
2202        };
2203        let out = render_changed_slice(&cursor);
2204        assert!(out.contains("The source moved"));
2205        assert!(out.contains("**Modified:**"));
2206        assert!(out.contains("- `other`: unscoped facet"));
2207        assert!(out.contains("### Recording your dispositions"));
2208        assert!(out.contains(
2209            r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2210        ));
2211    }
2212
2213    /// The one-shot lens block: destination-set table, routing rule (when set),
2214    /// idempotency, report template, and archive note (when set).
2215    #[test]
2216    fn renders_one_shot_lens_block() {
2217        let mut r = resolved("os", Some("plan source"), vec![]);
2218        r.rules = Some(serde_json::json!({ "routing": "route each entity to its spec" }));
2219        r.post_actions = Some(serde_json::json!({ "archive_source": true }));
2220
2221        let out = render_one_shot_lens(&r, Some("planning@0.1.0"), Some("the plan graph"));
2222        assert!(out.starts_with("## Mode: one-shot — lens routing\n\n"));
2223        assert!(out.contains(
2224            "### Destination set\n\n| Mem | Schema | Purpose |\n|-------|--------|---------|\n| os | planning@0.1.0 | the plan graph |\n"
2225        ));
2226        assert!(out.contains("### Routing rule\n\n```\nroute each entity to its spec\n```\n"));
2227        assert!(out.contains("### Idempotency"));
2228        assert!(out.contains("### Report: os"));
2229        assert!(out.contains("### Archive after run"));
2230        assert!(out.ends_with("is set on this ingest.\n\n"));
2231
2232        // No routing / no archive → those sections are omitted; a bare schema
2233        // and default purpose fall back.
2234        let bare = resolved("os", None, vec![]);
2235        let out2 = render_one_shot_lens(&bare, None, None);
2236        assert!(out2.contains("| os | (none) | (no purpose declared) |"));
2237        assert!(!out2.contains("### Routing rule"));
2238        assert!(!out2.contains("### Archive after run"));
2239        assert!(out2.contains("### End-of-run report"));
2240    }
2241
2242    /// The one-shot brief assembles situation (one-shot mode) + intent +
2243    /// goal/avoid + operative-data + the lens block; no process mem, no slice.
2244    #[test]
2245    fn assembles_one_shot_brief() {
2246        let mut r = resolved(
2247            "os",
2248            Some("src"),
2249            vec![primary(MediumType::Filesystem, vec![])],
2250        );
2251        r.mode = BuildMode::OneShot;
2252        let g = guidance(Some("goal"), None);
2253        let skipped = ProcessMemInfo {
2254            present: false,
2255            skipped: true,
2256            notice: None,
2257            leaf_name: "os".to_string(),
2258            mem_label: "ingest/os".to_string(),
2259        };
2260        let brief =
2261            assemble_one_shot_brief(&r, &g, &skipped, Some("s@1"), None, &[], Some("purpose"));
2262        assert!(brief.contains("(one-shot mode)"));
2263        assert!(brief.contains("No process mem is paired with this ingest (mode=one-shot;"));
2264        assert!(brief.contains("## Mode: one-shot — lens routing"));
2265        assert!(
2266            brief.contains("## Provenance — anchor your writes"),
2267            "one-shot carries the anchor instruction"
2268        );
2269        assert!(
2270            !brief.contains("## Source changes"),
2271            "one-shot has no changed-slice"
2272        );
2273    }
2274
2275    /// Beyond SLICE_CAP entries an overflow line stands in; the degraded flag
2276    /// adds the coarse-targeting note. Also exercises shell-quoting a JSON
2277    /// digest token (embedded quotes).
2278    #[test]
2279    fn changed_slice_caps_and_degrades_and_quotes() {
2280        let many: Vec<String> = (0..SLICE_CAP + 3).map(|i| format!("f{i}.rs")).collect();
2281        let cursor = SourceCursor {
2282            union: Slice {
2283                deleted: vec![],
2284                modified: vec![],
2285                added: many,
2286            },
2287            write_commands: vec![cmd("ing/f", r#"{"v":1,"aggregate":"x"}"#)],
2288            reseed: vec![],
2289            no_signal: vec![],
2290            any_changes: true,
2291            degraded: true,
2292            dead_denies: vec![],
2293            dest_mem: "d".to_string(),
2294            binding_id: "d/p".to_string(),
2295            delivery: vec![],
2296        };
2297        let out = render_changed_slice(&cursor);
2298        assert!(out.contains(&format!("- …and {} more added", 3)));
2299        assert!(out.contains("Precise change history for one or more facets was unavailable"));
2300        // The brief renders the `projection advance` line (the token is no longer
2301        // an operator command — the engine computes and records it, D4/D7).
2302        assert!(out.contains(
2303            r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2304        ));
2305    }
2306
2307    // ---- verify + sync briefs (group C) ----------------------------------
2308
2309    fn finding(class: FindingClass, target: FindingTarget, detail: &str) -> Finding {
2310        Finding {
2311            key: crate::ingest::findings::FindingKey {
2312                binding_hash: "h".to_string(),
2313                source_head: "s".to_string(),
2314            },
2315            facet: "src".to_string(),
2316            target,
2317            class,
2318            detail: detail.to_string(),
2319            created_at: "1".to_string(),
2320        }
2321    }
2322
2323    fn anchor_target(entity: &str, artifact: &str) -> FindingTarget {
2324        FindingTarget::Anchor {
2325            entity: entity.to_string(),
2326            artifact: artifact.to_string(),
2327        }
2328    }
2329
2330    fn artifact_target(artifact: &str) -> FindingTarget {
2331        FindingTarget::Artifact {
2332            artifact: artifact.to_string(),
2333        }
2334    }
2335
2336    fn empty_cursor() -> SourceCursor {
2337        SourceCursor {
2338            union: slice(&[], &[], &[]),
2339            write_commands: vec![],
2340            reseed: vec![],
2341            no_signal: vec![],
2342            any_changes: false,
2343            degraded: false,
2344            dead_denies: vec![],
2345            dest_mem: "engine".to_string(),
2346            binding_id: "engine/graph".to_string(),
2347            delivery: vec![],
2348        }
2349    }
2350
2351    /// C1 — the verify brief measures + adjudicates, and carries NO
2352    /// destination-mutation instruction of any kind. It names the sync brief as
2353    /// the repair home and prints its explicit no-mutation refusal.
2354    #[test]
2355    fn verify_brief_measures_and_refuses_mutation() {
2356        let r = resolved("engine", None, vec![]);
2357        let out = render_verify_brief(&r, 3);
2358        // Measurement + capped adjudication instructions.
2359        assert!(out.starts_with("## Verify — measure fidelity, do not mutate"));
2360        assert!(out.contains("3 finding(s) are queued for adjudication"));
2361        assert!(out.contains("per-run adjudication cap"));
2362        assert!(out.contains("this is a measurement, not a repair"));
2363        // C1 REFUSAL: structurally no destination-mutation instruction. The
2364        // brief never tells the agent to write into the mem — it says the
2365        // opposite, and hands repairs to the sync brief.
2366        //
2367        // Reworded 2026-08-20. This assertion used to pin "Verify writes
2368        // **nothing** into the destination mem", which was false: a completed
2369        // run records its findings store, backfills observed anchor hashes and
2370        // writes a `#verified` baseline. The refusal this test exists to
2371        // protect is about ENTITY CONTENT — that is what an agent reading the
2372        // brief must not touch — so the claim is narrowed to what is true
2373        // rather than deleted, and the bookkeeping is asserted alongside it so
2374        // the correction cannot silently regress.
2375        assert!(out.contains("Verify writes **no entity content**"));
2376        assert!(out.contains("`#verified` baseline"));
2377        assert!(out.contains("memstead projection brief --sync"));
2378        // No create/update/relate/delete *instruction* — the only occurrences of
2379        // those verbs are in the negated "do not …" refusal line.
2380        assert!(out.contains("do not create or delete an entity"));
2381        assert!(!out.contains("via `memstead_create`"));
2382        assert!(!out.contains("Run `memstead_update`"));
2383
2384        // Backlog 0 → the spot-check phrasing, still no mutation instruction.
2385        let zero = render_verify_brief(&r, 0);
2386        assert!(zero.contains("No findings are queued for adjudication"));
2387        assert!(zero.contains("record any drift you observe as a finding"));
2388        assert!(zero.contains("Verify writes **no entity content**"));
2389    }
2390
2391    /// C2 — the sync brief carries BOTH inputs in ONE render: the cursor slice
2392    /// (the changed artifacts) AND the open findings (`current(key)`), plus the
2393    /// commits-nothing posture.
2394    #[test]
2395    fn sync_brief_carries_both_cursor_and_findings() {
2396        let r = resolved("engine", None, vec![]);
2397        let cursor = SourceCursor {
2398            union: slice(&["gone.rs"], &["moved.rs"], &[]),
2399            write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2400            reseed: vec![],
2401            no_signal: vec![],
2402            any_changes: true,
2403            degraded: false,
2404            dead_denies: vec![],
2405            dest_mem: "engine".to_string(),
2406            binding_id: "engine/graph".to_string(),
2407            delivery: vec![],
2408        };
2409        let findings = vec![
2410            finding(
2411                FindingClass::Drifted,
2412                anchor_target("engine--e", "src/moved.rs"),
2413                "prepared-content hash drifted",
2414            ),
2415            finding(
2416                FindingClass::Uncovered,
2417                artifact_target("src/new.rs"),
2418                "in scope, no anchor",
2419            ),
2420        ];
2421        let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2422        // Both inputs present in one brief (C2).
2423        assert!(out.contains("## Source changes since the last sync"));
2424        assert!(out.contains("`moved.rs`"));
2425        assert!(out.contains("## Open findings to repair"));
2426        assert!(out.contains("`engine--e` → `src/moved.rs`"));
2427        assert!(out.contains("`src/new.rs`"));
2428        // Sole-writer + commits-nothing posture (C3).
2429        assert!(out.contains("sole maintenance writer"));
2430        assert!(out.contains("commits each one **per-mutation**"));
2431        assert!(out.contains("Sync commits nothing."));
2432    }
2433
2434    /// C3 — the sync brief carries the whole absorbed reconcile judgment: the
2435    /// five conservatism rules, edge-removal conservatism, and
2436    /// rationale-not-changelog. Each rule is quoted verbatim so absorption is
2437    /// verifiable against the C4 diff artifact.
2438    #[test]
2439    fn sync_brief_absorbs_reconcile_conservatism() {
2440        let r = resolved("engine", None, vec![]);
2441        let findings = vec![finding(
2442            FindingClass::Uncovered,
2443            artifact_target("src/x.rs"),
2444            "d",
2445        )];
2446        let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2447        // Five conservatism rules.
2448        assert!(out.contains("Unsure whether an entity is affected — skip it."));
2449        assert!(out.contains(
2450            "Do not create a new entity unless the change clearly introduces a new concept"
2451        ));
2452        assert!(
2453            out.contains("Do not delete an entity unless the change removes the concept entirely.")
2454        );
2455        assert!(out.contains("Never rewrite a section that has not changed"));
2456        assert!(out.contains(
2457            "No speculative edges — add only relationships the diff literally introduces"
2458        ));
2459        // Edge-removal conservatism — flags, never auto-removes.
2460        assert!(out.contains("A dropped dependency FLAGS, it does not auto-remove."));
2461        assert!(out.contains("Edge removal is out of scope for sync."));
2462        // Rationale-not-changelog.
2463        assert!(out.contains("Rationale is reasoning, not a changelog."));
2464        assert!(out.contains("`[commit <hash>]` log-style entries"));
2465    }
2466
2467    /// C3 — the first-sync/adopt framing (E1's brief half): a mem predating its
2468    /// binding is onboarding, expected-0%, with the backfill path — never a
2469    /// failure. The changed-slice reseed carries the per-facet first-sync note.
2470    #[test]
2471    fn sync_brief_renders_adopt_framing() {
2472        let mut r = resolved("engine", None, vec![]);
2473        // In a real ResolvedIngest, `name` is the canonical binding id
2474        // `<mem>/<stem>` while `destination_mem` is the mem — the header uses the
2475        // mem, the backfill command uses the binding id.
2476        r.name = "engine/graph".to_string();
2477        let out = render_sync_brief(&r, &empty_cursor(), &[], &[], true);
2478        assert!(out.contains("## First sync — adopting `engine`"));
2479        assert!(out.contains("0% anchored is expected — this is onboarding, not a failure."));
2480        assert!(out.contains("do **not** replay the whole history"));
2481        assert!(out.contains("**Backfill path:**"));
2482        assert!(out.contains("memstead projection verify engine/graph"));
2483    }
2484
2485    /// The reseed (first-sync, no cursor) framing lives in the embedded
2486    /// changed-slice preface — the sync brief inherits it for free.
2487    #[test]
2488    fn sync_brief_inherits_first_sync_reseed_framing() {
2489        let r = resolved("engine", None, vec![]);
2490        let mut cursor = empty_cursor();
2491        cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2492        let out = render_sync_brief(&r, &cursor, &[], &[], false);
2493        assert!(out.contains("No usable sync baseline exists for"));
2494        assert!(out.contains("Treating the current source state as the baseline"));
2495    }
2496
2497    /// A no-work sync pass (nothing moved, no findings, not adopt) renders a
2498    /// compact "nothing to sync" note and no repair machinery — a valid outcome.
2499    #[test]
2500    fn sync_brief_nothing_to_sync() {
2501        let r = resolved("engine", None, vec![]);
2502        let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2503        assert!(out.contains("## Nothing to sync"));
2504        assert!(!out.contains("## How to repair"));
2505        assert!(!out.contains("## Open findings"));
2506    }
2507
2508    /// C2 REFUSAL complement — the sync brief is the ONLY render carrying repair
2509    /// instructions; the verify brief carries none. The verify brief has no
2510    /// "## How to repair" / "## Open findings to repair" block; the sync brief
2511    /// has both.
2512    #[test]
2513    fn only_sync_brief_carries_repair_instructions() {
2514        let r = resolved("engine", None, vec![]);
2515        let findings = vec![finding(
2516            FindingClass::Drifted,
2517            anchor_target("engine--e", "src/a.rs"),
2518            "d",
2519        )];
2520        let verify = render_verify_brief(&r, 1);
2521        let sync = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2522        // Verify: no repair section, no repair verbs as instructions.
2523        assert!(!verify.contains("## How to repair"));
2524        assert!(!verify.contains("Update the affected section"));
2525        // Sync: both repair sections present.
2526        assert!(sync.contains("## How to repair — be conservative"));
2527        assert!(sync.contains("## Open findings to repair"));
2528        assert!(sync.contains("Update the affected section to match"));
2529    }
2530
2531    /// Criterion — a changed slice renders the bounded **stale-claim search**
2532    /// step: extract the changed facts, search the destination mem for claims
2533    /// about them, judge only entities whose claims mention a changed fact.
2534    #[test]
2535    fn sync_brief_changed_slice_renders_stale_claim_search() {
2536        let r = resolved("engine", None, vec![]);
2537        let cursor = SourceCursor {
2538            union: slice(&[], &["moved.rs"], &[]),
2539            write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2540            reseed: vec![],
2541            no_signal: vec![],
2542            any_changes: true,
2543            degraded: false,
2544            dead_denies: vec![],
2545            dest_mem: "engine".to_string(),
2546            binding_id: "engine/graph".to_string(),
2547            delivery: vec![],
2548        };
2549        let out = render_sync_brief(&r, &cursor, &[], &[], false);
2550        assert!(out.contains("## Stale claims beyond the slice — search, then judge"));
2551        // The search is bound to the changed facts and the destination mem.
2552        assert!(out.contains("Extract the **changed facts** from the changed artifacts above"));
2553        assert!(out.contains("search the destination mem `engine`"));
2554        assert!(out.contains("`memstead_search`"));
2555        assert!(out.contains("judge **only** the entities whose claims actually mention"));
2556        // Bounded shape, spelled out: not a live-verify, not a rewrite license,
2557        // and an empty fact set (cosmetic change) instructs nothing.
2558        assert!(out.contains("not a live-verify of every entity"));
2559        assert!(out.contains("not a rewrite license"));
2560        assert!(out.contains("the fact set is empty and this step ends with no"));
2561        // REFUSAL complement: the never-rewrite-unchanged-sections rule still
2562        // rides the same brief — idempotence stays protected.
2563        assert!(out.contains("Never rewrite a section that has not changed"));
2564    }
2565
2566    /// REFUSAL — the stale-claim search is absent from every pass whose cursor
2567    /// carries no changed artifacts: findings-only, reseed-only (first sync),
2568    /// and nothing-to-sync briefs instruct no fact search and no mem sweep.
2569    #[test]
2570    fn sync_brief_without_changes_renders_no_stale_claim_search() {
2571        let r = resolved("engine", None, vec![]);
2572        let heading = "## Stale claims beyond the slice";
2573
2574        // Findings-only pass (source unmoved).
2575        let findings = vec![finding(
2576            FindingClass::Uncovered,
2577            artifact_target("src/x.rs"),
2578            "d",
2579        )];
2580        let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2581        assert!(!out.contains(heading), "findings-only pass must not search");
2582
2583        // Reseed-only pass (first sync, no diffable slice).
2584        let mut reseed_cursor = empty_cursor();
2585        reseed_cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2586        let out = render_sync_brief(&r, &reseed_cursor, &[], &[], false);
2587        assert!(!out.contains(heading), "reseed-only pass must not search");
2588
2589        // Nothing-to-sync pass.
2590        let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2591        assert!(!out.contains(heading));
2592    }
2593
2594    /// A large findings group caps at FINDINGS_CAP with an overflow line —
2595    /// mirroring the changed-slice cap, so no facet renders unbounded.
2596    #[test]
2597    fn sync_brief_caps_large_findings_group() {
2598        let r = resolved("engine", None, vec![]);
2599        let findings: Vec<Finding> = (0..FINDINGS_CAP + 4)
2600            .map(|i| {
2601                finding(
2602                    FindingClass::Uncovered,
2603                    artifact_target(&format!("src/f{i}.rs")),
2604                    "d",
2605                )
2606            })
2607            .collect();
2608        let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2609        assert!(out.contains("- …and 4 more"));
2610        // The last few beyond the cap are not rendered inline.
2611        assert!(!out.contains(&format!("src/f{}.rs", FINDINGS_CAP + 3)));
2612    }
2613
2614    /// Criterion 8 (loop economics) — the default loop path's sync brief is
2615    /// **locked block-by-block** for a representative changed-slice pass: the
2616    /// heading sequence below is the whole brief, in this order, and nothing
2617    /// else. The only blocks this plan added to the loop path are the
2618    /// stale-claim search (criterion 1) and the head-durable findings
2619    /// presentation (criterion 2) — both locked here in place. The inventory
2620    /// operation (`projection verify --full` + the `/sync --inventory` repair
2621    /// loop) added NO block and NO line to this render, so a new block
2622    /// appearing (or one moving) fails this test and must be a deliberate
2623    /// loop-economics decision.
2624    #[test]
2625    fn sync_brief_block_sequence_locked_for_changed_slice() {
2626        let r = resolved("engine", None, vec![]);
2627        let cursor = SourceCursor {
2628            union: slice(&["gone.rs"], &["moved.rs"], &["new.rs"]),
2629            write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2630            reseed: vec![],
2631            no_signal: vec![],
2632            any_changes: true,
2633            degraded: false,
2634            dead_denies: vec![],
2635            dest_mem: "engine".to_string(),
2636            binding_id: "engine/graph".to_string(),
2637            delivery: vec![],
2638        };
2639        let findings = vec![
2640            finding(
2641                FindingClass::Drifted,
2642                anchor_target("engine--e", "src/moved.rs"),
2643                "prepared-content hash drifted",
2644            ),
2645            finding(
2646                FindingClass::Uncovered,
2647                artifact_target("src/new.rs"),
2648                "in scope, no anchor",
2649            ),
2650        ];
2651        let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2652        let headings: Vec<&str> = out
2653            .lines()
2654            .filter(|l| l.starts_with("## ") || l.starts_with("### "))
2655            .collect();
2656        assert_eq!(
2657            headings,
2658            vec![
2659                "## Sync — repair the graph to match the source",
2660                "## Source changes since the last sync",
2661                "### Recording your dispositions (do this LAST)",
2662                "## Stale claims beyond the slice — search, then judge",
2663                "## Open findings to repair",
2664                "### Drifted — the anchored content changed",
2665                "### Uncovered — a source artifact with no entity",
2666                // Deliberate addition (anchor-source plan): the sync
2667                // brief now carries the provenance instruction so
2668                // repair writes are anchored — and name their source.
2669                "## Provenance — anchor your writes",
2670                "## How to repair — be conservative",
2671            ],
2672            "the loop-path sync brief carries exactly these blocks, in this order"
2673        );
2674        // The brief closes on the conservatism block's final rule — nothing
2675        // (inventory or otherwise) rides after it.
2676        assert!(out.ends_with("`[commit <hash>]` log-style entries.\n\n"));
2677    }
2678
2679    /// Criterion 8 REFUSAL — no brief on the default (non-inventory) path
2680    /// carries any inventory machinery: not the build briefs (discovery /
2681    /// one-shot), not the verify brief, not the sync brief in any of its
2682    /// shapes (changed slice, findings-only, nothing-to-sync, adopt). The
2683    /// inventory operation lives entirely in `projection verify --full` and
2684    /// the `/sync --inventory` skill routing; the engine-side byte-compat of
2685    /// the no-flag sampled verify is asserted in
2686    /// `findings::tests::full_verify_uncaps_adjudication_and_walks_whole_source`
2687    /// (extended there, not duplicated here). The minute-loop pays nothing
2688    /// for inventory.
2689    #[test]
2690    fn no_default_path_brief_carries_inventory_machinery() {
2691        // Terms that exist only on the inventory surface (flag, skill mode,
2692        // report framing, termination rule). Matched case-insensitively.
2693        let inventory_terms = [
2694            "--full",
2695            "inventory",
2696            "full measurement",
2697            "did not converge",
2698            "quiescence",
2699        ];
2700        let assert_clean = |label: &str, text: &str| {
2701            let lower = text.to_lowercase();
2702            for term in inventory_terms {
2703                assert!(
2704                    !lower.contains(term),
2705                    "{label} must carry no inventory machinery (found {term:?})"
2706                );
2707            }
2708        };
2709
2710        let r = resolved("engine", None, vec![]);
2711        let g = guidance(Some("build coverage"), None);
2712        let pm = process_present("engine");
2713
2714        // Build briefs — with and without a changed-slice preface.
2715        let changed_cursor = SourceCursor {
2716            union: slice(&[], &["moved.rs"], &[]),
2717            write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2718            reseed: vec![],
2719            no_signal: vec![],
2720            any_changes: true,
2721            degraded: false,
2722            dead_denies: vec![],
2723            dest_mem: "engine".to_string(),
2724            binding_id: "engine/graph".to_string(),
2725            delivery: vec![],
2726        };
2727        let preface = render_changed_slice(&changed_cursor);
2728        assert_clean(
2729            "discovery build brief (plain roam)",
2730            &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], ""),
2731        );
2732        assert_clean(
2733            "discovery build brief (changed slice)",
2734            &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], &preface),
2735        );
2736        assert_clean(
2737            "one-shot build brief",
2738            &assemble_one_shot_brief(&r, &g, &pm, Some("s@1"), None, &[], Some("purpose")),
2739        );
2740
2741        // Verify brief — with and without an adjudication backlog.
2742        assert_clean("verify brief (backlog)", &render_verify_brief(&r, 3));
2743        assert_clean("verify brief (no backlog)", &render_verify_brief(&r, 0));
2744
2745        // Sync brief — every shape the loop renders.
2746        let findings = vec![finding(
2747            FindingClass::Drifted,
2748            anchor_target("engine--e", "src/moved.rs"),
2749            "d",
2750        )];
2751        assert_clean(
2752            "sync brief (changed slice + findings)",
2753            &render_sync_brief(&r, &changed_cursor, &findings, &[], false),
2754        );
2755        assert_clean(
2756            "sync brief (findings-only)",
2757            &render_sync_brief(&r, &empty_cursor(), &findings, &[], false),
2758        );
2759        assert_clean(
2760            "sync brief (nothing to sync)",
2761            &render_sync_brief(&r, &empty_cursor(), &[], &[], false),
2762        );
2763        assert_clean(
2764            "sync brief (adopt)",
2765            &render_sync_brief(&r, &empty_cursor(), &[], &[], true),
2766        );
2767    }
2768}