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 for source in &resolved.sources {
812 let crate::ingest::resolve::ResolvedSource::Primary(src) = source else {
813 continue;
814 };
815 let Some(prep) = src
816 .preparation
817 .as_deref()
818 .and_then(crate::preparation::lookup)
819 else {
820 continue;
821 };
822 let what = match prep.id {
823 crate::preparation::CODE_MAP => {
824 "the file's interface digest (imports, exports, signatures; comments, \
825 formatting and bodies invisible), and a `tree` anchor the code map of every \
826 scoped file under it"
827 }
828 crate::preparation::DATED_ENTRIES => {
829 "the unit's own text for a `<path>#<key>` span, the file's bytes otherwise"
830 }
831 crate::preparation::ENTITY_LOAD_BEARING => "the entity's load-bearing sections",
832 _ => prep.description,
833 };
834 block.push_str(&format!(
835 "Anchors on `{}` hash a prepared form (`{}`): {what}. Never compute `hash` \
836 yourself for this source — leave it empty (verify records it on first \
837 observation), or for a `file` or `span` anchor pass the artifact's `content` \
838 and the engine hashes the prepared form (a `tree` anchor takes no content).\n\n",
839 src.name, prep.id
840 ));
841 }
842 block
843}
844
845#[allow(clippy::too_many_arguments)]
846pub fn assemble_discovery_brief(
847 resolved: &ResolvedIngest,
848 guidance: &ResolvedGuidance,
849 process_mem: &ProcessMemInfo,
850 destination_schema: Option<&str>,
851 destination_note: Option<&str>,
852 absent_sources: &[String],
853 changed_slice_preface: &str,
854) -> String {
855 let parts = [
856 render_situation(resolved, process_mem),
857 render_intent(resolved),
858 render_goal_and_avoid(guidance),
859 render_operative_data(
860 resolved,
861 process_mem,
862 destination_schema,
863 destination_note,
864 absent_sources,
865 ),
866 render_anchor_instruction(resolved),
867 changed_slice_preface.to_string(),
868 ];
869 parts
870 .into_iter()
871 .filter(|p| !p.is_empty())
872 .collect::<Vec<_>>()
873 .join("")
874}
875
876pub fn render_one_shot_lens(
882 resolved: &ResolvedIngest,
883 destination_schema: Option<&str>,
884 destination_purpose: Option<&str>,
885) -> String {
886 let cell = |s: &str| s.replace('|', "\\|").replace('\n', " ");
887 let mut lines: Vec<String> = vec![
888 "## Mode: one-shot — lens routing".to_string(),
889 String::new(),
890 "A lens iterates entities once and writes per-destination, then exits. The agent decides \
891 per-entity which destinations to target (Routing rule). Re-runs use `memstead_update`; \
892 never duplicate."
893 .to_string(),
894 String::new(),
895 ];
896
897 lines.push("### Destination set".to_string());
898 lines.push(String::new());
899 lines.push("| Mem | Schema | Purpose |".to_string());
900 lines.push("|-------|--------|---------|".to_string());
901 let schema = destination_schema.unwrap_or("(none)");
902 let purpose = destination_purpose
903 .filter(|s| !s.is_empty())
904 .unwrap_or("(no purpose declared)");
905 lines.push(format!(
906 "| {} | {} | {} |",
907 cell(&resolved.destination_mem),
908 cell(schema),
909 cell(purpose)
910 ));
911 lines.push(String::new());
912
913 if let Some(routing) = resolved
914 .rules
915 .as_ref()
916 .and_then(|r| r.get("routing"))
917 .and_then(|v| v.as_str())
918 .map(str::trim)
919 .filter(|s| !s.is_empty())
920 {
921 lines.push("### Routing rule".to_string());
922 lines.push(String::new());
923 lines.push("```".to_string());
924 lines.push(routing.to_string());
925 lines.push("```".to_string());
926 lines.push(String::new());
927 }
928
929 lines.push("### Idempotency".to_string());
930 lines.push(String::new());
931 lines.push("- Search the destination before writing; route changes through `memstead_update` against the existing entity if present.".to_string());
932 lines.push("- Skip writes when the lifted content matches what is already there (record as `skipped: already-up-to-date`).".to_string());
933 lines.push(
934 "- Use `memstead_create` only when no entity for that concept exists yet.".to_string(),
935 );
936 lines.push(String::new());
937
938 lines.push("### End-of-run report".to_string());
939 lines.push(String::new());
940 lines.push("After every destination is processed, emit one block per destination on stdout, in Destination-set order:".to_string());
941 lines.push(String::new());
942 lines.push("```".to_string());
943 lines.push(format!("### Report: {}", resolved.name));
944 lines.push(String::new());
945 lines.push("Destination: <mem>".to_string());
946 lines.push(" created: <count>".to_string());
947 lines.push(" updated: <count>".to_string());
948 lines.push(" skipped: <count>".to_string());
949 lines.push(" failed: <count>".to_string());
950 lines.push(" failures:".to_string());
951 lines.push(" - <entity-key>: <error verbatim>".to_string());
952 lines.push(" skipped-detail:".to_string());
953 lines.push(" - <entity-key>: <one-line reason>".to_string());
954 lines.push("```".to_string());
955 lines.push(String::new());
956 lines.push("Per-destination commits are independent — partial success is the accepted failure mode. No rollback.".to_string());
957 lines.push(String::new());
958
959 let archive = resolved
960 .post_actions
961 .as_ref()
962 .and_then(|p| p.get("archive_source"))
963 .and_then(serde_json::Value::as_bool)
964 .unwrap_or(false);
965 if archive {
966 lines.push("### Archive after run".to_string());
967 lines.push(String::new());
968 lines.push("After the report has been emitted, archive the source planning mem — `post_actions.archive_source` is set on this ingest.".to_string());
969 lines.push(String::new());
970 }
971
972 format!("{}\n", lines.join("\n"))
973}
974
975#[allow(clippy::too_many_arguments)]
980pub fn assemble_one_shot_brief(
981 resolved: &ResolvedIngest,
982 guidance: &ResolvedGuidance,
983 process_mem: &ProcessMemInfo,
984 destination_schema: Option<&str>,
985 destination_note: Option<&str>,
986 absent_sources: &[String],
987 destination_purpose: Option<&str>,
988) -> String {
989 let parts = [
990 render_situation(resolved, process_mem),
991 render_intent(resolved),
992 render_goal_and_avoid(guidance),
993 render_operative_data(
994 resolved,
995 process_mem,
996 destination_schema,
997 destination_note,
998 absent_sources,
999 ),
1000 render_anchor_instruction(resolved),
1001 render_one_shot_lens(resolved, destination_schema, destination_purpose),
1002 ];
1003 parts
1004 .into_iter()
1005 .filter(|p| !p.is_empty())
1006 .collect::<Vec<_>>()
1007 .join("")
1008}
1009
1010use super::findings::{Finding, FindingClass, FindingTarget};
1020use super::prune::{PruneDisposition, PruneProposal};
1021
1022const FINDINGS_CAP: usize = SLICE_CAP;
1024
1025pub fn render_verify_brief(resolved: &ResolvedIngest, backlog: usize) -> String {
1034 let mut lines: Vec<String> = vec![
1035 "## Verify — measure fidelity, do not mutate".to_string(),
1036 String::new(),
1037 ];
1038 lines.push(format!(
1039 "You are measuring the fidelity of `{}` — how faithfully the destination mem \
1040 `{}` still matches its source. This pass **only measures**: read the source \
1041 and the mem's anchors, judge whether the graph still holds, and record what \
1042 you find. **You** write nothing into the destination mem — the run itself \
1043 records its findings store, backfills observed anchor hashes, and writes a \
1044 `#verified` baseline, which is engine bookkeeping, not your edits.",
1045 resolved.name, resolved.destination_mem
1046 ));
1047 lines.push(String::new());
1048
1049 lines.push(
1050 "Anchors may carry a `source` naming the binding entry point that produced them — \
1051 note it when recording findings, so fidelity stays measurable per source."
1052 .to_string(),
1053 );
1054 lines.push(String::new());
1055
1056 lines.push("### Adjudicate the queued findings (capped)".to_string());
1057 lines.push(String::new());
1058 if backlog == 0 {
1059 lines.push(
1060 "No findings are queued for adjudication this pass. Spot-check the resolving \
1061 anchors and the uncovered-artifact sample the fidelity report lists, and \
1062 record any drift you observe as a finding."
1063 .to_string(),
1064 );
1065 } else {
1066 lines.push(format!(
1067 "{backlog} finding(s) are queued for adjudication. Working up to the per-run \
1068 adjudication cap (an operations knob — the remainder stays queued and \
1069 re-presents on a later pass), take each queued finding and compare the \
1070 anchored source content against what the entity records. Classify it: still \
1071 accurate, or drifted. **Record the verdict — this is a measurement, not a \
1072 repair.** A drift you record becomes a finding the sync pass repairs; you do \
1073 not fix it here."
1074 ));
1075 }
1076 lines.push(String::new());
1077
1078 lines.push("### Out of scope for verify — no mutation".to_string());
1079 lines.push(String::new());
1080 lines.push(
1081 "Verify writes **no entity content**. Do not update a \
1082 `specifies` / `constraints` section, do not create or delete an entity, do not \
1083 add or remove a relationship. When measurement shows the graph is wrong, that \
1084 is a **finding** — the sync brief (`memstead projection brief --sync`) is the \
1085 one place those repairs are made. Leave every fix to it. (The run itself does \
1086 record its findings store, backfill observed anchor hashes, and write a \
1087 `#verified` baseline — engine bookkeeping, not your edits.)"
1088 .to_string(),
1089 );
1090 lines.push(String::new());
1091
1092 format!("{}\n", lines.join("\n"))
1093}
1094
1095fn finding_target_label(target: &FindingTarget) -> String {
1097 match target {
1098 FindingTarget::Anchor { entity, artifact } => format!("`{entity}` → `{artifact}`"),
1099 FindingTarget::Artifact { artifact } => format!("`{artifact}`"),
1100 }
1101}
1102
1103fn render_findings_group(
1106 lines: &mut Vec<String>,
1107 heading: &str,
1108 guidance: &str,
1109 items: &[&Finding],
1110) {
1111 if items.is_empty() {
1112 return;
1113 }
1114 lines.push(format!("### {heading}"));
1115 lines.push(String::new());
1116 lines.push(guidance.to_string());
1117 lines.push(String::new());
1118 let shown = items.len().min(FINDINGS_CAP);
1119 for f in &items[..shown] {
1120 lines.push(format!(
1121 "- {} — {}",
1122 finding_target_label(&f.target),
1123 f.detail
1124 ));
1125 }
1126 if items.len() > shown {
1127 lines.push(format!("- …and {} more", items.len() - shown));
1128 }
1129 lines.push(String::new());
1130}
1131
1132fn render_open_findings(findings: &[Finding], binding_id: &str) -> String {
1138 if findings.is_empty() {
1139 return String::new();
1140 }
1141 let mut lines: Vec<String> = vec![
1142 "## Open findings to repair".to_string(),
1143 String::new(),
1144 "The verify pass recorded these against the current source state. Repair them \
1145 conservatively (see the rules below); a finding you judge already correct needs \
1146 no write."
1147 .to_string(),
1148 String::new(),
1149 ];
1150
1151 let group = |class: FindingClass| -> Vec<&Finding> {
1152 findings.iter().filter(|f| f.class == class).collect()
1153 };
1154
1155 render_findings_group(
1158 &mut lines,
1159 "Drifted — the anchored content changed",
1160 "The source the entity describes moved. Update the affected section to match — \
1161 only the part that changed. If the entity is still accurate, leave it. Either \
1162 way, reset the anchor on the entity in ONE update call: `anchors_unset` the \
1163 row, then write it fresh in the same call's `anchors` (same artifact, grain, \
1164 class and source, no hash) — the next verify backfills the freshly observed \
1165 hash and the drift clears. A hashless re-declare WITHOUT the unset keeps the \
1166 stored baseline by design and clears nothing, and updating the entity alone, \
1167 or advancing the baseline, leaves the anchor drifted just the same.",
1168 &group(FindingClass::Drifted),
1169 );
1170 render_findings_group(
1171 &mut lines,
1172 "Wrong — an adjudicated content mismatch",
1173 "Adjudication found the entity no longer matches its source. Correct the \
1174 mismatched section; do not rewrite what still holds.",
1175 &group(FindingClass::Wrong),
1176 );
1177 render_findings_group(
1180 &mut lines,
1181 "Unresolvable anchor — the artifact is gone",
1182 "The source artifact an anchor references is no longer present. Delete the entity \
1183 **only** if the concept is removed entirely; otherwise leave it. Concept-level \
1184 removals are a prune concern with its own never-clobber / conflict-flag rules — \
1185 do not delete on a hunch here.",
1186 &group(FindingClass::UnresolvableAnchor),
1187 );
1188 let uncovered_guidance = format!(
1195 "An in-scope source artifact has no anchor in the mem. Create an entity for it \
1196 **only** if it is a clearly-new concept with no existing entity; otherwise \
1197 extend the entity that already owns the concept, or leave it for a discovery \
1198 build. A third answer is legitimate: the artifact is mined and deliberately \
1199 warrants no entity. Record that with a rationale — it stops presenting here \
1200 from the next brief on:\n\n```bash\nmemstead projection exclude {binding_id} \
1201 --exclusions '{{\"<artifact>\": \"<rationale>\"}}'\n```"
1202 );
1203 render_findings_group(
1204 &mut lines,
1205 "Uncovered — a source artifact with no entity",
1206 &uncovered_guidance,
1207 &group(FindingClass::Uncovered),
1208 );
1209 render_findings_group(
1211 &mut lines,
1212 "Queued for adjudication — not yet judged",
1213 "These are not adjudicated yet — that is the verify pass's job, not sync's. \
1214 **Skip them here**; they become repairable only after verify classifies them as \
1215 drifted.",
1216 &group(FindingClass::QueuedForAdjudication),
1217 );
1218
1219 format!("{}\n", lines.join("\n"))
1220}
1221
1222fn render_prune_proposals(proposals: &[PruneProposal]) -> String {
1233 if proposals.is_empty() {
1234 return String::new();
1235 }
1236 let mut lines: Vec<String> = vec![
1237 "## Prune — proposed removals (you decide; nothing is auto-deleted)".to_string(),
1238 String::new(),
1239 "The source removed the artifacts these entities describe. Each item below is a \
1240 **proposal**: prune writes nothing — you enact (or reject) the removal through the \
1241 normal MCP mutation surface. An `authored` entity is never proposed here; a `derived` \
1242 entity is flagged, never proposed for deletion."
1243 .to_string(),
1244 String::new(),
1245 ];
1246
1247 let group = |d: PruneDisposition| -> Vec<&PruneProposal> {
1248 proposals.iter().filter(|p| p.disposition == d).collect()
1249 };
1250
1251 let clean = group(PruneDisposition::CleanDelete);
1254 if !clean.is_empty() {
1255 lines.push("### Clean delete — never-clobber three-way merge is clean".to_string());
1256 lines.push(String::new());
1257 lines.push(
1258 "The source base leg was retrievable and the three-way merge found no model-side \
1259 divergence, so removal is safe. **Confirm, then delete via the mutation surface** — \
1260 this is still your call, not an auto-delete."
1261 .to_string(),
1262 );
1263 lines.push(String::new());
1264 let shown = clean.len().min(FINDINGS_CAP);
1265 for p in &clean[..shown] {
1266 lines.push(format!(
1267 "- `{}` — source artifact(s) gone: {}",
1268 p.entity,
1269 artifact_list(&p.artifacts)
1270 ));
1271 }
1272 if clean.len() > shown {
1273 lines.push(format!("- …and {} more", clean.len() - shown));
1274 }
1275 lines.push(String::new());
1276 }
1277
1278 let conflict = group(PruneDisposition::ConflictFlag);
1280 if !conflict.is_empty() {
1281 lines.push("### Conflict-flag — decide, never overwrite a model-side edit".to_string());
1282 lines.push(String::new());
1283 lines.push(
1284 "No retrievable base leg to merge against (a non-git source, or an anchor with no \
1285 pinned version). **Both sides are shown — decide deliberately.** If the concept is \
1286 truly gone, delete via the mutation surface; if the model side was edited on \
1287 purpose, keep it. Prune never overwrites a model-side edit for you."
1288 .to_string(),
1289 );
1290 lines.push(String::new());
1291 let shown = conflict.len().min(FINDINGS_CAP);
1292 for p in &conflict[..shown] {
1293 lines.push(format!(
1294 "- `{}` — **source side:** artifact(s) gone: {}; **model side:** the entity is \
1295 still present (may carry edits) — you decide.",
1296 p.entity,
1297 artifact_list(&p.artifacts)
1298 ));
1299 }
1300 if conflict.len() > shown {
1301 lines.push(format!("- …and {} more", conflict.len() - shown));
1302 }
1303 lines.push(String::new());
1304 }
1305
1306 let derived = group(PruneDisposition::DerivedFlagged);
1308 if !derived.is_empty() {
1309 lines.push("### Derived — flagged, NOT proposed for deletion".to_string());
1310 lines.push(String::new());
1311 lines.push(
1312 "These entities were **derived** from other inputs. A derived entity is flagged, \
1313 never auto-proposed for deletion — its inputs may still hold even though one source \
1314 artifact vanished. Re-examine the inputs before removing anything."
1315 .to_string(),
1316 );
1317 lines.push(String::new());
1318 let shown = derived.len().min(FINDINGS_CAP);
1319 for p in &derived[..shown] {
1320 let inputs = if p.derived_inputs.is_empty() {
1321 "(no recorded inputs)".to_string()
1322 } else {
1323 artifact_list(&p.derived_inputs)
1324 };
1325 lines.push(format!(
1326 "- `{}` — derived from: {}; source artifact(s) gone: {}.",
1327 p.entity,
1328 inputs,
1329 artifact_list(&p.artifacts)
1330 ));
1331 }
1332 if derived.len() > shown {
1333 lines.push(format!("- …and {} more", derived.len() - shown));
1334 }
1335 lines.push(String::new());
1336 }
1337
1338 format!("{}\n", lines.join("\n"))
1339}
1340
1341fn artifact_list(artifacts: &[String]) -> String {
1343 if artifacts.is_empty() {
1344 return "(none)".to_string();
1345 }
1346 artifacts
1347 .iter()
1348 .map(|a| format!("`{a}`"))
1349 .collect::<Vec<_>>()
1350 .join(", ")
1351}
1352
1353fn render_sync_situation(resolved: &ResolvedIngest) -> String {
1356 format!(
1357 "## Sync — repair the graph to match the source\n\n\
1358 You are running the sync pass for `{}`. Sync is the graph's **sole maintenance \
1359 writer**: the only place the destination mem `{}` is repaired to match its \
1360 source. Two inputs steer this pass — the source changes since the last sync, and \
1361 the open verify findings — both below. Work them: update, create, relate, and \
1362 (rarely) delete entities so the graph again matches the source.\n\n\
1363 Every mutation routes through the normal MCP mutation surface, and the engine \
1364 commits each one **per-mutation** to the mem's own gitdir. You **stage nothing \
1365 and commit nothing yourself** — not the graph, not the code. Sync commits \
1366 nothing.\n\n",
1367 resolved.name, resolved.destination_mem
1368 )
1369}
1370
1371fn render_adopt_framing(resolved: &ResolvedIngest) -> String {
1375 format!(
1376 "## First sync — adopting `{}`\n\n\
1377 This mem predates its binding: it has no anchors and no prior sync baseline, so \
1378 **0% anchored is expected — this is onboarding, not a failure.** Do not read it \
1379 as drift or a red verdict. There is no cursor to diff against, so the baseline is \
1380 the **current** source HEAD — do **not** replay the whole history; treat the \
1381 current source state as the starting point, and this is a **first sync**.\n\n\
1382 **Backfill path:** run `memstead projection verify {}` to enumerate the in-scope \
1383 source artifacts that carry no entity yet, then cover the clearly-new concepts \
1384 among them through the normal MCP mutation surface — the same conservative rules \
1385 below apply. Backfilling is incremental: a partial pass is fine, and the next \
1386 sync continues where you left off.\n\n",
1387 resolved.destination_mem, resolved.name
1388 )
1389}
1390
1391fn render_stale_claim_search(resolved: &ResolvedIngest) -> String {
1403 format!(
1404 "## Stale claims beyond the slice — search, then judge\n\n\
1405 A changed fact can be claimed by an entity whose anchors are all outside the \
1406 changed slice — anchor-steered repairs alone would leave that claim standing \
1407 falsified. Extract the **changed facts** from the changed artifacts above: \
1408 renamed identifiers, changed values or defaults, changed behaviors (e.g. an \
1409 exit code, a flag's meaning), removed or moved concepts. For each changed \
1410 fact, search the destination mem `{}` for claims about it (`memstead_search` \
1411 and its variants — try the new name, the old name/value, and close synonyms), \
1412 and judge **only** the entities whose claims actually mention a changed fact: \
1413 repair a claim the change falsifies, leave everything else untouched.\n\n\
1414 This is a bounded fact-search, not a live-verify of every entity and not a \
1415 rewrite license. If the changes carry no factual claims (formatting, \
1416 comments, cosmetic moves), the fact set is empty and this step ends with no \
1417 search and no edits.\n\n",
1418 resolved.destination_mem
1419 )
1420}
1421
1422fn render_sync_conservatism() -> String {
1426 let lines: Vec<&str> = vec![
1427 "## How to repair — be conservative",
1428 "",
1429 "Repair only what the source changes and the findings above actually justify:",
1430 "",
1431 "- **Unsure whether an entity is affected — skip it.** A missed update is a later \
1433 finding; a wrong rewrite is damage.",
1434 "- **Do not create a new entity unless the change clearly introduces a new concept \
1435 with no existing entity.** Prefer updating the entity that already owns the \
1436 concept.",
1437 "- **Do not delete an entity unless the change removes the concept entirely.** \
1438 Deletions a prune pass surfaces follow prune's own never-clobber / conflict-flag \
1439 rules — never delete on a hunch here.",
1440 "- **Never rewrite a section that has not changed** — touch only the part the \
1441 change or finding actually affects.",
1442 "- **No speculative edges — add only relationships the diff literally introduces** \
1443 (a new `use` / `import` / dependency you can point at in the change).",
1444 "- **A dropped dependency FLAGS, it does not auto-remove.** If the change removes an \
1446 import or dependency, leave the matching edge intact and note it for a later \
1447 audit — removals are ambiguous (temporary refactor vs. permanent cut), and a \
1448 stale edge is less damaging than an erased real one. **Edge removal is out of \
1449 scope for sync.**",
1450 "- **Rationale is reasoning, not a changelog.** When you record why a change was \
1452 made, append the *reasoning* (why this approach, which trade-offs) — never \
1453 `[commit <hash>]` log-style entries.",
1454 "",
1455 ];
1456
1457 format!("{}\n", lines.join("\n"))
1458}
1459
1460pub fn render_sync_brief(
1487 resolved: &ResolvedIngest,
1488 cursor: &SourceCursor,
1489 findings: &[Finding],
1490 prune: &[PruneProposal],
1491 adopt: bool,
1492) -> String {
1493 let preface = render_changed_slice(cursor);
1494 let open_findings = render_open_findings(findings, &resolved.name);
1495 let prune_block = render_prune_proposals(prune);
1496 let has_work =
1497 adopt || !preface.is_empty() || !open_findings.is_empty() || !prune_block.is_empty();
1498
1499 let mut parts: Vec<String> = vec![render_sync_situation(resolved)];
1500
1501 if !has_work {
1502 parts.push(
1503 "## Nothing to sync\n\nThe source has not moved since the last sync, no \
1504 verify findings are open, and no prune proposals stand. There is nothing to \
1505 repair this pass — reporting \"no changes\" is a valid outcome.\n\n"
1506 .to_string(),
1507 );
1508 return parts
1509 .into_iter()
1510 .filter(|p| !p.is_empty())
1511 .collect::<Vec<_>>()
1512 .join("");
1513 }
1514
1515 if adopt {
1516 parts.push(render_adopt_framing(resolved));
1517 }
1518 parts.push(preface);
1519 if cursor.any_changes {
1523 parts.push(render_stale_claim_search(resolved));
1524 }
1525 parts.push(open_findings);
1526 parts.push(prune_block);
1527 parts.push(render_anchor_instruction(resolved));
1528 parts.push(render_sync_conservatism());
1529
1530 parts
1531 .into_iter()
1532 .filter(|p| !p.is_empty())
1533 .collect::<Vec<_>>()
1534 .join("")
1535}
1536
1537#[cfg(test)]
1538mod tests {
1539 use super::*;
1540 use crate::ingest::resolve::Source;
1541 use crate::pipeline::{IngestTrigger, PatternEntry};
1542
1543 fn guidance(goal: Option<&str>, avoid: Option<&str>) -> ResolvedGuidance {
1544 ResolvedGuidance {
1545 goal: goal.map(str::to_string),
1546 avoid: avoid.map(str::to_string),
1547 }
1548 }
1549
1550 #[test]
1553 fn renders_goal_and_avoid_blocks() {
1554 let out = render_goal_and_avoid(&guidance(Some(" build coverage "), Some("no stubs")));
1555 assert_eq!(
1556 out,
1557 "## Goal\n\nbuild coverage\n\n## Failure modes to avoid\n\nno stubs\n\n"
1558 );
1559 }
1560
1561 #[test]
1563 fn renders_goal_only() {
1564 assert_eq!(
1565 render_goal_and_avoid(&guidance(Some("build coverage"), None)),
1566 "## Goal\n\nbuild coverage\n\n"
1567 );
1568 }
1569
1570 #[test]
1572 fn renders_avoid_only() {
1573 assert_eq!(
1574 render_goal_and_avoid(&guidance(None, Some("no stubs"))),
1575 "## Failure modes to avoid\n\nno stubs\n\n"
1576 );
1577 }
1578
1579 #[test]
1582 fn empty_guidance_yields_a_newline() {
1583 assert_eq!(render_goal_and_avoid(&guidance(None, None)), "\n");
1584 assert_eq!(render_goal_and_avoid(&guidance(Some(" "), None)), "\n");
1586 }
1587
1588 fn primary(medium_type: MediumType, scope: Vec<PatternEntry>) -> ResolvedSource {
1589 ResolvedSource::Primary(Source {
1590 name: "f".to_string(),
1591 medium_type,
1592 pointer: "../src".to_string(),
1593 change_detection: None,
1594 scope,
1595 engagement: None,
1596 preparation: None,
1597 })
1598 }
1599
1600 fn resolved(name: &str, intent: Option<&str>, sources: Vec<ResolvedSource>) -> ResolvedIngest {
1601 ResolvedIngest {
1602 name: name.to_string(),
1603 mode: BuildMode::Discovery,
1604 trigger: IngestTrigger::Loop,
1605 batch_size: 20,
1606 deny_paths: vec![],
1607 projection_ref: format!("{name}/p"),
1608 projection_mem: name.to_string(),
1609 projection_name: "p".to_string(),
1610 intent: intent.map(str::to_string),
1611 sources,
1612 destination_mem: name.to_string(),
1613 rules: None,
1614 post_actions: None,
1615 }
1616 }
1617
1618 fn process_present(name: &str) -> ProcessMemInfo {
1619 ProcessMemInfo {
1620 present: true,
1621 skipped: false,
1622 notice: None,
1623 leaf_name: name.to_string(),
1624 mem_label: format!("ingest/{name}"),
1625 }
1626 }
1627
1628 fn allow(path: &str) -> PatternEntry {
1629 PatternEntry {
1630 path: path.to_string(),
1631 mode: PatternMode::Allow,
1632 }
1633 }
1634
1635 fn deny(path: &str) -> PatternEntry {
1636 PatternEntry {
1637 path: path.to_string(),
1638 mode: PatternMode::Deny,
1639 }
1640 }
1641
1642 #[test]
1644 fn renders_intent() {
1645 let r = resolved("macos", Some(" Swift app source. "), vec![]);
1646 assert_eq!(
1647 render_intent(&r),
1648 "## About the source\n\nSwift app source.\n\n"
1649 );
1650 let none = resolved("macos", None, vec![]);
1651 assert_eq!(render_intent(&none), "");
1652 }
1653
1654 #[test]
1657 fn renders_situation_with_present_process_mem() {
1658 let r = resolved("macos", None, vec![]);
1659 let out = render_situation(&r, &process_present("macos"));
1660 assert!(out.starts_with("## Situation\n\nYou are running one iteration of `macos` (discovery mode) inside a loop."));
1661 assert!(out.contains("Mutating the destination is this run's mandate:"));
1662 assert!(out.contains("The `PreCompact` hook fires near the limit"));
1663 assert!(out.contains("A paired process mem `ingest/macos` (schema `ingest@0.5.0`) carries destination-quality debt"));
1664 assert!(
1665 out.ends_with("write rules.\n\n"),
1666 "block ends in a blank line"
1667 );
1668 }
1669
1670 #[test]
1673 fn situation_process_mem_branches() {
1674 let mut r = resolved("os", None, vec![]);
1675 r.mode = BuildMode::OneShot;
1676 let skipped = ProcessMemInfo {
1677 present: false,
1678 skipped: true,
1679 notice: None,
1680 leaf_name: "os".to_string(),
1681 mem_label: "ingest/os".to_string(),
1682 };
1683 assert!(
1684 render_situation(&r, &skipped)
1685 .contains("No process mem is paired with this ingest (mode=one-shot;")
1686 );
1687
1688 let failed = ProcessMemInfo {
1689 present: false,
1690 skipped: false,
1691 notice: Some("engine offline".to_string()),
1692 leaf_name: "os".to_string(),
1693 mem_label: "ingest/os".to_string(),
1694 };
1695 let out = render_situation(&resolved("os", None, vec![]), &failed);
1696 assert!(out.contains("could not be auto-created — engine offline."));
1697 assert!(out.contains("memstead mem init os --org-path ingest --schema ingest@0.5.0"));
1698 }
1699
1700 #[test]
1704 fn renders_operative_data_full() {
1705 let r = resolved(
1706 "macos",
1707 None,
1708 vec![
1709 primary(
1710 MediumType::Codebase,
1711 vec![allow("src/**/*.swift"), deny("src/gen/**")],
1712 ),
1713 ResolvedSource::Reference {
1714 mem: "engine".to_string(),
1715 },
1716 ],
1717 );
1718 let out = render_operative_data(
1719 &r,
1720 &process_present("macos"),
1721 Some("macos-code@0.1.0"),
1722 None,
1723 &[],
1724 );
1725 let expected = "\
1726## Operative data
1727
1728### Sources
1729
1730- **f** (codebase, primary) — `../src`
1731 - Paths: src/**/*.swift
1732 - Ignore: src/gen/**
1733- **graph** (reference) — mem: engine
1734
1735Sources tagged `(reference)` are read-only context for cross-mem edges — search them, never write into them. Only `(primary)` sources are ingested into the destination.
1736
1737**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`).
1738
1739### Destination
1740
1741- **macos** — schema: `macos-code@0.1.0`
1742
1743### Paired process mem
1744
1745- **ingest/macos** — schema: `ingest@0.5.0`. Inspect via `memstead_overview` / `memstead_search mem=macos`.
1746\n";
1747 assert_eq!(out, expected);
1748 }
1749
1750 #[test]
1753 fn renders_operative_data_minimal() {
1754 let r = resolved("g", None, vec![primary(MediumType::Filesystem, vec![])]);
1755 let skipped = ProcessMemInfo {
1756 present: false,
1757 skipped: true,
1758 notice: None,
1759 leaf_name: "g".to_string(),
1760 mem_label: "ingest/g".to_string(),
1761 };
1762 let out = render_operative_data(&r, &skipped, None, Some("**absent** — probe"), &[]);
1763 assert!(out.contains("- **f** (filesystem, primary) — `"));
1766 assert!(!out.contains("Cross-mem references"), "no reference note");
1767 assert!(out.contains("### Destination\n\n- **g**\n"));
1768 assert!(
1771 out.contains("**absent** — probe"),
1772 "the caller's destination note must be rendered: {out}",
1773 );
1774 assert!(
1775 !out.contains("Paired process mem"),
1776 "skipped process mem omitted"
1777 );
1778 }
1779
1780 #[test]
1786 fn operative_data_warns_on_retired_scope_dialect() {
1787 let r = resolved(
1788 "g",
1789 None,
1790 vec![primary(
1793 MediumType::Filesystem,
1794 vec![allow("../src/**/*.md"), allow("notes/**")],
1795 )],
1796 );
1797 let skipped = ProcessMemInfo {
1798 present: false,
1799 skipped: true,
1800 notice: None,
1801 leaf_name: "g".to_string(),
1802 mem_label: "ingest/g".to_string(),
1803 };
1804 let out = render_operative_data(&r, &skipped, None, None, &[]);
1805 assert!(
1806 out.contains("workspace root"),
1807 "the block names the retired dialect: {out}"
1808 );
1809 assert!(
1810 out.contains("../src/**/*.md"),
1811 "the offending pattern is named: {out}"
1812 );
1813 assert!(
1814 out.contains("`**/*.md`"),
1815 "the mechanical rewrite is offered: {out}"
1816 );
1817
1818 let clean = resolved(
1820 "g",
1821 None,
1822 vec![primary(MediumType::Filesystem, vec![allow("**/*.md")])],
1823 );
1824 let out2 = render_operative_data(&clean, &skipped, None, None, &[]);
1825 assert!(
1826 !out2.contains("workspace root"),
1827 "no warning without a retired-dialect pattern: {out2}"
1828 );
1829 }
1830
1831 #[test]
1834 fn assembles_discovery_brief() {
1835 let r = resolved(
1836 "macos",
1837 Some("Swift source."),
1838 vec![primary(MediumType::Codebase, vec![allow("src/**")])],
1839 );
1840 let g = guidance(Some("build coverage"), None);
1841 let pm = process_present("macos");
1842 let brief = assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], "");
1843
1844 let sit = brief.find("## Situation").unwrap();
1846 let src = brief.find("## About the source").unwrap();
1847 let goal = brief.find("## Goal").unwrap();
1848 let op = brief.find("## Operative data").unwrap();
1849 let anchors = brief.find("## Provenance — anchor your writes").unwrap();
1850 assert!(
1851 sit < src && src < goal && goal < op && op < anchors,
1852 "blocks in brief order"
1853 );
1854 assert!(
1855 !brief.contains("## Source changes"),
1856 "no changed-slice block when preface empty"
1857 );
1858
1859 let with_slice = assemble_discovery_brief(
1861 &r,
1862 &g,
1863 &pm,
1864 Some("s@1"),
1865 None,
1866 &[],
1867 "## Source changes\n\n…\n\n",
1868 );
1869 assert!(with_slice.ends_with("## Source changes\n\n…\n\n"));
1870 }
1871
1872 fn slice(deleted: &[&str], modified: &[&str], added: &[&str]) -> Slice {
1873 Slice {
1874 deleted: deleted.iter().map(|s| s.to_string()).collect(),
1875 modified: modified.iter().map(|s| s.to_string()).collect(),
1876 added: added.iter().map(|s| s.to_string()).collect(),
1877 }
1878 }
1879
1880 fn cmd(key: &str, token: &str) -> SyncCommand {
1881 SyncCommand {
1882 key: key.to_string(),
1883 token: token.to_string(),
1884 }
1885 }
1886
1887 fn note(source: &str, reason: NoSignalReason) -> NoSignalNote {
1888 NoSignalNote {
1889 medium_type: None,
1890 source: source.to_string(),
1891 reason,
1892 }
1893 }
1894
1895 #[test]
1899 fn anchor_instruction_names_prepared_form_sources() {
1900 let mut resolved = resolved("home", None, vec![primary(MediumType::Codebase, vec![])]);
1901 let plain = render_anchor_instruction(&resolved);
1902 assert!(!plain.contains("hash a prepared form"));
1903 if let Some(ResolvedSource::Primary(src)) = resolved.sources.first_mut() {
1904 src.preparation = Some(crate::preparation::CODE_MAP.to_string());
1905 }
1906 let prepared = render_anchor_instruction(&resolved);
1907 assert!(
1908 prepared.contains("hash a prepared form (`code-map`)"),
1909 "{prepared}"
1910 );
1911 assert!(prepared.contains("interface digest"));
1912 assert!(prepared.contains("for a `file` or `span` anchor pass the artifact's `content`"));
1913 assert!(prepared.contains("a `tree` anchor takes no content"));
1914 }
1915
1916 #[test]
1921 fn changed_slice_renders_delivery_sequences_in_order() {
1922 use crate::preparation::UnitChange;
1923 let unit = |id: &str, order: &str, change: UnitChange, disposed: bool| DeliveredUnit {
1924 id: id.to_string(),
1925 order_key: order.to_string(),
1926 change,
1927 disposed,
1928 };
1929 let units = vec![
1930 unit(
1931 "log/b.md#2026-08-20T00:00:00",
1932 "2026-08-20T00:00:00",
1933 UnitChange::Added,
1934 true,
1935 ),
1936 unit(
1937 "log/a.md#2026-08-21T00:00:00",
1938 "2026-08-21T00:00:00",
1939 UnitChange::Deleted,
1940 false,
1941 ),
1942 unit(
1943 "log/b.md#2026-08-22T00:00:00",
1944 "2026-08-22T00:00:00",
1945 UnitChange::Modified,
1946 false,
1947 ),
1948 unit(
1949 "log/a.md#2026-08-23T00:00:00",
1950 "2026-08-23T00:00:00",
1951 UnitChange::Added,
1952 false,
1953 ),
1954 ];
1955 let cursor = SourceCursor {
1956 union: slice(
1958 &["log/a.md#2026-08-21T00:00:00"],
1959 &["log/b.md#2026-08-22T00:00:00"],
1960 &[
1961 "log/a.md#2026-08-23T00:00:00",
1962 "log/b.md#2026-08-20T00:00:00",
1963 "other/x.rs",
1964 ],
1965 ),
1966 write_commands: vec![],
1967 reseed: vec![],
1968 no_signal: vec![],
1969 any_changes: true,
1970 degraded: false,
1971 dead_denies: vec![],
1972 dest_mem: "home".to_string(),
1973 binding_id: "home/log".to_string(),
1974 delivery: vec![DeliverySequence {
1975 source: "log".to_string(),
1976 preparation: "dated-entries".to_string(),
1977 first_run: false,
1978 degraded: true,
1979 batch: 2,
1980 units,
1981 }],
1982 };
1983 let out = render_changed_slice(&cursor);
1984 assert!(
1985 out.contains("### Delivery sequence: `log` (`dated-entries`)"),
1986 "{out}"
1987 );
1988 assert!(out.contains("The units that changed since the last pass"));
1989 assert!(out.contains("No baseline content was retrievable"));
1990 let listed: Vec<&str> = out
1991 .lines()
1992 .filter(|l| l.starts_with(|c: char| c.is_ascii_digit()))
1993 .collect();
1994 assert_eq!(
1995 listed,
1996 vec![
1997 "2. `log/a.md#2026-08-21T00:00:00` (deleted)",
1998 "3. `log/b.md#2026-08-22T00:00:00` (changed)",
1999 ],
2000 "positions are total-order positions; the disposed first unit is skipped"
2001 );
2002 assert!(out.contains("…and 1 more, presented in order once these are disposed"));
2003 assert!(out.contains("1 unit of this sequence already disposed"));
2004 assert!(out.contains("**Added:**\n- `other/x.rs`\n"), "{out}");
2006 assert!(!out.contains("**Modified:**"));
2007 assert!(!out.contains("**Deleted:**"));
2008 }
2009
2010 #[test]
2012 fn changed_slice_empty_when_nothing_moved() {
2013 let cursor = SourceCursor {
2014 union: slice(&[], &[], &[]),
2015 write_commands: vec![],
2016 reseed: vec![],
2017 no_signal: vec![],
2018 any_changes: false,
2019 degraded: false,
2020 dead_denies: vec![],
2021 dest_mem: "engine".to_string(),
2022 binding_id: "engine/graph".to_string(),
2023 delivery: vec![],
2024 };
2025 assert_eq!(render_changed_slice(&cursor), "");
2026 }
2027
2028 #[test]
2032 fn changed_slice_renders_dead_deny_warning() {
2033 let cursor = SourceCursor {
2034 union: slice(&[], &[], &[]),
2035 write_commands: vec![],
2036 reseed: vec![],
2037 no_signal: vec![],
2038 any_changes: false,
2039 degraded: false,
2040 dead_denies: vec!["dev".to_string(), "typo/**".to_string()],
2041 dest_mem: "engine".to_string(),
2042 binding_id: "engine/graph".to_string(),
2043 delivery: vec![],
2044 };
2045 let out = render_changed_slice(&cursor);
2046 assert!(out.contains("deny_paths` entries match nothing"));
2047 assert!(out.contains("- `dev`"));
2048 assert!(out.contains("- `typo/**`"));
2049 }
2050
2051 #[test]
2055 fn changed_slice_renders_slice_and_recording() {
2056 let cursor = SourceCursor {
2057 union: slice(&["a.rs"], &["b.rs"], &[]),
2058 write_commands: vec![cmd("engine-graph/source", "HEADSHA")],
2059 reseed: vec![],
2060 no_signal: vec![],
2061 any_changes: true,
2062 degraded: false,
2063 dead_denies: vec![],
2064 dest_mem: "engine".to_string(),
2065 binding_id: "engine/graph".to_string(),
2066 delivery: vec![],
2067 };
2068 let expected_lines = [
2069 "## Source changes since the last sync\n",
2070 "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",
2071 "**Deleted:**",
2072 "- `a.rs`",
2073 "",
2074 "**Modified:**",
2075 "- `b.rs`",
2076 "",
2077 "### Recording your dispositions (do this LAST)\n",
2078 "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",
2079 "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",
2080 "```sh",
2081 r#"memstead projection advance engine/graph --dispositions '{"<artifact>": "<disposition>", ...}'"#,
2082 "```",
2083 "If you were interrupted before finishing, that is fine — your recorded dispositions persist, and the next run re-presents only what is left.\n",
2084 ];
2085 assert_eq!(
2086 render_changed_slice(&cursor),
2087 format!("{}\n", expected_lines.join("\n"))
2088 );
2089 }
2090
2091 #[test]
2094 fn changed_slice_reseed_only() {
2095 let cursor = SourceCursor {
2096 union: slice(&[], &[], &[]),
2097 write_commands: vec![],
2098 reseed: vec![cmd("ing/f", "TOK")],
2099 no_signal: vec![],
2100 any_changes: false,
2101 degraded: false,
2102 dead_denies: vec![],
2103 dest_mem: "d".to_string(),
2104 binding_id: "d/p".to_string(),
2105 delivery: vec![],
2106 };
2107 let out = render_changed_slice(&cursor);
2108 assert!(out.starts_with("## Source changes since the last sync\n\n"));
2109 assert!(out.contains(
2110 "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."
2111 ));
2112 assert!(out.contains(
2113 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2114 ));
2115 assert!(
2116 !out.contains("The source moved"),
2117 "no 'moved' copy when only reseeding"
2118 );
2119 }
2120
2121 #[test]
2127 fn changed_slice_renders_no_signal_reasons_distinguishably() {
2128 let cursor = SourceCursor {
2129 union: slice(&[], &[], &[]),
2130 write_commands: vec![],
2131 reseed: vec![],
2132 no_signal: vec![
2133 note("code-facet", NoSignalReason::Unscoped),
2134 note("plan-facet", NoSignalReason::DetectionNone),
2135 note("git-facet", NoSignalReason::GitUnavailable),
2136 note("ref-mem", NoSignalReason::GraphSnapshotMissing),
2137 ],
2138 any_changes: false,
2139 degraded: false,
2140 dead_denies: vec![],
2141 dest_mem: "d".to_string(),
2142 binding_id: "d/p".to_string(),
2143 delivery: vec![],
2144 };
2145 let out = render_changed_slice(&cursor);
2146 assert!(out.starts_with("## Source changes since the last sync\n"));
2147 assert!(out.contains("Some sources produced **no change signal**"));
2148 assert!(out.contains("- `code-facet`: unscoped facet (no allow patterns)"));
2150 assert!(
2151 out.contains("- `plan-facet`: `signal:none`"),
2152 "detection-none renders the literal signal:none state"
2153 );
2154 assert!(out.contains("- `git-facet`: git signal unavailable"));
2155 assert!(out.contains("- `ref-mem`: graph snapshot missing"));
2156 let texts = [
2158 no_signal_reason_text(NoSignalReason::Unscoped, None),
2159 no_signal_reason_text(NoSignalReason::DetectionNone, None),
2160 no_signal_reason_text(NoSignalReason::GitUnavailable, None),
2161 no_signal_reason_text(NoSignalReason::GraphSnapshotMissing, None),
2162 ];
2163 for (i, a) in texts.iter().enumerate() {
2164 for b in &texts[i + 1..] {
2165 assert_ne!(a, b, "each no-signal reason must render distinctly");
2166 }
2167 }
2168 assert!(!out.contains("### Recording your dispositions"));
2170 assert!(!out.contains("The source moved"));
2171 }
2172
2173 #[test]
2177 fn changed_slice_mixes_changes_and_no_signal() {
2178 let cursor = SourceCursor {
2179 union: slice(&[], &["b.rs"], &[]),
2180 write_commands: vec![cmd("ing/f", "HEAD")],
2181 reseed: vec![],
2182 no_signal: vec![note("other", NoSignalReason::Unscoped)],
2183 any_changes: true,
2184 degraded: false,
2185 dead_denies: vec![],
2186 dest_mem: "d".to_string(),
2187 binding_id: "d/p".to_string(),
2188 delivery: vec![],
2189 };
2190 let out = render_changed_slice(&cursor);
2191 assert!(out.contains("The source moved"));
2192 assert!(out.contains("**Modified:**"));
2193 assert!(out.contains("- `other`: unscoped facet"));
2194 assert!(out.contains("### Recording your dispositions"));
2195 assert!(out.contains(
2196 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2197 ));
2198 }
2199
2200 #[test]
2203 fn renders_one_shot_lens_block() {
2204 let mut r = resolved("os", Some("plan source"), vec![]);
2205 r.rules = Some(serde_json::json!({ "routing": "route each entity to its spec" }));
2206 r.post_actions = Some(serde_json::json!({ "archive_source": true }));
2207
2208 let out = render_one_shot_lens(&r, Some("planning@0.1.0"), Some("the plan graph"));
2209 assert!(out.starts_with("## Mode: one-shot — lens routing\n\n"));
2210 assert!(out.contains(
2211 "### Destination set\n\n| Mem | Schema | Purpose |\n|-------|--------|---------|\n| os | planning@0.1.0 | the plan graph |\n"
2212 ));
2213 assert!(out.contains("### Routing rule\n\n```\nroute each entity to its spec\n```\n"));
2214 assert!(out.contains("### Idempotency"));
2215 assert!(out.contains("### Report: os"));
2216 assert!(out.contains("### Archive after run"));
2217 assert!(out.ends_with("is set on this ingest.\n\n"));
2218
2219 let bare = resolved("os", None, vec![]);
2222 let out2 = render_one_shot_lens(&bare, None, None);
2223 assert!(out2.contains("| os | (none) | (no purpose declared) |"));
2224 assert!(!out2.contains("### Routing rule"));
2225 assert!(!out2.contains("### Archive after run"));
2226 assert!(out2.contains("### End-of-run report"));
2227 }
2228
2229 #[test]
2232 fn assembles_one_shot_brief() {
2233 let mut r = resolved(
2234 "os",
2235 Some("src"),
2236 vec![primary(MediumType::Filesystem, vec![])],
2237 );
2238 r.mode = BuildMode::OneShot;
2239 let g = guidance(Some("goal"), None);
2240 let skipped = ProcessMemInfo {
2241 present: false,
2242 skipped: true,
2243 notice: None,
2244 leaf_name: "os".to_string(),
2245 mem_label: "ingest/os".to_string(),
2246 };
2247 let brief =
2248 assemble_one_shot_brief(&r, &g, &skipped, Some("s@1"), None, &[], Some("purpose"));
2249 assert!(brief.contains("(one-shot mode)"));
2250 assert!(brief.contains("No process mem is paired with this ingest (mode=one-shot;"));
2251 assert!(brief.contains("## Mode: one-shot — lens routing"));
2252 assert!(
2253 brief.contains("## Provenance — anchor your writes"),
2254 "one-shot carries the anchor instruction"
2255 );
2256 assert!(
2257 !brief.contains("## Source changes"),
2258 "one-shot has no changed-slice"
2259 );
2260 }
2261
2262 #[test]
2266 fn changed_slice_caps_and_degrades_and_quotes() {
2267 let many: Vec<String> = (0..SLICE_CAP + 3).map(|i| format!("f{i}.rs")).collect();
2268 let cursor = SourceCursor {
2269 union: Slice {
2270 deleted: vec![],
2271 modified: vec![],
2272 added: many,
2273 },
2274 write_commands: vec![cmd("ing/f", r#"{"v":1,"aggregate":"x"}"#)],
2275 reseed: vec![],
2276 no_signal: vec![],
2277 any_changes: true,
2278 degraded: true,
2279 dead_denies: vec![],
2280 dest_mem: "d".to_string(),
2281 binding_id: "d/p".to_string(),
2282 delivery: vec![],
2283 };
2284 let out = render_changed_slice(&cursor);
2285 assert!(out.contains(&format!("- …and {} more added", 3)));
2286 assert!(out.contains("Precise change history for one or more facets was unavailable"));
2287 assert!(out.contains(
2290 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2291 ));
2292 }
2293
2294 fn finding(class: FindingClass, target: FindingTarget, detail: &str) -> Finding {
2297 Finding {
2298 key: crate::ingest::findings::FindingKey {
2299 binding_hash: "h".to_string(),
2300 source_head: "s".to_string(),
2301 },
2302 facet: "src".to_string(),
2303 target,
2304 class,
2305 detail: detail.to_string(),
2306 created_at: "1".to_string(),
2307 }
2308 }
2309
2310 fn anchor_target(entity: &str, artifact: &str) -> FindingTarget {
2311 FindingTarget::Anchor {
2312 entity: entity.to_string(),
2313 artifact: artifact.to_string(),
2314 }
2315 }
2316
2317 fn artifact_target(artifact: &str) -> FindingTarget {
2318 FindingTarget::Artifact {
2319 artifact: artifact.to_string(),
2320 }
2321 }
2322
2323 fn empty_cursor() -> SourceCursor {
2324 SourceCursor {
2325 union: slice(&[], &[], &[]),
2326 write_commands: vec![],
2327 reseed: vec![],
2328 no_signal: vec![],
2329 any_changes: false,
2330 degraded: false,
2331 dead_denies: vec![],
2332 dest_mem: "engine".to_string(),
2333 binding_id: "engine/graph".to_string(),
2334 delivery: vec![],
2335 }
2336 }
2337
2338 #[test]
2342 fn verify_brief_measures_and_refuses_mutation() {
2343 let r = resolved("engine", None, vec![]);
2344 let out = render_verify_brief(&r, 3);
2345 assert!(out.starts_with("## Verify — measure fidelity, do not mutate"));
2347 assert!(out.contains("3 finding(s) are queued for adjudication"));
2348 assert!(out.contains("per-run adjudication cap"));
2349 assert!(out.contains("this is a measurement, not a repair"));
2350 assert!(out.contains("Verify writes **no entity content**"));
2363 assert!(out.contains("`#verified` baseline"));
2364 assert!(out.contains("memstead projection brief --sync"));
2365 assert!(out.contains("do not create or delete an entity"));
2368 assert!(!out.contains("via `memstead_create`"));
2369 assert!(!out.contains("Run `memstead_update`"));
2370
2371 let zero = render_verify_brief(&r, 0);
2373 assert!(zero.contains("No findings are queued for adjudication"));
2374 assert!(zero.contains("record any drift you observe as a finding"));
2375 assert!(zero.contains("Verify writes **no entity content**"));
2376 }
2377
2378 #[test]
2382 fn sync_brief_carries_both_cursor_and_findings() {
2383 let r = resolved("engine", None, vec![]);
2384 let cursor = SourceCursor {
2385 union: slice(&["gone.rs"], &["moved.rs"], &[]),
2386 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2387 reseed: vec![],
2388 no_signal: vec![],
2389 any_changes: true,
2390 degraded: false,
2391 dead_denies: vec![],
2392 dest_mem: "engine".to_string(),
2393 binding_id: "engine/graph".to_string(),
2394 delivery: vec![],
2395 };
2396 let findings = vec![
2397 finding(
2398 FindingClass::Drifted,
2399 anchor_target("engine--e", "src/moved.rs"),
2400 "prepared-content hash drifted",
2401 ),
2402 finding(
2403 FindingClass::Uncovered,
2404 artifact_target("src/new.rs"),
2405 "in scope, no anchor",
2406 ),
2407 ];
2408 let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2409 assert!(out.contains("## Source changes since the last sync"));
2411 assert!(out.contains("`moved.rs`"));
2412 assert!(out.contains("## Open findings to repair"));
2413 assert!(out.contains("`engine--e` → `src/moved.rs`"));
2414 assert!(out.contains("`src/new.rs`"));
2415 assert!(out.contains("sole maintenance writer"));
2417 assert!(out.contains("commits each one **per-mutation**"));
2418 assert!(out.contains("Sync commits nothing."));
2419 }
2420
2421 #[test]
2426 fn sync_brief_absorbs_reconcile_conservatism() {
2427 let r = resolved("engine", None, vec![]);
2428 let findings = vec![finding(
2429 FindingClass::Uncovered,
2430 artifact_target("src/x.rs"),
2431 "d",
2432 )];
2433 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2434 assert!(out.contains("Unsure whether an entity is affected — skip it."));
2436 assert!(out.contains(
2437 "Do not create a new entity unless the change clearly introduces a new concept"
2438 ));
2439 assert!(
2440 out.contains("Do not delete an entity unless the change removes the concept entirely.")
2441 );
2442 assert!(out.contains("Never rewrite a section that has not changed"));
2443 assert!(out.contains(
2444 "No speculative edges — add only relationships the diff literally introduces"
2445 ));
2446 assert!(out.contains("A dropped dependency FLAGS, it does not auto-remove."));
2448 assert!(out.contains("Edge removal is out of scope for sync."));
2449 assert!(out.contains("Rationale is reasoning, not a changelog."));
2451 assert!(out.contains("`[commit <hash>]` log-style entries"));
2452 }
2453
2454 #[test]
2458 fn sync_brief_renders_adopt_framing() {
2459 let mut r = resolved("engine", None, vec![]);
2460 r.name = "engine/graph".to_string();
2464 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], true);
2465 assert!(out.contains("## First sync — adopting `engine`"));
2466 assert!(out.contains("0% anchored is expected — this is onboarding, not a failure."));
2467 assert!(out.contains("do **not** replay the whole history"));
2468 assert!(out.contains("**Backfill path:**"));
2469 assert!(out.contains("memstead projection verify engine/graph"));
2470 }
2471
2472 #[test]
2475 fn sync_brief_inherits_first_sync_reseed_framing() {
2476 let r = resolved("engine", None, vec![]);
2477 let mut cursor = empty_cursor();
2478 cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2479 let out = render_sync_brief(&r, &cursor, &[], &[], false);
2480 assert!(out.contains("No usable sync baseline exists for"));
2481 assert!(out.contains("Treating the current source state as the baseline"));
2482 }
2483
2484 #[test]
2487 fn sync_brief_nothing_to_sync() {
2488 let r = resolved("engine", None, vec![]);
2489 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2490 assert!(out.contains("## Nothing to sync"));
2491 assert!(!out.contains("## How to repair"));
2492 assert!(!out.contains("## Open findings"));
2493 }
2494
2495 #[test]
2500 fn only_sync_brief_carries_repair_instructions() {
2501 let r = resolved("engine", None, vec![]);
2502 let findings = vec![finding(
2503 FindingClass::Drifted,
2504 anchor_target("engine--e", "src/a.rs"),
2505 "d",
2506 )];
2507 let verify = render_verify_brief(&r, 1);
2508 let sync = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2509 assert!(!verify.contains("## How to repair"));
2511 assert!(!verify.contains("Update the affected section"));
2512 assert!(sync.contains("## How to repair — be conservative"));
2514 assert!(sync.contains("## Open findings to repair"));
2515 assert!(sync.contains("Update the affected section to match"));
2516 }
2517
2518 #[test]
2522 fn sync_brief_changed_slice_renders_stale_claim_search() {
2523 let r = resolved("engine", None, vec![]);
2524 let cursor = SourceCursor {
2525 union: slice(&[], &["moved.rs"], &[]),
2526 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2527 reseed: vec![],
2528 no_signal: vec![],
2529 any_changes: true,
2530 degraded: false,
2531 dead_denies: vec![],
2532 dest_mem: "engine".to_string(),
2533 binding_id: "engine/graph".to_string(),
2534 delivery: vec![],
2535 };
2536 let out = render_sync_brief(&r, &cursor, &[], &[], false);
2537 assert!(out.contains("## Stale claims beyond the slice — search, then judge"));
2538 assert!(out.contains("Extract the **changed facts** from the changed artifacts above"));
2540 assert!(out.contains("search the destination mem `engine`"));
2541 assert!(out.contains("`memstead_search`"));
2542 assert!(out.contains("judge **only** the entities whose claims actually mention"));
2543 assert!(out.contains("not a live-verify of every entity"));
2546 assert!(out.contains("not a rewrite license"));
2547 assert!(out.contains("the fact set is empty and this step ends with no"));
2548 assert!(out.contains("Never rewrite a section that has not changed"));
2551 }
2552
2553 #[test]
2557 fn sync_brief_without_changes_renders_no_stale_claim_search() {
2558 let r = resolved("engine", None, vec![]);
2559 let heading = "## Stale claims beyond the slice";
2560
2561 let findings = vec![finding(
2563 FindingClass::Uncovered,
2564 artifact_target("src/x.rs"),
2565 "d",
2566 )];
2567 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2568 assert!(!out.contains(heading), "findings-only pass must not search");
2569
2570 let mut reseed_cursor = empty_cursor();
2572 reseed_cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2573 let out = render_sync_brief(&r, &reseed_cursor, &[], &[], false);
2574 assert!(!out.contains(heading), "reseed-only pass must not search");
2575
2576 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2578 assert!(!out.contains(heading));
2579 }
2580
2581 #[test]
2584 fn sync_brief_caps_large_findings_group() {
2585 let r = resolved("engine", None, vec![]);
2586 let findings: Vec<Finding> = (0..FINDINGS_CAP + 4)
2587 .map(|i| {
2588 finding(
2589 FindingClass::Uncovered,
2590 artifact_target(&format!("src/f{i}.rs")),
2591 "d",
2592 )
2593 })
2594 .collect();
2595 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2596 assert!(out.contains("- …and 4 more"));
2597 assert!(!out.contains(&format!("src/f{}.rs", FINDINGS_CAP + 3)));
2599 }
2600
2601 #[test]
2612 fn sync_brief_block_sequence_locked_for_changed_slice() {
2613 let r = resolved("engine", None, vec![]);
2614 let cursor = SourceCursor {
2615 union: slice(&["gone.rs"], &["moved.rs"], &["new.rs"]),
2616 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2617 reseed: vec![],
2618 no_signal: vec![],
2619 any_changes: true,
2620 degraded: false,
2621 dead_denies: vec![],
2622 dest_mem: "engine".to_string(),
2623 binding_id: "engine/graph".to_string(),
2624 delivery: vec![],
2625 };
2626 let findings = vec![
2627 finding(
2628 FindingClass::Drifted,
2629 anchor_target("engine--e", "src/moved.rs"),
2630 "prepared-content hash drifted",
2631 ),
2632 finding(
2633 FindingClass::Uncovered,
2634 artifact_target("src/new.rs"),
2635 "in scope, no anchor",
2636 ),
2637 ];
2638 let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2639 let headings: Vec<&str> = out
2640 .lines()
2641 .filter(|l| l.starts_with("## ") || l.starts_with("### "))
2642 .collect();
2643 assert_eq!(
2644 headings,
2645 vec![
2646 "## Sync — repair the graph to match the source",
2647 "## Source changes since the last sync",
2648 "### Recording your dispositions (do this LAST)",
2649 "## Stale claims beyond the slice — search, then judge",
2650 "## Open findings to repair",
2651 "### Drifted — the anchored content changed",
2652 "### Uncovered — a source artifact with no entity",
2653 "## Provenance — anchor your writes",
2657 "## How to repair — be conservative",
2658 ],
2659 "the loop-path sync brief carries exactly these blocks, in this order"
2660 );
2661 assert!(out.ends_with("`[commit <hash>]` log-style entries.\n\n"));
2664 }
2665
2666 #[test]
2677 fn no_default_path_brief_carries_inventory_machinery() {
2678 let inventory_terms = [
2681 "--full",
2682 "inventory",
2683 "full measurement",
2684 "did not converge",
2685 "quiescence",
2686 ];
2687 let assert_clean = |label: &str, text: &str| {
2688 let lower = text.to_lowercase();
2689 for term in inventory_terms {
2690 assert!(
2691 !lower.contains(term),
2692 "{label} must carry no inventory machinery (found {term:?})"
2693 );
2694 }
2695 };
2696
2697 let r = resolved("engine", None, vec![]);
2698 let g = guidance(Some("build coverage"), None);
2699 let pm = process_present("engine");
2700
2701 let changed_cursor = SourceCursor {
2703 union: slice(&[], &["moved.rs"], &[]),
2704 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2705 reseed: vec![],
2706 no_signal: vec![],
2707 any_changes: true,
2708 degraded: false,
2709 dead_denies: vec![],
2710 dest_mem: "engine".to_string(),
2711 binding_id: "engine/graph".to_string(),
2712 delivery: vec![],
2713 };
2714 let preface = render_changed_slice(&changed_cursor);
2715 assert_clean(
2716 "discovery build brief (plain roam)",
2717 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], ""),
2718 );
2719 assert_clean(
2720 "discovery build brief (changed slice)",
2721 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], &preface),
2722 );
2723 assert_clean(
2724 "one-shot build brief",
2725 &assemble_one_shot_brief(&r, &g, &pm, Some("s@1"), None, &[], Some("purpose")),
2726 );
2727
2728 assert_clean("verify brief (backlog)", &render_verify_brief(&r, 3));
2730 assert_clean("verify brief (no backlog)", &render_verify_brief(&r, 0));
2731
2732 let findings = vec![finding(
2734 FindingClass::Drifted,
2735 anchor_target("engine--e", "src/moved.rs"),
2736 "d",
2737 )];
2738 assert_clean(
2739 "sync brief (changed slice + findings)",
2740 &render_sync_brief(&r, &changed_cursor, &findings, &[], false),
2741 );
2742 assert_clean(
2743 "sync brief (findings-only)",
2744 &render_sync_brief(&r, &empty_cursor(), &findings, &[], false),
2745 );
2746 assert_clean(
2747 "sync brief (nothing to sync)",
2748 &render_sync_brief(&r, &empty_cursor(), &[], &[], false),
2749 );
2750 assert_clean(
2751 "sync brief (adopt)",
2752 &render_sync_brief(&r, &empty_cursor(), &[], &[], true),
2753 );
2754 }
2755}