1use super::guidance::ResolvedGuidance;
19use super::resolve::{ResolvedIngest, ResolvedSource};
20use super::slice::{NoSignalReason, Slice};
21use crate::binding::BuildMode;
22use crate::pipeline::{MediumType, PatternMode};
23
24const SLICE_CAP: usize = 25;
27
28pub const PROCESS_MEM_SCHEMA: &str = "ingest@0.5.0";
32
33#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ProcessMemInfo {
39 pub present: bool,
41 pub skipped: bool,
43 pub notice: Option<String>,
45 pub leaf_name: String,
47 pub mem_label: String,
49}
50
51fn mode_label(mode: BuildMode) -> &'static str {
54 match mode {
55 BuildMode::Discovery => "discovery",
56 BuildMode::OneShot => "one-shot",
57 }
58}
59
60fn 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
71pub 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
110pub 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
170pub 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
185pub 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 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 lines.push(format!(
218 "- **{}** ({}, primary) — `{}`",
219 p.name,
220 medium_type_label(p.medium_type),
221 p.pointer
222 ));
223 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 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 for note in super::cursor::scope_migration_notes(p) {
274 let rewrite = match ¬e.suggested {
275 Some(s) => format!(" — rewrite it as `{s}`"),
276 None => String::new(),
277 };
278 lines.push(format!(
279 " - **Scope pattern `{}` is written against the workspace root \
280 rather than the source pointer, so it selects nothing**{rewrite}.",
281 note.pattern
282 ));
283 }
284 if is_graph {
285 lines.push(format!(
286 " - Read the source baseline with `memstead_search mem={}` \
287 (add `entity_type=` to match a `type:` selector). The changed \
288 slice below is a delta against the last pass — it is not the \
289 whole source, and an entity absent from it may still be \
290 unprojected.",
291 p.pointer
292 ));
293 }
294 }
295 ResolvedSource::Reference { mem } => {
296 lines.push(format!("- **graph** (reference) — mem: {mem}"));
297 reference_mems.push(mem.clone());
298 }
299 }
300 }
301 lines.push(String::new());
302 if !reference_mems.is_empty() {
303 lines.push(
304 "Sources tagged `(reference)` are read-only context for cross-mem edges — search \
305 them, never write into them. Only `(primary)` sources are ingested into the \
306 destination."
307 .to_string(),
308 );
309 lines.push(String::new());
310 let mem_list = reference_mems
311 .iter()
312 .map(|v| format!("`memstead_search mem={v}`"))
313 .collect::<Vec<_>>()
314 .join(", ");
315 lines.push(format!(
316 "**Cross-mem references:** consult {mem_list} before authoring cross-mem edges. \
317 The target entity must exist — a wiki-link or relationship to a missing target \
318 either auto-stubs (silent) or fails authorization (`CROSS_MEM_RELATION`)."
319 ));
320 lines.push(String::new());
321 }
322 }
323
324 lines.push("### Destination".to_string());
326 lines.push(String::new());
327 let schema_bit = destination_schema
328 .map(|s| format!(" — schema: `{s}`"))
329 .unwrap_or_default();
330 lines.push(format!("- **{}**{schema_bit}", resolved.destination_mem));
331 if let Some(note) = destination_note {
342 lines.push(format!(" - {note}"));
343 }
344 lines.push(String::new());
345
346 if process_mem.present {
348 lines.push("### Paired process mem".to_string());
349 lines.push(String::new());
350 lines.push(format!(
351 "- **{}** — schema: `{PROCESS_MEM_SCHEMA}`. Inspect via `memstead_overview` / \
352 `memstead_search mem={}`.",
353 process_mem.mem_label, process_mem.leaf_name
354 ));
355 lines.push(String::new());
356 }
357
358 format!("{}\n", lines.join("\n"))
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct SyncCommand {
368 pub key: String,
370 pub token: String,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct NoSignalNote {
381 pub source: String,
384 pub reason: NoSignalReason,
386 pub medium_type: Option<MediumType>,
392}
393
394#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct SourceCursor {
400 pub union: Slice,
402 pub write_commands: Vec<SyncCommand>,
404 pub reseed: Vec<SyncCommand>,
406 pub no_signal: Vec<NoSignalNote>,
412 pub any_changes: bool,
414 pub degraded: bool,
416 pub dead_denies: Vec<String>,
425 pub dest_mem: String,
427 pub binding_id: String,
431 pub delivery: Vec<DeliverySequence>,
436}
437
438#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct DeliveredUnit {
441 pub id: String,
443 pub order_key: String,
445 pub change: crate::preparation::UnitChange,
447 pub disposed: bool,
450}
451
452#[derive(Debug, Clone, PartialEq, Eq)]
456pub struct DeliverySequence {
457 pub source: String,
459 pub preparation: String,
461 pub first_run: bool,
463 pub degraded: bool,
466 pub batch: usize,
469 pub units: Vec<DeliveredUnit>,
471}
472
473fn shell_quote(s: &str) -> String {
477 format!("'{}'", s.replace('\'', "'\\''"))
478}
479
480fn render_delivery_sequence(lines: &mut Vec<String>, seq: &DeliverySequence) {
488 use crate::preparation::UnitChange;
489 lines.push(format!(
490 "### Delivery sequence: `{}` (`{}`)\n",
491 seq.source, seq.preparation
492 ));
493 let opening = if seq.first_run {
494 "First delivery of this source: every unit, in the source's own order."
495 } else {
496 "The units that changed since the last pass, at their positions in the source's own \
497 order."
498 };
499 lines.push(format!(
500 "{opening} Work them top to bottom: the order derives from the units' own keys, never \
501 from discovery or directory order, it is identical on every pass, and a unit assumes \
502 only the units numbered before it. Address a unit as `<path>#<key>` in anchors and \
503 dispositions.\n"
504 ));
505 if seq.degraded {
506 lines.push(
507 "_(No baseline content was retrievable for one or more changed files, so every unit \
508 of those files is listed; precision is coarser this pass only.)_\n"
509 .to_string(),
510 );
511 }
512 let pending: Vec<(usize, &DeliveredUnit)> = seq
513 .units
514 .iter()
515 .enumerate()
516 .filter(|(_, u)| !u.disposed)
517 .collect();
518 let disposed = seq.units.len() - pending.len();
519 let shown = if seq.batch == 0 {
520 pending.len()
521 } else {
522 pending.len().min(seq.batch)
523 };
524 for (position, unit) in &pending[..shown] {
525 let label = match unit.change {
526 UnitChange::Added => "new",
527 UnitChange::Modified => "changed",
528 UnitChange::Deleted => "deleted",
529 };
530 lines.push(format!("{}. `{}` ({label})", position + 1, unit.id));
531 }
532 if pending.len() > shown {
533 lines.push(format!(
534 "- …and {} more, presented in order once these are disposed",
535 pending.len() - shown
536 ));
537 }
538 if disposed > 0 {
539 lines.push(format!(
540 "_({disposed} unit{} of this sequence already disposed this pass.)_",
541 if disposed == 1 { "" } else { "s" }
542 ));
543 }
544 if pending.is_empty() {
545 lines.push(
546 "_(Every unit of this sequence is disposed; the baseline advances when the pass \
547 completes.)_"
548 .to_string(),
549 );
550 }
551 lines.push(String::new());
552}
553
554fn render_slice_class(lines: &mut Vec<String>, label: &str, paths: &[String]) {
555 if paths.is_empty() {
556 return;
557 }
558 let shown = paths.len().min(SLICE_CAP);
559 lines.push(format!("**{label}:**"));
560 for path in &paths[..shown] {
561 lines.push(format!("- `{path}`"));
562 }
563 if paths.len() > shown {
564 lines.push(format!(
565 "- …and {} more {}",
566 paths.len() - shown,
567 label.to_lowercase()
568 ));
569 }
570 lines.push(String::new());
571}
572
573fn no_signal_reason_text(reason: NoSignalReason, medium: Option<MediumType>) -> &'static str {
578 match reason {
579 NoSignalReason::Unscoped => match medium {
583 Some(MediumType::Graph) => {
584 "unscoped facet (no allow patterns) — nothing is monitored; write `*` in the \
585 facet scope to watch the whole mem, or `type:<entity_type>` / `id:<glob>` \
586 to narrow it (a graph source selects entities, not paths)"
587 }
588 _ => {
589 "unscoped facet (no allow patterns) — nothing is monitored; write `**/*` in the \
590 facet scope to watch the whole medium"
591 }
592 },
593 NoSignalReason::DetectionNone => {
594 "`signal:none` — change detection is disabled for this source (declared `none`)"
595 }
596 NoSignalReason::GitUnavailable => {
597 "git signal unavailable — no work tree, an unreadable `HEAD`, or an unknown baseline; \
598 a full re-roam is warranted this pass"
599 }
600 NoSignalReason::GraphSnapshotMissing => {
601 "graph snapshot missing — the source mem has no comparable baseline this pass"
602 }
603 }
604}
605
606pub fn render_changed_slice(cursor: &SourceCursor) -> String {
613 if !cursor.any_changes
614 && cursor.reseed.is_empty()
615 && cursor.no_signal.is_empty()
616 && cursor.dead_denies.is_empty()
617 {
618 return String::new();
619 }
620 let mut lines: Vec<String> = Vec::new();
621 lines.push("## Source changes since the last sync\n".to_string());
622
623 if cursor.any_changes {
624 lines.push(
625 "The source moved since this graph was last synced. Steer this pass at these changed \
626 artifacts **first** — they are where the graph is most likely now wrong.\n"
627 .to_string(),
628 );
629 for seq in &cursor.delivery {
633 render_delivery_sequence(&mut lines, seq);
634 }
635 let unit_ids: std::collections::BTreeSet<&str> = cursor
636 .delivery
637 .iter()
638 .flat_map(|s| s.units.iter().map(|u| u.id.as_str()))
639 .collect();
640 let without_units = |v: &[String]| -> Vec<String> {
641 v.iter()
642 .filter(|p| !unit_ids.contains(p.as_str()))
643 .cloned()
644 .collect()
645 };
646 render_slice_class(&mut lines, "Deleted", &without_units(&cursor.union.deleted));
648 render_slice_class(
649 &mut lines,
650 "Modified",
651 &without_units(&cursor.union.modified),
652 );
653 render_slice_class(&mut lines, "Added", &without_units(&cursor.union.added));
654 if cursor.degraded {
655 lines.push(
656 "_(Precise change history for one or more facets was unavailable, so its full \
657 current file set is listed above. Detection still fired from the durable baseline; \
658 targeting is coarser this pass only.)_\n"
659 .to_string(),
660 );
661 }
662 }
663
664 if !cursor.reseed.is_empty() {
665 let keys = cursor
666 .reseed
667 .iter()
668 .map(|r| format!("`{}`", r.key))
669 .collect::<Vec<_>>()
670 .join(", ");
671 let it = if cursor.reseed.len() == 1 {
672 "it"
673 } else {
674 "them"
675 };
676 lines.push(format!(
677 "No usable sync baseline exists for {keys} — none was recorded, or the recorded one \
678 is not a commit of the source's repo (foreign or garbage-collected). Treating the \
679 current source state as the baseline. No priority slice from {it} this pass; \
680 proceed as usual.\n"
681 ));
682 }
683
684 if !cursor.no_signal.is_empty() {
685 lines.push(
686 "Some sources produced **no change signal** this pass — detection could not compare \
687 them against a baseline, so they were not steered (roam them as usual). This is \
688 distinct from a source that was checked and had not moved:\n"
689 .to_string(),
690 );
691 for note in &cursor.no_signal {
692 lines.push(format!(
693 "- `{}`: {}",
694 note.source,
695 no_signal_reason_text(note.reason, note.medium_type)
696 ));
697 }
698 lines.push(String::new());
699 }
700
701 if !cursor.dead_denies.is_empty() {
702 lines.push(
703 "**Warning — some `deny_paths` entries match nothing.** The following ingest \
704 `deny_paths` selected **no file** in the project tree, so they exclude nothing from \
705 the slice and hide nothing from the ingest agent. This is usually a typo or a legacy \
706 bare name that never migrated to the workspace-relative glob dialect (e.g. `dev` → \
707 `dev/**`, `VISION.md` → `**/VISION.md`). Fix or remove them:\n"
708 .to_string(),
709 );
710 for entry in &cursor.dead_denies {
711 lines.push(format!("- `{entry}`"));
712 }
713 lines.push(String::new());
714 }
715
716 let has_baseline_to_advance = !cursor.write_commands.is_empty() || !cursor.reseed.is_empty();
724 if has_baseline_to_advance {
725 lines.push("### Recording your dispositions (do this LAST)\n".to_string());
726 lines.push(
727 "Only after you have worked the changed artifacts above — and only for the artifacts \
728 you actually judged — record a disposition for each, so the next pass targets just \
729 what changes next. This advance is resumable and non-stalling: a partial pass is \
730 honored, and if the source moves mid-pass the remaining slice re-presents \
731 (remaining + new) without losing your recorded work.\n"
732 .to_string(),
733 );
734 lines.push(
735 "Anchored work disposes itself: at advance time, every listed artifact that an \
736 anchor in the destination mem references is marked `worked` automatically (an \
737 explicit disposition you pass wins over the auto-mark). Supply dispositions only \
738 for the residue — artifacts you skipped, judged out of intent, or worked without \
739 anchors. The gate accepts only artifact ids listed above — an unknown id refuses \
740 the whole call. When every artifact is disposed, the sync baseline advances \
741 automatically. Run:\n"
742 .to_string(),
743 );
744 lines.push("```sh".to_string());
745 lines.push(format!(
746 "memstead projection advance {} --dispositions {}",
747 cursor.binding_id,
748 shell_quote(r#"{"<artifact>": "<disposition>", ...}"#)
749 ));
750 lines.push("```".to_string());
751 lines.push(
752 "If you were interrupted before finishing, that is fine — your recorded dispositions \
753 persist, and the next run re-presents only what is left.\n"
754 .to_string(),
755 );
756 }
757
758 format!("{}\n", lines.join("\n"))
759}
760
761pub fn render_anchor_instruction(resolved: &ResolvedIngest) -> String {
774 let mut block = "## Provenance — anchor your writes\n\n\
775 Attach an `anchors` list to every `memstead_create` / `memstead_update`, naming the \
776 source artifact(s) the entity is drawn from (the mutation tools document the element \
777 shape). Anchored writes are what verify measures coverage and drift against, and — on \
778 cursor-driven passes — what the advance gate auto-marks `worked`; an unanchored write \
779 leaves the fidelity report and the disposition window blind to your work.\n\n"
780 .to_string();
781 let primary_names: Vec<&str> = resolved
785 .sources
786 .iter()
787 .filter_map(|s| match s {
788 crate::ingest::resolve::ResolvedSource::Primary(src) => Some(src.name.as_str()),
789 crate::ingest::resolve::ResolvedSource::Reference { .. } => None,
790 })
791 .collect();
792 if !primary_names.is_empty() {
793 block.push_str(&format!(
794 "Set each anchor's `source` to the binding source name you drew the artifact \
795 from — this binding declares: {}. The name selects the pointer the \
796 artifact path is joined onto, so the wrong one usually refuses \
797 `INVALID_ANCHOR` (the path resolves under no candidate join). A name \
798 outside the list is NOT itself refused when the path happens to \
799 resolve workspace-relative — that tolerance exists for anchors whose \
800 binding was later renamed — so getting it right is on you, not on a \
801 gate.\n\n",
802 primary_names
803 .iter()
804 .map(|n| format!("`{n}`"))
805 .collect::<Vec<_>>()
806 .join(", ")
807 ));
808 }
809 block.push_str(
814 "For a web document use `grain: url` with the URL as `artifact` and pass the retrieved \
815 text as `content` so the engine records its hash (the engine never fetches). Set \
816 `hash_stability: stable` on an IMMUTABLE document — a dated PDF, an archived page, a \
817 versioned standard — so a later changed hash reads as `drifted`; leave the default \
818 `unstable` for a living page, where a change is only a `recheck`. Url rows are \
819 re-adjudicated when someone supplies a fresh observation (`memstead verify-anchors \
820 --observations`), and every surface shows how long each has gone unobserved.\n\n",
821 );
822 for source in &resolved.sources {
825 let crate::ingest::resolve::ResolvedSource::Primary(src) = source else {
826 continue;
827 };
828 let Some(prep) = src
829 .preparation
830 .as_deref()
831 .and_then(crate::preparation::lookup)
832 else {
833 continue;
834 };
835 let what = match prep.id {
836 crate::preparation::CODE_MAP => {
837 "the file's interface digest (imports, exports, signatures; comments, \
838 formatting and bodies invisible), and a `tree` anchor the code map of every \
839 scoped file under it"
840 }
841 crate::preparation::DATED_ENTRIES => {
842 "the unit's own text for a `<path>#<key>` span, the file's bytes otherwise"
843 }
844 crate::preparation::ENTITY_LOAD_BEARING => "the entity's load-bearing sections",
845 _ => prep.description,
846 };
847 block.push_str(&format!(
848 "Anchors on `{}` hash a prepared form (`{}`): {what}. Never compute `hash` \
849 yourself for this source — leave it empty (verify records it on first \
850 observation), or for a `file` or `span` anchor pass the artifact's `content` \
851 and the engine hashes the prepared form (a `tree` anchor takes no content).\n\n",
852 src.name, prep.id
853 ));
854 }
855 block
856}
857
858#[allow(clippy::too_many_arguments)]
859pub fn assemble_discovery_brief(
860 resolved: &ResolvedIngest,
861 guidance: &ResolvedGuidance,
862 process_mem: &ProcessMemInfo,
863 destination_schema: Option<&str>,
864 destination_note: Option<&str>,
865 absent_sources: &[String],
866 changed_slice_preface: &str,
867) -> String {
868 let parts = [
869 render_situation(resolved, process_mem),
870 render_intent(resolved),
871 render_goal_and_avoid(guidance),
872 render_operative_data(
873 resolved,
874 process_mem,
875 destination_schema,
876 destination_note,
877 absent_sources,
878 ),
879 render_anchor_instruction(resolved),
880 changed_slice_preface.to_string(),
881 ];
882 parts
883 .into_iter()
884 .filter(|p| !p.is_empty())
885 .collect::<Vec<_>>()
886 .join("")
887}
888
889pub fn render_one_shot_lens(
895 resolved: &ResolvedIngest,
896 destination_schema: Option<&str>,
897 destination_purpose: Option<&str>,
898) -> String {
899 let cell = |s: &str| s.replace('|', "\\|").replace('\n', " ");
900 let mut lines: Vec<String> = vec![
901 "## Mode: one-shot — lens routing".to_string(),
902 String::new(),
903 "A lens iterates entities once and writes per-destination, then exits. The agent decides \
904 per-entity which destinations to target (Routing rule). Re-runs use `memstead_update`; \
905 never duplicate."
906 .to_string(),
907 String::new(),
908 ];
909
910 lines.push("### Destination set".to_string());
911 lines.push(String::new());
912 lines.push("| Mem | Schema | Purpose |".to_string());
913 lines.push("|-------|--------|---------|".to_string());
914 let schema = destination_schema.unwrap_or("(none)");
915 let purpose = destination_purpose
916 .filter(|s| !s.is_empty())
917 .unwrap_or("(no purpose declared)");
918 lines.push(format!(
919 "| {} | {} | {} |",
920 cell(&resolved.destination_mem),
921 cell(schema),
922 cell(purpose)
923 ));
924 lines.push(String::new());
925
926 if let Some(routing) = resolved
927 .rules
928 .as_ref()
929 .and_then(|r| r.get("routing"))
930 .and_then(|v| v.as_str())
931 .map(str::trim)
932 .filter(|s| !s.is_empty())
933 {
934 lines.push("### Routing rule".to_string());
935 lines.push(String::new());
936 lines.push("```".to_string());
937 lines.push(routing.to_string());
938 lines.push("```".to_string());
939 lines.push(String::new());
940 }
941
942 lines.push("### Idempotency".to_string());
943 lines.push(String::new());
944 lines.push("- Search the destination before writing; route changes through `memstead_update` against the existing entity if present.".to_string());
945 lines.push("- Skip writes when the lifted content matches what is already there (record as `skipped: already-up-to-date`).".to_string());
946 lines.push(
947 "- Use `memstead_create` only when no entity for that concept exists yet.".to_string(),
948 );
949 lines.push(String::new());
950
951 lines.push("### End-of-run report".to_string());
952 lines.push(String::new());
953 lines.push("After every destination is processed, emit one block per destination on stdout, in Destination-set order:".to_string());
954 lines.push(String::new());
955 lines.push("```".to_string());
956 lines.push(format!("### Report: {}", resolved.name));
957 lines.push(String::new());
958 lines.push("Destination: <mem>".to_string());
959 lines.push(" created: <count>".to_string());
960 lines.push(" updated: <count>".to_string());
961 lines.push(" skipped: <count>".to_string());
962 lines.push(" failed: <count>".to_string());
963 lines.push(" failures:".to_string());
964 lines.push(" - <entity-key>: <error verbatim>".to_string());
965 lines.push(" skipped-detail:".to_string());
966 lines.push(" - <entity-key>: <one-line reason>".to_string());
967 lines.push("```".to_string());
968 lines.push(String::new());
969 lines.push("Per-destination commits are independent — partial success is the accepted failure mode. No rollback.".to_string());
970 lines.push(String::new());
971
972 let archive = resolved
973 .post_actions
974 .as_ref()
975 .and_then(|p| p.get("archive_source"))
976 .and_then(serde_json::Value::as_bool)
977 .unwrap_or(false);
978 if archive {
979 lines.push("### Archive after run".to_string());
980 lines.push(String::new());
981 lines.push("After the report has been emitted, archive the source planning mem — `post_actions.archive_source` is set on this ingest.".to_string());
982 lines.push(String::new());
983 }
984
985 format!("{}\n", lines.join("\n"))
986}
987
988#[allow(clippy::too_many_arguments)]
993pub fn assemble_one_shot_brief(
994 resolved: &ResolvedIngest,
995 guidance: &ResolvedGuidance,
996 process_mem: &ProcessMemInfo,
997 destination_schema: Option<&str>,
998 destination_note: Option<&str>,
999 absent_sources: &[String],
1000 destination_purpose: Option<&str>,
1001) -> String {
1002 let parts = [
1003 render_situation(resolved, process_mem),
1004 render_intent(resolved),
1005 render_goal_and_avoid(guidance),
1006 render_operative_data(
1007 resolved,
1008 process_mem,
1009 destination_schema,
1010 destination_note,
1011 absent_sources,
1012 ),
1013 render_anchor_instruction(resolved),
1014 render_one_shot_lens(resolved, destination_schema, destination_purpose),
1015 ];
1016 parts
1017 .into_iter()
1018 .filter(|p| !p.is_empty())
1019 .collect::<Vec<_>>()
1020 .join("")
1021}
1022
1023use super::findings::{Finding, FindingClass, FindingTarget};
1033use super::prune::{PruneDisposition, PruneProposal};
1034
1035const FINDINGS_CAP: usize = SLICE_CAP;
1037
1038pub fn render_verify_brief(resolved: &ResolvedIngest, backlog: usize) -> String {
1047 let mut lines: Vec<String> = vec![
1048 "## Verify — measure fidelity, do not mutate".to_string(),
1049 String::new(),
1050 ];
1051 lines.push(format!(
1052 "You are measuring the fidelity of `{}` — how faithfully the destination mem \
1053 `{}` still matches its source. This pass **only measures**: read the source \
1054 and the mem's anchors, judge whether the graph still holds, and record what \
1055 you find. **You** write nothing into the destination mem — the run itself \
1056 records its findings store, backfills observed anchor hashes, and writes a \
1057 `#verified` baseline, which is engine bookkeeping, not your edits.",
1058 resolved.name, resolved.destination_mem
1059 ));
1060 lines.push(String::new());
1061
1062 lines.push(
1063 "Anchors may carry a `source` naming the binding entry point that produced them — \
1064 note it when recording findings, so fidelity stays measurable per source."
1065 .to_string(),
1066 );
1067 lines.push(String::new());
1068
1069 lines.push("### Adjudicate the queued findings (capped)".to_string());
1070 lines.push(String::new());
1071 if backlog == 0 {
1072 lines.push(
1073 "No findings are queued for adjudication this pass. Spot-check the resolving \
1074 anchors and the uncovered-artifact sample the fidelity report lists, and \
1075 record any drift you observe as a finding."
1076 .to_string(),
1077 );
1078 } else {
1079 lines.push(format!(
1080 "{backlog} finding(s) are queued for adjudication. Working up to the per-run \
1081 adjudication cap (an operations knob — the remainder stays queued and \
1082 re-presents on a later pass), take each queued finding and compare the \
1083 anchored source content against what the entity records. Classify it: still \
1084 accurate, or drifted. **Record the verdict — this is a measurement, not a \
1085 repair.** A drift you record becomes a finding the sync pass repairs; you do \
1086 not fix it here."
1087 ));
1088 }
1089 lines.push(String::new());
1090
1091 lines.push("### Out of scope for verify — no mutation".to_string());
1092 lines.push(String::new());
1093 lines.push(
1094 "Verify writes **no entity content**. Do not update a \
1095 `specifies` / `constraints` section, do not create or delete an entity, do not \
1096 add or remove a relationship. When measurement shows the graph is wrong, that \
1097 is a **finding** — the sync brief (`memstead projection brief --sync`) is the \
1098 one place those repairs are made. Leave every fix to it. (The run itself does \
1099 record its findings store, backfill observed anchor hashes, and write a \
1100 `#verified` baseline — engine bookkeeping, not your edits.)"
1101 .to_string(),
1102 );
1103 lines.push(String::new());
1104
1105 format!("{}\n", lines.join("\n"))
1106}
1107
1108fn finding_target_label(target: &FindingTarget) -> String {
1110 match target {
1111 FindingTarget::Anchor { entity, artifact } => format!("`{entity}` → `{artifact}`"),
1112 FindingTarget::Artifact { artifact } => format!("`{artifact}`"),
1113 }
1114}
1115
1116fn render_findings_group(
1119 lines: &mut Vec<String>,
1120 heading: &str,
1121 guidance: &str,
1122 items: &[&Finding],
1123) {
1124 if items.is_empty() {
1125 return;
1126 }
1127 lines.push(format!("### {heading}"));
1128 lines.push(String::new());
1129 lines.push(guidance.to_string());
1130 lines.push(String::new());
1131 let shown = items.len().min(FINDINGS_CAP);
1132 for f in &items[..shown] {
1133 lines.push(format!(
1134 "- {} — {}",
1135 finding_target_label(&f.target),
1136 f.detail
1137 ));
1138 }
1139 if items.len() > shown {
1140 lines.push(format!("- …and {} more", items.len() - shown));
1141 }
1142 lines.push(String::new());
1143}
1144
1145fn render_open_findings(findings: &[Finding], binding_id: &str) -> String {
1151 if findings.is_empty() {
1152 return String::new();
1153 }
1154 let mut lines: Vec<String> = vec![
1155 "## Open findings to repair".to_string(),
1156 String::new(),
1157 "The verify pass recorded these against the current source state. Repair them \
1158 conservatively (see the rules below); a finding you judge already correct needs \
1159 no write."
1160 .to_string(),
1161 String::new(),
1162 ];
1163
1164 let group = |class: FindingClass| -> Vec<&Finding> {
1165 findings.iter().filter(|f| f.class == class).collect()
1166 };
1167
1168 render_findings_group(
1171 &mut lines,
1172 "Drifted — the anchored content changed",
1173 "The source the entity describes moved. Update the affected section to match — \
1174 only the part that changed. If the entity is still accurate, leave it. Either \
1175 way, reset the anchor on the entity in ONE update call: `anchors_unset` the \
1176 row, then write it fresh in the same call's `anchors` (same artifact, grain, \
1177 class and source, no hash) — the next verify backfills the freshly observed \
1178 hash and the drift clears. A hashless re-declare WITHOUT the unset keeps the \
1179 stored baseline by design and clears nothing, and updating the entity alone, \
1180 or advancing the baseline, leaves the anchor drifted just the same.",
1181 &group(FindingClass::Drifted),
1182 );
1183 render_findings_group(
1184 &mut lines,
1185 "Wrong — an adjudicated content mismatch",
1186 "Adjudication found the entity no longer matches its source. Correct the \
1187 mismatched section; do not rewrite what still holds.",
1188 &group(FindingClass::Wrong),
1189 );
1190 render_findings_group(
1193 &mut lines,
1194 "Unresolvable anchor — the artifact is gone",
1195 "The source artifact an anchor references is no longer present. Delete the entity \
1196 **only** if the concept is removed entirely; otherwise leave it. Concept-level \
1197 removals are a prune concern with its own never-clobber / conflict-flag rules — \
1198 do not delete on a hunch here.",
1199 &group(FindingClass::UnresolvableAnchor),
1200 );
1201 let uncovered_guidance = format!(
1208 "An in-scope source artifact has no anchor in the mem. Create an entity for it \
1209 **only** if it is a clearly-new concept with no existing entity; otherwise \
1210 extend the entity that already owns the concept, or leave it for a discovery \
1211 build. A third answer is legitimate: the artifact is mined and deliberately \
1212 warrants no entity. Record that with a rationale — it stops presenting here \
1213 from the next brief on:\n\n```bash\nmemstead projection exclude {binding_id} \
1214 --exclusions '{{\"<artifact>\": \"<rationale>\"}}'\n```"
1215 );
1216 render_findings_group(
1217 &mut lines,
1218 "Uncovered — a source artifact with no entity",
1219 &uncovered_guidance,
1220 &group(FindingClass::Uncovered),
1221 );
1222 render_findings_group(
1224 &mut lines,
1225 "Queued for adjudication — not yet judged",
1226 "These are not adjudicated yet — that is the verify pass's job, not sync's. \
1227 **Skip them here**; they become repairable only after verify classifies them as \
1228 drifted.",
1229 &group(FindingClass::QueuedForAdjudication),
1230 );
1231
1232 format!("{}\n", lines.join("\n"))
1233}
1234
1235fn render_exclusions(ledger: &crate::ingest::advance::ExclusionLedger) -> String {
1239 if ledger.active.is_empty() && ledger.dropped.is_empty() {
1240 return String::new();
1241 }
1242 let mut lines: Vec<String> = Vec::new();
1243 if !ledger.active.is_empty() {
1244 lines.push("## Excluded artifacts (authored)".to_string());
1245 lines.push(String::new());
1246 lines.push(
1247 "These in-scope artifacts are deliberately excluded with a recorded rationale; \
1248 they never present as uncovered and need no entity. An exclusion keys on the \
1249 artifact and its source, so it survives edits to the rest of the binding."
1250 .to_string(),
1251 );
1252 lines.push(String::new());
1253 for e in &ledger.active {
1254 lines.push(format!(
1255 "- `{}` (source `{}`): {}",
1256 e.artifact, e.source, e.rationale
1257 ));
1258 }
1259 lines.push(String::new());
1260 }
1261 if !ledger.dropped.is_empty() {
1262 lines.push("## Exclusions dropped — their source is no longer declared".to_string());
1263 lines.push(String::new());
1264 lines.push(
1265 "The source these exclusions were recorded under left the binding's declaration, \
1266 so they no longer apply; re-declare the source and record them again if they \
1267 still hold."
1268 .to_string(),
1269 );
1270 lines.push(String::new());
1271 for d in &ledger.dropped {
1272 lines.push(format!(
1273 "- `{}` (source `{}`, dropped {}): {}",
1274 d.artifact, d.source, d.dropped_at, d.rationale
1275 ));
1276 }
1277 lines.push(String::new());
1278 }
1279 format!("{}\n", lines.join("\n"))
1280}
1281
1282fn render_prune_proposals(proposals: &[PruneProposal]) -> String {
1293 if proposals.is_empty() {
1294 return String::new();
1295 }
1296 let mut lines: Vec<String> = vec![
1297 "## Prune — proposed removals (you decide; nothing is auto-deleted)".to_string(),
1298 String::new(),
1299 "The source removed the artifacts these entities describe. Each item below is a \
1300 **proposal**: prune writes nothing — you enact (or reject) the removal through the \
1301 normal MCP mutation surface. An `authored` entity is never proposed here; a `derived` \
1302 entity is flagged, never proposed for deletion."
1303 .to_string(),
1304 String::new(),
1305 ];
1306
1307 let group = |d: PruneDisposition| -> Vec<&PruneProposal> {
1308 proposals.iter().filter(|p| p.disposition == d).collect()
1309 };
1310
1311 let clean = group(PruneDisposition::CleanDelete);
1314 if !clean.is_empty() {
1315 lines.push("### Clean delete — never-clobber three-way merge is clean".to_string());
1316 lines.push(String::new());
1317 lines.push(
1318 "The source base leg was retrievable and the three-way merge found no model-side \
1319 divergence, so removal is safe. **Confirm, then delete via the mutation surface** — \
1320 this is still your call, not an auto-delete."
1321 .to_string(),
1322 );
1323 lines.push(String::new());
1324 let shown = clean.len().min(FINDINGS_CAP);
1325 for p in &clean[..shown] {
1326 lines.push(format!(
1327 "- `{}` — source artifact(s) gone: {}",
1328 p.entity,
1329 artifact_list(&p.artifacts)
1330 ));
1331 }
1332 if clean.len() > shown {
1333 lines.push(format!("- …and {} more", clean.len() - shown));
1334 }
1335 lines.push(String::new());
1336 }
1337
1338 let conflict = group(PruneDisposition::ConflictFlag);
1340 if !conflict.is_empty() {
1341 lines.push("### Conflict-flag — decide, never overwrite a model-side edit".to_string());
1342 lines.push(String::new());
1343 lines.push(
1344 "No retrievable base leg to merge against (a non-git source, or an anchor with no \
1345 pinned version). **Both sides are shown — decide deliberately.** If the concept is \
1346 truly gone, delete via the mutation surface; if the model side was edited on \
1347 purpose, keep it. Prune never overwrites a model-side edit for you."
1348 .to_string(),
1349 );
1350 lines.push(String::new());
1351 let shown = conflict.len().min(FINDINGS_CAP);
1352 for p in &conflict[..shown] {
1353 lines.push(format!(
1354 "- `{}` — **source side:** artifact(s) gone: {}; **model side:** the entity is \
1355 still present (may carry edits) — you decide.",
1356 p.entity,
1357 artifact_list(&p.artifacts)
1358 ));
1359 }
1360 if conflict.len() > shown {
1361 lines.push(format!("- …and {} more", conflict.len() - shown));
1362 }
1363 lines.push(String::new());
1364 }
1365
1366 let derived = group(PruneDisposition::DerivedFlagged);
1368 if !derived.is_empty() {
1369 lines.push("### Derived — flagged, NOT proposed for deletion".to_string());
1370 lines.push(String::new());
1371 lines.push(
1372 "These entities were **derived** from other inputs. A derived entity is flagged, \
1373 never auto-proposed for deletion — its inputs may still hold even though one source \
1374 artifact vanished. Re-examine the inputs before removing anything."
1375 .to_string(),
1376 );
1377 lines.push(String::new());
1378 let shown = derived.len().min(FINDINGS_CAP);
1379 for p in &derived[..shown] {
1380 let inputs = if p.derived_inputs.is_empty() {
1381 "(no recorded inputs)".to_string()
1382 } else {
1383 artifact_list(&p.derived_inputs)
1384 };
1385 lines.push(format!(
1386 "- `{}` — derived from: {}; source artifact(s) gone: {}.",
1387 p.entity,
1388 inputs,
1389 artifact_list(&p.artifacts)
1390 ));
1391 }
1392 if derived.len() > shown {
1393 lines.push(format!("- …and {} more", derived.len() - shown));
1394 }
1395 lines.push(String::new());
1396 }
1397
1398 format!("{}\n", lines.join("\n"))
1399}
1400
1401fn artifact_list(artifacts: &[String]) -> String {
1403 if artifacts.is_empty() {
1404 return "(none)".to_string();
1405 }
1406 artifacts
1407 .iter()
1408 .map(|a| format!("`{a}`"))
1409 .collect::<Vec<_>>()
1410 .join(", ")
1411}
1412
1413fn render_sync_situation(resolved: &ResolvedIngest) -> String {
1416 format!(
1417 "## Sync — repair the graph to match the source\n\n\
1418 You are running the sync pass for `{}`. Sync is the graph's **sole maintenance \
1419 writer**: the only place the destination mem `{}` is repaired to match its \
1420 source. Two inputs steer this pass — the source changes since the last sync, and \
1421 the open verify findings — both below. Work them: update, create, relate, and \
1422 (rarely) delete entities so the graph again matches the source.\n\n\
1423 Every mutation routes through the normal MCP mutation surface, and the engine \
1424 commits each one **per-mutation** to the mem's own gitdir. You **stage nothing \
1425 and commit nothing yourself** — not the graph, not the code. Sync commits \
1426 nothing.\n\n",
1427 resolved.name, resolved.destination_mem
1428 )
1429}
1430
1431fn render_adopt_framing(resolved: &ResolvedIngest) -> String {
1435 format!(
1436 "## First sync — adopting `{}`\n\n\
1437 This mem predates its binding: it has no anchors and no prior sync baseline, so \
1438 **0% anchored is expected — this is onboarding, not a failure.** Do not read it \
1439 as drift or a red verdict. There is no cursor to diff against, so the baseline is \
1440 the **current** source HEAD — do **not** replay the whole history; treat the \
1441 current source state as the starting point, and this is a **first sync**.\n\n\
1442 **Backfill path:** run `memstead projection verify {}` to enumerate the in-scope \
1443 source artifacts that carry no entity yet, then cover the clearly-new concepts \
1444 among them through the normal MCP mutation surface — the same conservative rules \
1445 below apply. Backfilling is incremental: a partial pass is fine, and the next \
1446 sync continues where you left off.\n\n",
1447 resolved.destination_mem, resolved.name
1448 )
1449}
1450
1451fn render_stale_claim_search(resolved: &ResolvedIngest) -> String {
1463 format!(
1464 "## Stale claims beyond the slice — search, then judge\n\n\
1465 A changed fact can be claimed by an entity whose anchors are all outside the \
1466 changed slice — anchor-steered repairs alone would leave that claim standing \
1467 falsified. Extract the **changed facts** from the changed artifacts above: \
1468 renamed identifiers, changed values or defaults, changed behaviors (e.g. an \
1469 exit code, a flag's meaning), removed or moved concepts. For each changed \
1470 fact, search the destination mem `{}` for claims about it (`memstead_search` \
1471 and its variants — try the new name, the old name/value, and close synonyms), \
1472 and judge **only** the entities whose claims actually mention a changed fact: \
1473 repair a claim the change falsifies, leave everything else untouched.\n\n\
1474 This is a bounded fact-search, not a live-verify of every entity and not a \
1475 rewrite license. If the changes carry no factual claims (formatting, \
1476 comments, cosmetic moves), the fact set is empty and this step ends with no \
1477 search and no edits.\n\n",
1478 resolved.destination_mem
1479 )
1480}
1481
1482fn render_sync_conservatism() -> String {
1486 let lines: Vec<&str> = vec![
1487 "## How to repair — be conservative",
1488 "",
1489 "Repair only what the source changes and the findings above actually justify:",
1490 "",
1491 "- **Unsure whether an entity is affected — skip it.** A missed update is a later \
1493 finding; a wrong rewrite is damage.",
1494 "- **Do not create a new entity unless the change clearly introduces a new concept \
1495 with no existing entity.** Prefer updating the entity that already owns the \
1496 concept.",
1497 "- **Do not delete an entity unless the change removes the concept entirely.** \
1498 Deletions a prune pass surfaces follow prune's own never-clobber / conflict-flag \
1499 rules — never delete on a hunch here.",
1500 "- **Never rewrite a section that has not changed** — touch only the part the \
1501 change or finding actually affects.",
1502 "- **No speculative edges — add only relationships the diff literally introduces** \
1503 (a new `use` / `import` / dependency you can point at in the change).",
1504 "- **A dropped dependency FLAGS, it does not auto-remove.** If the change removes an \
1506 import or dependency, leave the matching edge intact and note it for a later \
1507 audit — removals are ambiguous (temporary refactor vs. permanent cut), and a \
1508 stale edge is less damaging than an erased real one. **Edge removal is out of \
1509 scope for sync.**",
1510 "- **Rationale is reasoning, not a changelog.** When you record why a change was \
1512 made, append the *reasoning* (why this approach, which trade-offs) — never \
1513 `[commit <hash>]` log-style entries.",
1514 "",
1515 ];
1516
1517 format!("{}\n", lines.join("\n"))
1518}
1519
1520pub fn render_sync_brief(
1547 resolved: &ResolvedIngest,
1548 cursor: &SourceCursor,
1549 findings: &[Finding],
1550 prune: &[PruneProposal],
1551 adopt: bool,
1552 exclusions: &crate::ingest::advance::ExclusionLedger,
1553) -> String {
1554 let preface = render_changed_slice(cursor);
1555 let open_findings = render_open_findings(findings, &resolved.name);
1556 let prune_block = render_prune_proposals(prune);
1557 let has_work =
1558 adopt || !preface.is_empty() || !open_findings.is_empty() || !prune_block.is_empty();
1559
1560 let mut parts: Vec<String> = vec![
1564 render_sync_situation(resolved),
1565 render_exclusions(exclusions),
1566 ];
1567
1568 if !has_work {
1569 parts.push(
1570 "## Nothing to sync\n\nThe source has not moved since the last sync, no \
1571 verify findings are open, and no prune proposals stand. There is nothing to \
1572 repair this pass — reporting \"no changes\" is a valid outcome.\n\n"
1573 .to_string(),
1574 );
1575 return parts
1576 .into_iter()
1577 .filter(|p| !p.is_empty())
1578 .collect::<Vec<_>>()
1579 .join("");
1580 }
1581
1582 if adopt {
1583 parts.push(render_adopt_framing(resolved));
1584 }
1585 parts.push(preface);
1586 if cursor.any_changes {
1590 parts.push(render_stale_claim_search(resolved));
1591 }
1592 parts.push(open_findings);
1593 parts.push(prune_block);
1594 parts.push(render_anchor_instruction(resolved));
1595 parts.push(render_sync_conservatism());
1596
1597 parts
1598 .into_iter()
1599 .filter(|p| !p.is_empty())
1600 .collect::<Vec<_>>()
1601 .join("")
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606 use super::*;
1607 use crate::ingest::resolve::Source;
1608 use crate::pipeline::{IngestTrigger, PatternEntry};
1609
1610 fn guidance(goal: Option<&str>, avoid: Option<&str>) -> ResolvedGuidance {
1611 ResolvedGuidance {
1612 goal: goal.map(str::to_string),
1613 avoid: avoid.map(str::to_string),
1614 }
1615 }
1616
1617 #[test]
1620 fn renders_goal_and_avoid_blocks() {
1621 let out = render_goal_and_avoid(&guidance(Some(" build coverage "), Some("no stubs")));
1622 assert_eq!(
1623 out,
1624 "## Goal\n\nbuild coverage\n\n## Failure modes to avoid\n\nno stubs\n\n"
1625 );
1626 }
1627
1628 #[test]
1630 fn renders_goal_only() {
1631 assert_eq!(
1632 render_goal_and_avoid(&guidance(Some("build coverage"), None)),
1633 "## Goal\n\nbuild coverage\n\n"
1634 );
1635 }
1636
1637 #[test]
1639 fn renders_avoid_only() {
1640 assert_eq!(
1641 render_goal_and_avoid(&guidance(None, Some("no stubs"))),
1642 "## Failure modes to avoid\n\nno stubs\n\n"
1643 );
1644 }
1645
1646 #[test]
1649 fn empty_guidance_yields_a_newline() {
1650 assert_eq!(render_goal_and_avoid(&guidance(None, None)), "\n");
1651 assert_eq!(render_goal_and_avoid(&guidance(Some(" "), None)), "\n");
1653 }
1654
1655 fn primary(medium_type: MediumType, scope: Vec<PatternEntry>) -> ResolvedSource {
1656 ResolvedSource::Primary(Source {
1657 name: "f".to_string(),
1658 medium_type,
1659 pointer: "../src".to_string(),
1660 change_detection: None,
1661 scope,
1662 engagement: None,
1663 preparation: None,
1664 })
1665 }
1666
1667 fn resolved(name: &str, intent: Option<&str>, sources: Vec<ResolvedSource>) -> ResolvedIngest {
1668 ResolvedIngest {
1669 name: name.to_string(),
1670 mode: BuildMode::Discovery,
1671 trigger: IngestTrigger::Loop,
1672 batch_size: 20,
1673 deny_paths: vec![],
1674 projection_ref: format!("{name}/p"),
1675 projection_mem: name.to_string(),
1676 projection_name: "p".to_string(),
1677 intent: intent.map(str::to_string),
1678 sources,
1679 destination_mem: name.to_string(),
1680 rules: None,
1681 post_actions: None,
1682 }
1683 }
1684
1685 fn process_present(name: &str) -> ProcessMemInfo {
1686 ProcessMemInfo {
1687 present: true,
1688 skipped: false,
1689 notice: None,
1690 leaf_name: name.to_string(),
1691 mem_label: format!("ingest/{name}"),
1692 }
1693 }
1694
1695 fn allow(path: &str) -> PatternEntry {
1696 PatternEntry {
1697 path: path.to_string(),
1698 mode: PatternMode::Allow,
1699 }
1700 }
1701
1702 fn deny(path: &str) -> PatternEntry {
1703 PatternEntry {
1704 path: path.to_string(),
1705 mode: PatternMode::Deny,
1706 }
1707 }
1708
1709 #[test]
1711 fn renders_intent() {
1712 let r = resolved("macos", Some(" Swift app source. "), vec![]);
1713 assert_eq!(
1714 render_intent(&r),
1715 "## About the source\n\nSwift app source.\n\n"
1716 );
1717 let none = resolved("macos", None, vec![]);
1718 assert_eq!(render_intent(&none), "");
1719 }
1720
1721 #[test]
1724 fn renders_situation_with_present_process_mem() {
1725 let r = resolved("macos", None, vec![]);
1726 let out = render_situation(&r, &process_present("macos"));
1727 assert!(out.starts_with("## Situation\n\nYou are running one iteration of `macos` (discovery mode) inside a loop."));
1728 assert!(out.contains("Mutating the destination is this run's mandate:"));
1729 assert!(out.contains("The `PreCompact` hook fires near the limit"));
1730 assert!(out.contains("A paired process mem `ingest/macos` (schema `ingest@0.5.0`) carries destination-quality debt"));
1731 assert!(
1732 out.ends_with("write rules.\n\n"),
1733 "block ends in a blank line"
1734 );
1735 }
1736
1737 #[test]
1740 fn situation_process_mem_branches() {
1741 let mut r = resolved("os", None, vec![]);
1742 r.mode = BuildMode::OneShot;
1743 let skipped = ProcessMemInfo {
1744 present: false,
1745 skipped: true,
1746 notice: None,
1747 leaf_name: "os".to_string(),
1748 mem_label: "ingest/os".to_string(),
1749 };
1750 assert!(
1751 render_situation(&r, &skipped)
1752 .contains("No process mem is paired with this ingest (mode=one-shot;")
1753 );
1754
1755 let failed = ProcessMemInfo {
1756 present: false,
1757 skipped: false,
1758 notice: Some("engine offline".to_string()),
1759 leaf_name: "os".to_string(),
1760 mem_label: "ingest/os".to_string(),
1761 };
1762 let out = render_situation(&resolved("os", None, vec![]), &failed);
1763 assert!(out.contains("could not be auto-created — engine offline."));
1764 assert!(out.contains("memstead mem init os --org-path ingest --schema ingest@0.5.0"));
1765 }
1766
1767 #[test]
1771 fn renders_operative_data_full() {
1772 let r = resolved(
1773 "macos",
1774 None,
1775 vec![
1776 primary(
1777 MediumType::Codebase,
1778 vec![allow("src/**/*.swift"), deny("src/gen/**")],
1779 ),
1780 ResolvedSource::Reference {
1781 mem: "engine".to_string(),
1782 },
1783 ],
1784 );
1785 let out = render_operative_data(
1786 &r,
1787 &process_present("macos"),
1788 Some("macos-code@0.1.0"),
1789 None,
1790 &[],
1791 );
1792 let expected = "\
1793## Operative data
1794
1795### Sources
1796
1797- **f** (codebase, primary) — `../src`
1798 - Paths: src/**/*.swift
1799 - Ignore: src/gen/**
1800- **graph** (reference) — mem: engine
1801
1802Sources tagged `(reference)` are read-only context for cross-mem edges — search them, never write into them. Only `(primary)` sources are ingested into the destination.
1803
1804**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`).
1805
1806### Destination
1807
1808- **macos** — schema: `macos-code@0.1.0`
1809
1810### Paired process mem
1811
1812- **ingest/macos** — schema: `ingest@0.5.0`. Inspect via `memstead_overview` / `memstead_search mem=macos`.
1813\n";
1814 assert_eq!(out, expected);
1815 }
1816
1817 #[test]
1820 fn renders_operative_data_minimal() {
1821 let r = resolved("g", None, vec![primary(MediumType::Filesystem, vec![])]);
1822 let skipped = ProcessMemInfo {
1823 present: false,
1824 skipped: true,
1825 notice: None,
1826 leaf_name: "g".to_string(),
1827 mem_label: "ingest/g".to_string(),
1828 };
1829 let out = render_operative_data(&r, &skipped, None, Some("**absent** — probe"), &[]);
1830 assert!(out.contains("- **f** (filesystem, primary) — `"));
1833 assert!(!out.contains("Cross-mem references"), "no reference note");
1834 assert!(out.contains("### Destination\n\n- **g**\n"));
1835 assert!(
1838 out.contains("**absent** — probe"),
1839 "the caller's destination note must be rendered: {out}",
1840 );
1841 assert!(
1842 !out.contains("Paired process mem"),
1843 "skipped process mem omitted"
1844 );
1845 }
1846
1847 #[test]
1853 fn operative_data_warns_on_retired_scope_dialect() {
1854 let r = resolved(
1855 "g",
1856 None,
1857 vec![primary(
1860 MediumType::Filesystem,
1861 vec![allow("../src/**/*.md"), allow("notes/**")],
1862 )],
1863 );
1864 let skipped = ProcessMemInfo {
1865 present: false,
1866 skipped: true,
1867 notice: None,
1868 leaf_name: "g".to_string(),
1869 mem_label: "ingest/g".to_string(),
1870 };
1871 let out = render_operative_data(&r, &skipped, None, None, &[]);
1872 assert!(
1873 out.contains("workspace root"),
1874 "the block names the retired dialect: {out}"
1875 );
1876 assert!(
1877 out.contains("../src/**/*.md"),
1878 "the offending pattern is named: {out}"
1879 );
1880 assert!(
1881 out.contains("`**/*.md`"),
1882 "the mechanical rewrite is offered: {out}"
1883 );
1884
1885 let clean = resolved(
1887 "g",
1888 None,
1889 vec![primary(MediumType::Filesystem, vec![allow("**/*.md")])],
1890 );
1891 let out2 = render_operative_data(&clean, &skipped, None, None, &[]);
1892 assert!(
1893 !out2.contains("workspace root"),
1894 "no warning without a retired-dialect pattern: {out2}"
1895 );
1896 }
1897
1898 #[test]
1901 fn assembles_discovery_brief() {
1902 let r = resolved(
1903 "macos",
1904 Some("Swift source."),
1905 vec![primary(MediumType::Codebase, vec![allow("src/**")])],
1906 );
1907 let g = guidance(Some("build coverage"), None);
1908 let pm = process_present("macos");
1909 let brief = assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], "");
1910
1911 let sit = brief.find("## Situation").unwrap();
1913 let src = brief.find("## About the source").unwrap();
1914 let goal = brief.find("## Goal").unwrap();
1915 let op = brief.find("## Operative data").unwrap();
1916 let anchors = brief.find("## Provenance — anchor your writes").unwrap();
1917 assert!(
1918 sit < src && src < goal && goal < op && op < anchors,
1919 "blocks in brief order"
1920 );
1921 assert!(
1922 !brief.contains("## Source changes"),
1923 "no changed-slice block when preface empty"
1924 );
1925
1926 let with_slice = assemble_discovery_brief(
1928 &r,
1929 &g,
1930 &pm,
1931 Some("s@1"),
1932 None,
1933 &[],
1934 "## Source changes\n\n…\n\n",
1935 );
1936 assert!(with_slice.ends_with("## Source changes\n\n…\n\n"));
1937 }
1938
1939 fn slice(deleted: &[&str], modified: &[&str], added: &[&str]) -> Slice {
1940 Slice {
1941 deleted: deleted.iter().map(|s| s.to_string()).collect(),
1942 modified: modified.iter().map(|s| s.to_string()).collect(),
1943 added: added.iter().map(|s| s.to_string()).collect(),
1944 }
1945 }
1946
1947 fn cmd(key: &str, token: &str) -> SyncCommand {
1948 SyncCommand {
1949 key: key.to_string(),
1950 token: token.to_string(),
1951 }
1952 }
1953
1954 fn note(source: &str, reason: NoSignalReason) -> NoSignalNote {
1955 NoSignalNote {
1956 medium_type: None,
1957 source: source.to_string(),
1958 reason,
1959 }
1960 }
1961
1962 #[test]
1966 fn anchor_instruction_names_prepared_form_sources() {
1967 let mut resolved = resolved("home", None, vec![primary(MediumType::Codebase, vec![])]);
1968 let plain = render_anchor_instruction(&resolved);
1969 assert!(!plain.contains("hash a prepared form"));
1970 if let Some(ResolvedSource::Primary(src)) = resolved.sources.first_mut() {
1971 src.preparation = Some(crate::preparation::CODE_MAP.to_string());
1972 }
1973 let prepared = render_anchor_instruction(&resolved);
1974 assert!(
1975 prepared.contains("hash a prepared form (`code-map`)"),
1976 "{prepared}"
1977 );
1978 assert!(prepared.contains("interface digest"));
1979 assert!(prepared.contains("for a `file` or `span` anchor pass the artifact's `content`"));
1980 assert!(prepared.contains("a `tree` anchor takes no content"));
1981 }
1982
1983 #[test]
1988 fn changed_slice_renders_delivery_sequences_in_order() {
1989 use crate::preparation::UnitChange;
1990 let unit = |id: &str, order: &str, change: UnitChange, disposed: bool| DeliveredUnit {
1991 id: id.to_string(),
1992 order_key: order.to_string(),
1993 change,
1994 disposed,
1995 };
1996 let units = vec![
1997 unit(
1998 "log/b.md#2026-08-20T00:00:00",
1999 "2026-08-20T00:00:00",
2000 UnitChange::Added,
2001 true,
2002 ),
2003 unit(
2004 "log/a.md#2026-08-21T00:00:00",
2005 "2026-08-21T00:00:00",
2006 UnitChange::Deleted,
2007 false,
2008 ),
2009 unit(
2010 "log/b.md#2026-08-22T00:00:00",
2011 "2026-08-22T00:00:00",
2012 UnitChange::Modified,
2013 false,
2014 ),
2015 unit(
2016 "log/a.md#2026-08-23T00:00:00",
2017 "2026-08-23T00:00:00",
2018 UnitChange::Added,
2019 false,
2020 ),
2021 ];
2022 let cursor = SourceCursor {
2023 union: slice(
2025 &["log/a.md#2026-08-21T00:00:00"],
2026 &["log/b.md#2026-08-22T00:00:00"],
2027 &[
2028 "log/a.md#2026-08-23T00:00:00",
2029 "log/b.md#2026-08-20T00:00:00",
2030 "other/x.rs",
2031 ],
2032 ),
2033 write_commands: vec![],
2034 reseed: vec![],
2035 no_signal: vec![],
2036 any_changes: true,
2037 degraded: false,
2038 dead_denies: vec![],
2039 dest_mem: "home".to_string(),
2040 binding_id: "home/log".to_string(),
2041 delivery: vec![DeliverySequence {
2042 source: "log".to_string(),
2043 preparation: "dated-entries".to_string(),
2044 first_run: false,
2045 degraded: true,
2046 batch: 2,
2047 units,
2048 }],
2049 };
2050 let out = render_changed_slice(&cursor);
2051 assert!(
2052 out.contains("### Delivery sequence: `log` (`dated-entries`)"),
2053 "{out}"
2054 );
2055 assert!(out.contains("The units that changed since the last pass"));
2056 assert!(out.contains("No baseline content was retrievable"));
2057 let listed: Vec<&str> = out
2058 .lines()
2059 .filter(|l| l.starts_with(|c: char| c.is_ascii_digit()))
2060 .collect();
2061 assert_eq!(
2062 listed,
2063 vec![
2064 "2. `log/a.md#2026-08-21T00:00:00` (deleted)",
2065 "3. `log/b.md#2026-08-22T00:00:00` (changed)",
2066 ],
2067 "positions are total-order positions; the disposed first unit is skipped"
2068 );
2069 assert!(out.contains("…and 1 more, presented in order once these are disposed"));
2070 assert!(out.contains("1 unit of this sequence already disposed"));
2071 assert!(out.contains("**Added:**\n- `other/x.rs`\n"), "{out}");
2073 assert!(!out.contains("**Modified:**"));
2074 assert!(!out.contains("**Deleted:**"));
2075 }
2076
2077 #[test]
2079 fn changed_slice_empty_when_nothing_moved() {
2080 let cursor = SourceCursor {
2081 union: slice(&[], &[], &[]),
2082 write_commands: vec![],
2083 reseed: vec![],
2084 no_signal: vec![],
2085 any_changes: false,
2086 degraded: false,
2087 dead_denies: vec![],
2088 dest_mem: "engine".to_string(),
2089 binding_id: "engine/graph".to_string(),
2090 delivery: vec![],
2091 };
2092 assert_eq!(render_changed_slice(&cursor), "");
2093 }
2094
2095 #[test]
2099 fn changed_slice_renders_dead_deny_warning() {
2100 let cursor = SourceCursor {
2101 union: slice(&[], &[], &[]),
2102 write_commands: vec![],
2103 reseed: vec![],
2104 no_signal: vec![],
2105 any_changes: false,
2106 degraded: false,
2107 dead_denies: vec!["dev".to_string(), "typo/**".to_string()],
2108 dest_mem: "engine".to_string(),
2109 binding_id: "engine/graph".to_string(),
2110 delivery: vec![],
2111 };
2112 let out = render_changed_slice(&cursor);
2113 assert!(out.contains("deny_paths` entries match nothing"));
2114 assert!(out.contains("- `dev`"));
2115 assert!(out.contains("- `typo/**`"));
2116 }
2117
2118 #[test]
2122 fn changed_slice_renders_slice_and_recording() {
2123 let cursor = SourceCursor {
2124 union: slice(&["a.rs"], &["b.rs"], &[]),
2125 write_commands: vec![cmd("engine-graph/source", "HEADSHA")],
2126 reseed: vec![],
2127 no_signal: vec![],
2128 any_changes: true,
2129 degraded: false,
2130 dead_denies: vec![],
2131 dest_mem: "engine".to_string(),
2132 binding_id: "engine/graph".to_string(),
2133 delivery: vec![],
2134 };
2135 let expected_lines = [
2136 "## Source changes since the last sync\n",
2137 "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",
2138 "**Deleted:**",
2139 "- `a.rs`",
2140 "",
2141 "**Modified:**",
2142 "- `b.rs`",
2143 "",
2144 "### Recording your dispositions (do this LAST)\n",
2145 "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",
2146 "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",
2147 "```sh",
2148 r#"memstead projection advance engine/graph --dispositions '{"<artifact>": "<disposition>", ...}'"#,
2149 "```",
2150 "If you were interrupted before finishing, that is fine — your recorded dispositions persist, and the next run re-presents only what is left.\n",
2151 ];
2152 assert_eq!(
2153 render_changed_slice(&cursor),
2154 format!("{}\n", expected_lines.join("\n"))
2155 );
2156 }
2157
2158 #[test]
2161 fn changed_slice_reseed_only() {
2162 let cursor = SourceCursor {
2163 union: slice(&[], &[], &[]),
2164 write_commands: vec![],
2165 reseed: vec![cmd("ing/f", "TOK")],
2166 no_signal: vec![],
2167 any_changes: false,
2168 degraded: false,
2169 dead_denies: vec![],
2170 dest_mem: "d".to_string(),
2171 binding_id: "d/p".to_string(),
2172 delivery: vec![],
2173 };
2174 let out = render_changed_slice(&cursor);
2175 assert!(out.starts_with("## Source changes since the last sync\n\n"));
2176 assert!(out.contains(
2177 "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."
2178 ));
2179 assert!(out.contains(
2180 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2181 ));
2182 assert!(
2183 !out.contains("The source moved"),
2184 "no 'moved' copy when only reseeding"
2185 );
2186 }
2187
2188 #[test]
2194 fn changed_slice_renders_no_signal_reasons_distinguishably() {
2195 let cursor = SourceCursor {
2196 union: slice(&[], &[], &[]),
2197 write_commands: vec![],
2198 reseed: vec![],
2199 no_signal: vec![
2200 note("code-facet", NoSignalReason::Unscoped),
2201 note("plan-facet", NoSignalReason::DetectionNone),
2202 note("git-facet", NoSignalReason::GitUnavailable),
2203 note("ref-mem", NoSignalReason::GraphSnapshotMissing),
2204 ],
2205 any_changes: false,
2206 degraded: false,
2207 dead_denies: vec![],
2208 dest_mem: "d".to_string(),
2209 binding_id: "d/p".to_string(),
2210 delivery: vec![],
2211 };
2212 let out = render_changed_slice(&cursor);
2213 assert!(out.starts_with("## Source changes since the last sync\n"));
2214 assert!(out.contains("Some sources produced **no change signal**"));
2215 assert!(out.contains("- `code-facet`: unscoped facet (no allow patterns)"));
2217 assert!(
2218 out.contains("- `plan-facet`: `signal:none`"),
2219 "detection-none renders the literal signal:none state"
2220 );
2221 assert!(out.contains("- `git-facet`: git signal unavailable"));
2222 assert!(out.contains("- `ref-mem`: graph snapshot missing"));
2223 let texts = [
2225 no_signal_reason_text(NoSignalReason::Unscoped, None),
2226 no_signal_reason_text(NoSignalReason::DetectionNone, None),
2227 no_signal_reason_text(NoSignalReason::GitUnavailable, None),
2228 no_signal_reason_text(NoSignalReason::GraphSnapshotMissing, None),
2229 ];
2230 for (i, a) in texts.iter().enumerate() {
2231 for b in &texts[i + 1..] {
2232 assert_ne!(a, b, "each no-signal reason must render distinctly");
2233 }
2234 }
2235 assert!(!out.contains("### Recording your dispositions"));
2237 assert!(!out.contains("The source moved"));
2238 }
2239
2240 #[test]
2244 fn changed_slice_mixes_changes_and_no_signal() {
2245 let cursor = SourceCursor {
2246 union: slice(&[], &["b.rs"], &[]),
2247 write_commands: vec![cmd("ing/f", "HEAD")],
2248 reseed: vec![],
2249 no_signal: vec![note("other", NoSignalReason::Unscoped)],
2250 any_changes: true,
2251 degraded: false,
2252 dead_denies: vec![],
2253 dest_mem: "d".to_string(),
2254 binding_id: "d/p".to_string(),
2255 delivery: vec![],
2256 };
2257 let out = render_changed_slice(&cursor);
2258 assert!(out.contains("The source moved"));
2259 assert!(out.contains("**Modified:**"));
2260 assert!(out.contains("- `other`: unscoped facet"));
2261 assert!(out.contains("### Recording your dispositions"));
2262 assert!(out.contains(
2263 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2264 ));
2265 }
2266
2267 #[test]
2270 fn renders_one_shot_lens_block() {
2271 let mut r = resolved("os", Some("plan source"), vec![]);
2272 r.rules = Some(serde_json::json!({ "routing": "route each entity to its spec" }));
2273 r.post_actions = Some(serde_json::json!({ "archive_source": true }));
2274
2275 let out = render_one_shot_lens(&r, Some("planning@0.1.0"), Some("the plan graph"));
2276 assert!(out.starts_with("## Mode: one-shot — lens routing\n\n"));
2277 assert!(out.contains(
2278 "### Destination set\n\n| Mem | Schema | Purpose |\n|-------|--------|---------|\n| os | planning@0.1.0 | the plan graph |\n"
2279 ));
2280 assert!(out.contains("### Routing rule\n\n```\nroute each entity to its spec\n```\n"));
2281 assert!(out.contains("### Idempotency"));
2282 assert!(out.contains("### Report: os"));
2283 assert!(out.contains("### Archive after run"));
2284 assert!(out.ends_with("is set on this ingest.\n\n"));
2285
2286 let bare = resolved("os", None, vec![]);
2289 let out2 = render_one_shot_lens(&bare, None, None);
2290 assert!(out2.contains("| os | (none) | (no purpose declared) |"));
2291 assert!(!out2.contains("### Routing rule"));
2292 assert!(!out2.contains("### Archive after run"));
2293 assert!(out2.contains("### End-of-run report"));
2294 }
2295
2296 #[test]
2299 fn assembles_one_shot_brief() {
2300 let mut r = resolved(
2301 "os",
2302 Some("src"),
2303 vec![primary(MediumType::Filesystem, vec![])],
2304 );
2305 r.mode = BuildMode::OneShot;
2306 let g = guidance(Some("goal"), None);
2307 let skipped = ProcessMemInfo {
2308 present: false,
2309 skipped: true,
2310 notice: None,
2311 leaf_name: "os".to_string(),
2312 mem_label: "ingest/os".to_string(),
2313 };
2314 let brief =
2315 assemble_one_shot_brief(&r, &g, &skipped, Some("s@1"), None, &[], Some("purpose"));
2316 assert!(brief.contains("(one-shot mode)"));
2317 assert!(brief.contains("No process mem is paired with this ingest (mode=one-shot;"));
2318 assert!(brief.contains("## Mode: one-shot — lens routing"));
2319 assert!(
2320 brief.contains("## Provenance — anchor your writes"),
2321 "one-shot carries the anchor instruction"
2322 );
2323 assert!(
2324 !brief.contains("## Source changes"),
2325 "one-shot has no changed-slice"
2326 );
2327 }
2328
2329 #[test]
2333 fn changed_slice_caps_and_degrades_and_quotes() {
2334 let many: Vec<String> = (0..SLICE_CAP + 3).map(|i| format!("f{i}.rs")).collect();
2335 let cursor = SourceCursor {
2336 union: Slice {
2337 deleted: vec![],
2338 modified: vec![],
2339 added: many,
2340 },
2341 write_commands: vec![cmd("ing/f", r#"{"v":1,"aggregate":"x"}"#)],
2342 reseed: vec![],
2343 no_signal: vec![],
2344 any_changes: true,
2345 degraded: true,
2346 dead_denies: vec![],
2347 dest_mem: "d".to_string(),
2348 binding_id: "d/p".to_string(),
2349 delivery: vec![],
2350 };
2351 let out = render_changed_slice(&cursor);
2352 assert!(out.contains(&format!("- …and {} more added", 3)));
2353 assert!(out.contains("Precise change history for one or more facets was unavailable"));
2354 assert!(out.contains(
2357 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2358 ));
2359 }
2360
2361 fn finding(class: FindingClass, target: FindingTarget, detail: &str) -> Finding {
2364 Finding {
2365 key: crate::ingest::findings::FindingKey {
2366 binding_hash: "h".to_string(),
2367 source_head: "s".to_string(),
2368 },
2369 facet: "src".to_string(),
2370 target,
2371 class,
2372 detail: detail.to_string(),
2373 created_at: "1".to_string(),
2374 }
2375 }
2376
2377 fn anchor_target(entity: &str, artifact: &str) -> FindingTarget {
2378 FindingTarget::Anchor {
2379 entity: entity.to_string(),
2380 artifact: artifact.to_string(),
2381 }
2382 }
2383
2384 fn artifact_target(artifact: &str) -> FindingTarget {
2385 FindingTarget::Artifact {
2386 artifact: artifact.to_string(),
2387 }
2388 }
2389
2390 fn empty_cursor() -> SourceCursor {
2391 SourceCursor {
2392 union: slice(&[], &[], &[]),
2393 write_commands: vec![],
2394 reseed: vec![],
2395 no_signal: vec![],
2396 any_changes: false,
2397 degraded: false,
2398 dead_denies: vec![],
2399 dest_mem: "engine".to_string(),
2400 binding_id: "engine/graph".to_string(),
2401 delivery: vec![],
2402 }
2403 }
2404
2405 #[test]
2409 fn verify_brief_measures_and_refuses_mutation() {
2410 let r = resolved("engine", None, vec![]);
2411 let out = render_verify_brief(&r, 3);
2412 assert!(out.starts_with("## Verify — measure fidelity, do not mutate"));
2414 assert!(out.contains("3 finding(s) are queued for adjudication"));
2415 assert!(out.contains("per-run adjudication cap"));
2416 assert!(out.contains("this is a measurement, not a repair"));
2417 assert!(out.contains("Verify writes **no entity content**"));
2430 assert!(out.contains("`#verified` baseline"));
2431 assert!(out.contains("memstead projection brief --sync"));
2432 assert!(out.contains("do not create or delete an entity"));
2435 assert!(!out.contains("via `memstead_create`"));
2436 assert!(!out.contains("Run `memstead_update`"));
2437
2438 let zero = render_verify_brief(&r, 0);
2440 assert!(zero.contains("No findings are queued for adjudication"));
2441 assert!(zero.contains("record any drift you observe as a finding"));
2442 assert!(zero.contains("Verify writes **no entity content**"));
2443 }
2444
2445 #[test]
2449 fn sync_brief_carries_both_cursor_and_findings() {
2450 let r = resolved("engine", None, vec![]);
2451 let cursor = SourceCursor {
2452 union: slice(&["gone.rs"], &["moved.rs"], &[]),
2453 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2454 reseed: vec![],
2455 no_signal: vec![],
2456 any_changes: true,
2457 degraded: false,
2458 dead_denies: vec![],
2459 dest_mem: "engine".to_string(),
2460 binding_id: "engine/graph".to_string(),
2461 delivery: vec![],
2462 };
2463 let findings = vec![
2464 finding(
2465 FindingClass::Drifted,
2466 anchor_target("engine--e", "src/moved.rs"),
2467 "prepared-content hash drifted",
2468 ),
2469 finding(
2470 FindingClass::Uncovered,
2471 artifact_target("src/new.rs"),
2472 "in scope, no anchor",
2473 ),
2474 ];
2475 let out = render_sync_brief(
2476 &r,
2477 &cursor,
2478 &findings,
2479 &[],
2480 false,
2481 &crate::ingest::advance::ExclusionLedger::default(),
2482 );
2483 assert!(out.contains("## Source changes since the last sync"));
2485 assert!(out.contains("`moved.rs`"));
2486 assert!(out.contains("## Open findings to repair"));
2487 assert!(out.contains("`engine--e` → `src/moved.rs`"));
2488 assert!(out.contains("`src/new.rs`"));
2489 assert!(out.contains("sole maintenance writer"));
2491 assert!(out.contains("commits each one **per-mutation**"));
2492 assert!(out.contains("Sync commits nothing."));
2493 }
2494
2495 #[test]
2500 fn sync_brief_absorbs_reconcile_conservatism() {
2501 let r = resolved("engine", None, vec![]);
2502 let findings = vec![finding(
2503 FindingClass::Uncovered,
2504 artifact_target("src/x.rs"),
2505 "d",
2506 )];
2507 let out = render_sync_brief(
2508 &r,
2509 &empty_cursor(),
2510 &findings,
2511 &[],
2512 false,
2513 &crate::ingest::advance::ExclusionLedger::default(),
2514 );
2515 assert!(out.contains("Unsure whether an entity is affected — skip it."));
2517 assert!(out.contains(
2518 "Do not create a new entity unless the change clearly introduces a new concept"
2519 ));
2520 assert!(
2521 out.contains("Do not delete an entity unless the change removes the concept entirely.")
2522 );
2523 assert!(out.contains("Never rewrite a section that has not changed"));
2524 assert!(out.contains(
2525 "No speculative edges — add only relationships the diff literally introduces"
2526 ));
2527 assert!(out.contains("A dropped dependency FLAGS, it does not auto-remove."));
2529 assert!(out.contains("Edge removal is out of scope for sync."));
2530 assert!(out.contains("Rationale is reasoning, not a changelog."));
2532 assert!(out.contains("`[commit <hash>]` log-style entries"));
2533 }
2534
2535 #[test]
2539 fn sync_brief_renders_adopt_framing() {
2540 let mut r = resolved("engine", None, vec![]);
2541 r.name = "engine/graph".to_string();
2545 let out = render_sync_brief(
2546 &r,
2547 &empty_cursor(),
2548 &[],
2549 &[],
2550 true,
2551 &crate::ingest::advance::ExclusionLedger::default(),
2552 );
2553 assert!(out.contains("## First sync — adopting `engine`"));
2554 assert!(out.contains("0% anchored is expected — this is onboarding, not a failure."));
2555 assert!(out.contains("do **not** replay the whole history"));
2556 assert!(out.contains("**Backfill path:**"));
2557 assert!(out.contains("memstead projection verify engine/graph"));
2558 }
2559
2560 #[test]
2563 fn sync_brief_inherits_first_sync_reseed_framing() {
2564 let r = resolved("engine", None, vec![]);
2565 let mut cursor = empty_cursor();
2566 cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2567 let out = render_sync_brief(
2568 &r,
2569 &cursor,
2570 &[],
2571 &[],
2572 false,
2573 &crate::ingest::advance::ExclusionLedger::default(),
2574 );
2575 assert!(out.contains("No usable sync baseline exists for"));
2576 assert!(out.contains("Treating the current source state as the baseline"));
2577 }
2578
2579 #[test]
2582 fn sync_brief_nothing_to_sync() {
2583 let r = resolved("engine", None, vec![]);
2584 let out = render_sync_brief(
2585 &r,
2586 &empty_cursor(),
2587 &[],
2588 &[],
2589 false,
2590 &crate::ingest::advance::ExclusionLedger::default(),
2591 );
2592 assert!(out.contains("## Nothing to sync"));
2593 assert!(!out.contains("## How to repair"));
2594 assert!(!out.contains("## Open findings"));
2595 }
2596
2597 #[test]
2602 fn only_sync_brief_carries_repair_instructions() {
2603 let r = resolved("engine", None, vec![]);
2604 let findings = vec![finding(
2605 FindingClass::Drifted,
2606 anchor_target("engine--e", "src/a.rs"),
2607 "d",
2608 )];
2609 let verify = render_verify_brief(&r, 1);
2610 let sync = render_sync_brief(
2611 &r,
2612 &empty_cursor(),
2613 &findings,
2614 &[],
2615 false,
2616 &crate::ingest::advance::ExclusionLedger::default(),
2617 );
2618 assert!(!verify.contains("## How to repair"));
2620 assert!(!verify.contains("Update the affected section"));
2621 assert!(sync.contains("## How to repair — be conservative"));
2623 assert!(sync.contains("## Open findings to repair"));
2624 assert!(sync.contains("Update the affected section to match"));
2625 }
2626
2627 #[test]
2631 fn sync_brief_changed_slice_renders_stale_claim_search() {
2632 let r = resolved("engine", None, vec![]);
2633 let cursor = SourceCursor {
2634 union: slice(&[], &["moved.rs"], &[]),
2635 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2636 reseed: vec![],
2637 no_signal: vec![],
2638 any_changes: true,
2639 degraded: false,
2640 dead_denies: vec![],
2641 dest_mem: "engine".to_string(),
2642 binding_id: "engine/graph".to_string(),
2643 delivery: vec![],
2644 };
2645 let out = render_sync_brief(
2646 &r,
2647 &cursor,
2648 &[],
2649 &[],
2650 false,
2651 &crate::ingest::advance::ExclusionLedger::default(),
2652 );
2653 assert!(out.contains("## Stale claims beyond the slice — search, then judge"));
2654 assert!(out.contains("Extract the **changed facts** from the changed artifacts above"));
2656 assert!(out.contains("search the destination mem `engine`"));
2657 assert!(out.contains("`memstead_search`"));
2658 assert!(out.contains("judge **only** the entities whose claims actually mention"));
2659 assert!(out.contains("not a live-verify of every entity"));
2662 assert!(out.contains("not a rewrite license"));
2663 assert!(out.contains("the fact set is empty and this step ends with no"));
2664 assert!(out.contains("Never rewrite a section that has not changed"));
2667 }
2668
2669 #[test]
2673 fn sync_brief_without_changes_renders_no_stale_claim_search() {
2674 let r = resolved("engine", None, vec![]);
2675 let heading = "## Stale claims beyond the slice";
2676
2677 let findings = vec![finding(
2679 FindingClass::Uncovered,
2680 artifact_target("src/x.rs"),
2681 "d",
2682 )];
2683 let out = render_sync_brief(
2684 &r,
2685 &empty_cursor(),
2686 &findings,
2687 &[],
2688 false,
2689 &crate::ingest::advance::ExclusionLedger::default(),
2690 );
2691 assert!(!out.contains(heading), "findings-only pass must not search");
2692
2693 let mut reseed_cursor = empty_cursor();
2695 reseed_cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2696 let out = render_sync_brief(
2697 &r,
2698 &reseed_cursor,
2699 &[],
2700 &[],
2701 false,
2702 &crate::ingest::advance::ExclusionLedger::default(),
2703 );
2704 assert!(!out.contains(heading), "reseed-only pass must not search");
2705
2706 let out = render_sync_brief(
2708 &r,
2709 &empty_cursor(),
2710 &[],
2711 &[],
2712 false,
2713 &crate::ingest::advance::ExclusionLedger::default(),
2714 );
2715 assert!(!out.contains(heading));
2716 }
2717
2718 #[test]
2721 fn sync_brief_caps_large_findings_group() {
2722 let r = resolved("engine", None, vec![]);
2723 let findings: Vec<Finding> = (0..FINDINGS_CAP + 4)
2724 .map(|i| {
2725 finding(
2726 FindingClass::Uncovered,
2727 artifact_target(&format!("src/f{i}.rs")),
2728 "d",
2729 )
2730 })
2731 .collect();
2732 let out = render_sync_brief(
2733 &r,
2734 &empty_cursor(),
2735 &findings,
2736 &[],
2737 false,
2738 &crate::ingest::advance::ExclusionLedger::default(),
2739 );
2740 assert!(out.contains("- …and 4 more"));
2741 assert!(!out.contains(&format!("src/f{}.rs", FINDINGS_CAP + 3)));
2743 }
2744
2745 #[test]
2756 fn sync_brief_block_sequence_locked_for_changed_slice() {
2757 let r = resolved("engine", None, vec![]);
2758 let cursor = SourceCursor {
2759 union: slice(&["gone.rs"], &["moved.rs"], &["new.rs"]),
2760 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2761 reseed: vec![],
2762 no_signal: vec![],
2763 any_changes: true,
2764 degraded: false,
2765 dead_denies: vec![],
2766 dest_mem: "engine".to_string(),
2767 binding_id: "engine/graph".to_string(),
2768 delivery: vec![],
2769 };
2770 let findings = vec![
2771 finding(
2772 FindingClass::Drifted,
2773 anchor_target("engine--e", "src/moved.rs"),
2774 "prepared-content hash drifted",
2775 ),
2776 finding(
2777 FindingClass::Uncovered,
2778 artifact_target("src/new.rs"),
2779 "in scope, no anchor",
2780 ),
2781 ];
2782 let out = render_sync_brief(
2783 &r,
2784 &cursor,
2785 &findings,
2786 &[],
2787 false,
2788 &crate::ingest::advance::ExclusionLedger::default(),
2789 );
2790 let headings: Vec<&str> = out
2791 .lines()
2792 .filter(|l| l.starts_with("## ") || l.starts_with("### "))
2793 .collect();
2794 assert_eq!(
2795 headings,
2796 vec![
2797 "## Sync — repair the graph to match the source",
2798 "## Source changes since the last sync",
2799 "### Recording your dispositions (do this LAST)",
2800 "## Stale claims beyond the slice — search, then judge",
2801 "## Open findings to repair",
2802 "### Drifted — the anchored content changed",
2803 "### Uncovered — a source artifact with no entity",
2804 "## Provenance — anchor your writes",
2808 "## How to repair — be conservative",
2809 ],
2810 "the loop-path sync brief carries exactly these blocks, in this order"
2811 );
2812 assert!(out.ends_with("`[commit <hash>]` log-style entries.\n\n"));
2815 }
2816
2817 #[test]
2828 fn no_default_path_brief_carries_inventory_machinery() {
2829 let inventory_terms = [
2832 "--full",
2833 "inventory",
2834 "full measurement",
2835 "did not converge",
2836 "quiescence",
2837 ];
2838 let assert_clean = |label: &str, text: &str| {
2839 let lower = text.to_lowercase();
2840 for term in inventory_terms {
2841 assert!(
2842 !lower.contains(term),
2843 "{label} must carry no inventory machinery (found {term:?})"
2844 );
2845 }
2846 };
2847
2848 let r = resolved("engine", None, vec![]);
2849 let g = guidance(Some("build coverage"), None);
2850 let pm = process_present("engine");
2851
2852 let changed_cursor = SourceCursor {
2854 union: slice(&[], &["moved.rs"], &[]),
2855 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2856 reseed: vec![],
2857 no_signal: vec![],
2858 any_changes: true,
2859 degraded: false,
2860 dead_denies: vec![],
2861 dest_mem: "engine".to_string(),
2862 binding_id: "engine/graph".to_string(),
2863 delivery: vec![],
2864 };
2865 let preface = render_changed_slice(&changed_cursor);
2866 assert_clean(
2867 "discovery build brief (plain roam)",
2868 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], ""),
2869 );
2870 assert_clean(
2871 "discovery build brief (changed slice)",
2872 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], &preface),
2873 );
2874 assert_clean(
2875 "one-shot build brief",
2876 &assemble_one_shot_brief(&r, &g, &pm, Some("s@1"), None, &[], Some("purpose")),
2877 );
2878
2879 assert_clean("verify brief (backlog)", &render_verify_brief(&r, 3));
2881 assert_clean("verify brief (no backlog)", &render_verify_brief(&r, 0));
2882
2883 let findings = vec![finding(
2885 FindingClass::Drifted,
2886 anchor_target("engine--e", "src/moved.rs"),
2887 "d",
2888 )];
2889 assert_clean(
2890 "sync brief (changed slice + findings)",
2891 &render_sync_brief(
2892 &r,
2893 &changed_cursor,
2894 &findings,
2895 &[],
2896 false,
2897 &crate::ingest::advance::ExclusionLedger::default(),
2898 ),
2899 );
2900 assert_clean(
2901 "sync brief (findings-only)",
2902 &render_sync_brief(
2903 &r,
2904 &empty_cursor(),
2905 &findings,
2906 &[],
2907 false,
2908 &crate::ingest::advance::ExclusionLedger::default(),
2909 ),
2910 );
2911 assert_clean(
2912 "sync brief (nothing to sync)",
2913 &render_sync_brief(
2914 &r,
2915 &empty_cursor(),
2916 &[],
2917 &[],
2918 false,
2919 &crate::ingest::advance::ExclusionLedger::default(),
2920 ),
2921 );
2922 assert_clean(
2923 "sync brief (adopt)",
2924 &render_sync_brief(
2925 &r,
2926 &empty_cursor(),
2927 &[],
2928 &[],
2929 true,
2930 &crate::ingest::advance::ExclusionLedger::default(),
2931 ),
2932 );
2933 }
2934}