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