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 if is_graph {
268 lines.push(format!(
269 " - Read the source baseline with `memstead_search mem={}` \
270 (add `entity_type=` to match a `type:` selector). The changed \
271 slice below is a delta against the last pass — it is not the \
272 whole source, and an entity absent from it may still be \
273 unprojected.",
274 p.pointer
275 ));
276 }
277 }
278 ResolvedSource::Reference { mem } => {
279 lines.push(format!("- **graph** (reference) — mem: {mem}"));
280 reference_mems.push(mem.clone());
281 }
282 }
283 }
284 lines.push(String::new());
285 if !reference_mems.is_empty() {
286 lines.push(
287 "Sources tagged `(reference)` are read-only context for cross-mem edges — search \
288 them, never write into them. Only `(primary)` sources are ingested into the \
289 destination."
290 .to_string(),
291 );
292 lines.push(String::new());
293 let mem_list = reference_mems
294 .iter()
295 .map(|v| format!("`memstead_search mem={v}`"))
296 .collect::<Vec<_>>()
297 .join(", ");
298 lines.push(format!(
299 "**Cross-mem references:** consult {mem_list} before authoring cross-mem edges. \
300 The target entity must exist — a wiki-link or relationship to a missing target \
301 either auto-stubs (silent) or fails authorization (`CROSS_MEM_RELATION`)."
302 ));
303 lines.push(String::new());
304 }
305 }
306
307 lines.push("### Destination".to_string());
309 lines.push(String::new());
310 let schema_bit = destination_schema
311 .map(|s| format!(" — schema: `{s}`"))
312 .unwrap_or_default();
313 lines.push(format!("- **{}**{schema_bit}", resolved.destination_mem));
314 if let Some(note) = destination_note {
325 lines.push(format!(" - {note}"));
326 }
327 lines.push(String::new());
328
329 if process_mem.present {
331 lines.push("### Paired process mem".to_string());
332 lines.push(String::new());
333 lines.push(format!(
334 "- **{}** — schema: `{PROCESS_MEM_SCHEMA}`. Inspect via `memstead_overview` / \
335 `memstead_search mem={}`.",
336 process_mem.mem_label, process_mem.leaf_name
337 ));
338 lines.push(String::new());
339 }
340
341 format!("{}\n", lines.join("\n"))
342}
343
344#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct SyncCommand {
351 pub key: String,
353 pub token: String,
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct NoSignalNote {
364 pub source: String,
367 pub reason: NoSignalReason,
369 pub medium_type: Option<MediumType>,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct SourceCursor {
383 pub union: Slice,
385 pub write_commands: Vec<SyncCommand>,
387 pub reseed: Vec<SyncCommand>,
389 pub no_signal: Vec<NoSignalNote>,
395 pub any_changes: bool,
397 pub degraded: bool,
399 pub dead_denies: Vec<String>,
408 pub dest_mem: String,
410 pub binding_id: String,
414 pub delivery: Vec<DeliverySequence>,
419}
420
421#[derive(Debug, Clone, PartialEq, Eq)]
423pub struct DeliveredUnit {
424 pub id: String,
426 pub order_key: String,
428 pub change: crate::preparation::UnitChange,
430 pub disposed: bool,
433}
434
435#[derive(Debug, Clone, PartialEq, Eq)]
439pub struct DeliverySequence {
440 pub source: String,
442 pub preparation: String,
444 pub first_run: bool,
446 pub degraded: bool,
449 pub batch: usize,
452 pub units: Vec<DeliveredUnit>,
454}
455
456fn shell_quote(s: &str) -> String {
460 format!("'{}'", s.replace('\'', "'\\''"))
461}
462
463fn render_delivery_sequence(lines: &mut Vec<String>, seq: &DeliverySequence) {
471 use crate::preparation::UnitChange;
472 lines.push(format!(
473 "### Delivery sequence: `{}` (`{}`)\n",
474 seq.source, seq.preparation
475 ));
476 let opening = if seq.first_run {
477 "First delivery of this source: every unit, in the source's own order."
478 } else {
479 "The units that changed since the last pass, at their positions in the source's own \
480 order."
481 };
482 lines.push(format!(
483 "{opening} Work them top to bottom: the order derives from the units' own keys, never \
484 from discovery or directory order, it is identical on every pass, and a unit assumes \
485 only the units numbered before it. Address a unit as `<path>#<key>` in anchors and \
486 dispositions.\n"
487 ));
488 if seq.degraded {
489 lines.push(
490 "_(No baseline content was retrievable for one or more changed files, so every unit \
491 of those files is listed; precision is coarser this pass only.)_\n"
492 .to_string(),
493 );
494 }
495 let pending: Vec<(usize, &DeliveredUnit)> = seq
496 .units
497 .iter()
498 .enumerate()
499 .filter(|(_, u)| !u.disposed)
500 .collect();
501 let disposed = seq.units.len() - pending.len();
502 let shown = if seq.batch == 0 {
503 pending.len()
504 } else {
505 pending.len().min(seq.batch)
506 };
507 for (position, unit) in &pending[..shown] {
508 let label = match unit.change {
509 UnitChange::Added => "new",
510 UnitChange::Modified => "changed",
511 UnitChange::Deleted => "deleted",
512 };
513 lines.push(format!("{}. `{}` ({label})", position + 1, unit.id));
514 }
515 if pending.len() > shown {
516 lines.push(format!(
517 "- …and {} more, presented in order once these are disposed",
518 pending.len() - shown
519 ));
520 }
521 if disposed > 0 {
522 lines.push(format!(
523 "_({disposed} unit{} of this sequence already disposed this pass.)_",
524 if disposed == 1 { "" } else { "s" }
525 ));
526 }
527 if pending.is_empty() {
528 lines.push(
529 "_(Every unit of this sequence is disposed; the baseline advances when the pass \
530 completes.)_"
531 .to_string(),
532 );
533 }
534 lines.push(String::new());
535}
536
537fn render_slice_class(lines: &mut Vec<String>, label: &str, paths: &[String]) {
538 if paths.is_empty() {
539 return;
540 }
541 let shown = paths.len().min(SLICE_CAP);
542 lines.push(format!("**{label}:**"));
543 for path in &paths[..shown] {
544 lines.push(format!("- `{path}`"));
545 }
546 if paths.len() > shown {
547 lines.push(format!(
548 "- …and {} more {}",
549 paths.len() - shown,
550 label.to_lowercase()
551 ));
552 }
553 lines.push(String::new());
554}
555
556fn no_signal_reason_text(reason: NoSignalReason, medium: Option<MediumType>) -> &'static str {
561 match reason {
562 NoSignalReason::Unscoped => match medium {
566 Some(MediumType::Graph) => {
567 "unscoped facet (no allow patterns) — nothing is monitored; write `*` in the \
568 facet scope to watch the whole mem, or `type:<entity_type>` / `id:<glob>` \
569 to narrow it (a graph source selects entities, not paths)"
570 }
571 _ => {
572 "unscoped facet (no allow patterns) — nothing is monitored; write `**/*` in the \
573 facet scope to watch the whole medium"
574 }
575 },
576 NoSignalReason::DetectionNone => {
577 "`signal:none` — change detection is disabled for this source (declared `none`)"
578 }
579 NoSignalReason::GitUnavailable => {
580 "git signal unavailable — no work tree, an unreadable `HEAD`, or an unknown baseline; \
581 a full re-roam is warranted this pass"
582 }
583 NoSignalReason::GraphSnapshotMissing => {
584 "graph snapshot missing — the source mem has no comparable baseline this pass"
585 }
586 }
587}
588
589pub fn render_changed_slice(cursor: &SourceCursor) -> String {
596 if !cursor.any_changes
597 && cursor.reseed.is_empty()
598 && cursor.no_signal.is_empty()
599 && cursor.dead_denies.is_empty()
600 {
601 return String::new();
602 }
603 let mut lines: Vec<String> = Vec::new();
604 lines.push("## Source changes since the last sync\n".to_string());
605
606 if cursor.any_changes {
607 lines.push(
608 "The source moved since this graph was last synced. Steer this pass at these changed \
609 artifacts **first** — they are where the graph is most likely now wrong.\n"
610 .to_string(),
611 );
612 for seq in &cursor.delivery {
616 render_delivery_sequence(&mut lines, seq);
617 }
618 let unit_ids: std::collections::BTreeSet<&str> = cursor
619 .delivery
620 .iter()
621 .flat_map(|s| s.units.iter().map(|u| u.id.as_str()))
622 .collect();
623 let without_units = |v: &[String]| -> Vec<String> {
624 v.iter()
625 .filter(|p| !unit_ids.contains(p.as_str()))
626 .cloned()
627 .collect()
628 };
629 render_slice_class(&mut lines, "Deleted", &without_units(&cursor.union.deleted));
631 render_slice_class(
632 &mut lines,
633 "Modified",
634 &without_units(&cursor.union.modified),
635 );
636 render_slice_class(&mut lines, "Added", &without_units(&cursor.union.added));
637 if cursor.degraded {
638 lines.push(
639 "_(Precise change history for one or more facets was unavailable, so its full \
640 current file set is listed above. Detection still fired from the durable baseline; \
641 targeting is coarser this pass only.)_\n"
642 .to_string(),
643 );
644 }
645 }
646
647 if !cursor.reseed.is_empty() {
648 let keys = cursor
649 .reseed
650 .iter()
651 .map(|r| format!("`{}`", r.key))
652 .collect::<Vec<_>>()
653 .join(", ");
654 let it = if cursor.reseed.len() == 1 {
655 "it"
656 } else {
657 "them"
658 };
659 lines.push(format!(
660 "No usable sync baseline exists for {keys} — none was recorded, or the recorded one \
661 is not a commit of the source's repo (foreign or garbage-collected). Treating the \
662 current source state as the baseline. No priority slice from {it} this pass; \
663 proceed as usual.\n"
664 ));
665 }
666
667 if !cursor.no_signal.is_empty() {
668 lines.push(
669 "Some sources produced **no change signal** this pass — detection could not compare \
670 them against a baseline, so they were not steered (roam them as usual). This is \
671 distinct from a source that was checked and had not moved:\n"
672 .to_string(),
673 );
674 for note in &cursor.no_signal {
675 lines.push(format!(
676 "- `{}`: {}",
677 note.source,
678 no_signal_reason_text(note.reason, note.medium_type)
679 ));
680 }
681 lines.push(String::new());
682 }
683
684 if !cursor.dead_denies.is_empty() {
685 lines.push(
686 "**Warning — some `deny_paths` entries match nothing.** The following ingest \
687 `deny_paths` selected **no file** in the project tree, so they exclude nothing from \
688 the slice and hide nothing from the ingest agent. This is usually a typo or a legacy \
689 bare name that never migrated to the workspace-relative glob dialect (e.g. `dev` → \
690 `dev/**`, `VISION.md` → `**/VISION.md`). Fix or remove them:\n"
691 .to_string(),
692 );
693 for entry in &cursor.dead_denies {
694 lines.push(format!("- `{entry}`"));
695 }
696 lines.push(String::new());
697 }
698
699 let has_baseline_to_advance = !cursor.write_commands.is_empty() || !cursor.reseed.is_empty();
707 if has_baseline_to_advance {
708 lines.push("### Recording your dispositions (do this LAST)\n".to_string());
709 lines.push(
710 "Only after you have worked the changed artifacts above — and only for the artifacts \
711 you actually judged — record a disposition for each, so the next pass targets just \
712 what changes next. This advance is resumable and non-stalling: a partial pass is \
713 honored, and if the source moves mid-pass the remaining slice re-presents \
714 (remaining + new) without losing your recorded work.\n"
715 .to_string(),
716 );
717 lines.push(
718 "Anchored work disposes itself: at advance time, every listed artifact that an \
719 anchor in the destination mem references is marked `worked` automatically (an \
720 explicit disposition you pass wins over the auto-mark). Supply dispositions only \
721 for the residue — artifacts you skipped, judged out of intent, or worked without \
722 anchors. The gate accepts only artifact ids listed above — an unknown id refuses \
723 the whole call. When every artifact is disposed, the sync baseline advances \
724 automatically. Run:\n"
725 .to_string(),
726 );
727 lines.push("```sh".to_string());
728 lines.push(format!(
729 "memstead projection advance {} --dispositions {}",
730 cursor.binding_id,
731 shell_quote(r#"{"<artifact>": "<disposition>", ...}"#)
732 ));
733 lines.push("```".to_string());
734 lines.push(
735 "If you were interrupted before finishing, that is fine — your recorded dispositions \
736 persist, and the next run re-presents only what is left.\n"
737 .to_string(),
738 );
739 }
740
741 format!("{}\n", lines.join("\n"))
742}
743
744pub fn render_anchor_instruction(resolved: &ResolvedIngest) -> String {
757 let mut block = "## Provenance — anchor your writes\n\n\
758 Attach an `anchors` list to every `memstead_create` / `memstead_update`, naming the \
759 source artifact(s) the entity is drawn from (the mutation tools document the element \
760 shape). Anchored writes are what verify measures coverage and drift against, and — on \
761 cursor-driven passes — what the advance gate auto-marks `worked`; an unanchored write \
762 leaves the fidelity report and the disposition window blind to your work.\n\n"
763 .to_string();
764 let primary_names: Vec<&str> = resolved
768 .sources
769 .iter()
770 .filter_map(|s| match s {
771 crate::ingest::resolve::ResolvedSource::Primary(src) => Some(src.name.as_str()),
772 crate::ingest::resolve::ResolvedSource::Reference { .. } => None,
773 })
774 .collect();
775 if !primary_names.is_empty() {
776 block.push_str(&format!(
777 "Set each anchor's `source` to the binding source name you drew the artifact \
778 from — this binding declares: {}. The name selects the pointer the \
779 artifact path is joined onto, so the wrong one usually refuses \
780 `INVALID_ANCHOR` (the path resolves under no candidate join). A name \
781 outside the list is NOT itself refused when the path happens to \
782 resolve workspace-relative — that tolerance exists for anchors whose \
783 binding was later renamed — so getting it right is on you, not on a \
784 gate.\n\n",
785 primary_names
786 .iter()
787 .map(|n| format!("`{n}`"))
788 .collect::<Vec<_>>()
789 .join(", ")
790 ));
791 }
792 for source in &resolved.sources {
795 let crate::ingest::resolve::ResolvedSource::Primary(src) = source else {
796 continue;
797 };
798 let Some(prep) = src
799 .preparation
800 .as_deref()
801 .and_then(crate::preparation::lookup)
802 else {
803 continue;
804 };
805 let what = match prep.id {
806 crate::preparation::CODE_MAP => {
807 "the file's interface digest (imports, exports, signatures; comments, \
808 formatting and bodies invisible), and a `tree` anchor the code map of every \
809 scoped file under it"
810 }
811 crate::preparation::DATED_ENTRIES => {
812 "the unit's own text for a `<path>#<key>` span, the file's bytes otherwise"
813 }
814 crate::preparation::ENTITY_LOAD_BEARING => "the entity's load-bearing sections",
815 _ => prep.description,
816 };
817 block.push_str(&format!(
818 "Anchors on `{}` hash a prepared form (`{}`): {what}. Never compute `hash` \
819 yourself for this source — leave it empty (verify records it on first \
820 observation), or for a `file` or `span` anchor pass the artifact's `content` \
821 and the engine hashes the prepared form (a `tree` anchor takes no content).\n\n",
822 src.name, prep.id
823 ));
824 }
825 block
826}
827
828#[allow(clippy::too_many_arguments)]
829pub fn assemble_discovery_brief(
830 resolved: &ResolvedIngest,
831 guidance: &ResolvedGuidance,
832 process_mem: &ProcessMemInfo,
833 destination_schema: Option<&str>,
834 destination_note: Option<&str>,
835 absent_sources: &[String],
836 changed_slice_preface: &str,
837) -> String {
838 let parts = [
839 render_situation(resolved, process_mem),
840 render_intent(resolved),
841 render_goal_and_avoid(guidance),
842 render_operative_data(
843 resolved,
844 process_mem,
845 destination_schema,
846 destination_note,
847 absent_sources,
848 ),
849 render_anchor_instruction(resolved),
850 changed_slice_preface.to_string(),
851 ];
852 parts
853 .into_iter()
854 .filter(|p| !p.is_empty())
855 .collect::<Vec<_>>()
856 .join("")
857}
858
859pub fn render_one_shot_lens(
865 resolved: &ResolvedIngest,
866 destination_schema: Option<&str>,
867 destination_purpose: Option<&str>,
868) -> String {
869 let cell = |s: &str| s.replace('|', "\\|").replace('\n', " ");
870 let mut lines: Vec<String> = vec![
871 "## Mode: one-shot — lens routing".to_string(),
872 String::new(),
873 "A lens iterates entities once and writes per-destination, then exits. The agent decides \
874 per-entity which destinations to target (Routing rule). Re-runs use `memstead_update`; \
875 never duplicate."
876 .to_string(),
877 String::new(),
878 ];
879
880 lines.push("### Destination set".to_string());
881 lines.push(String::new());
882 lines.push("| Mem | Schema | Purpose |".to_string());
883 lines.push("|-------|--------|---------|".to_string());
884 let schema = destination_schema.unwrap_or("(none)");
885 let purpose = destination_purpose
886 .filter(|s| !s.is_empty())
887 .unwrap_or("(no purpose declared)");
888 lines.push(format!(
889 "| {} | {} | {} |",
890 cell(&resolved.destination_mem),
891 cell(schema),
892 cell(purpose)
893 ));
894 lines.push(String::new());
895
896 if let Some(routing) = resolved
897 .rules
898 .as_ref()
899 .and_then(|r| r.get("routing"))
900 .and_then(|v| v.as_str())
901 .map(str::trim)
902 .filter(|s| !s.is_empty())
903 {
904 lines.push("### Routing rule".to_string());
905 lines.push(String::new());
906 lines.push("```".to_string());
907 lines.push(routing.to_string());
908 lines.push("```".to_string());
909 lines.push(String::new());
910 }
911
912 lines.push("### Idempotency".to_string());
913 lines.push(String::new());
914 lines.push("- Search the destination before writing; route changes through `memstead_update` against the existing entity if present.".to_string());
915 lines.push("- Skip writes when the lifted content matches what is already there (record as `skipped: already-up-to-date`).".to_string());
916 lines.push(
917 "- Use `memstead_create` only when no entity for that concept exists yet.".to_string(),
918 );
919 lines.push(String::new());
920
921 lines.push("### End-of-run report".to_string());
922 lines.push(String::new());
923 lines.push("After every destination is processed, emit one block per destination on stdout, in Destination-set order:".to_string());
924 lines.push(String::new());
925 lines.push("```".to_string());
926 lines.push(format!("### Report: {}", resolved.name));
927 lines.push(String::new());
928 lines.push("Destination: <mem>".to_string());
929 lines.push(" created: <count>".to_string());
930 lines.push(" updated: <count>".to_string());
931 lines.push(" skipped: <count>".to_string());
932 lines.push(" failed: <count>".to_string());
933 lines.push(" failures:".to_string());
934 lines.push(" - <entity-key>: <error verbatim>".to_string());
935 lines.push(" skipped-detail:".to_string());
936 lines.push(" - <entity-key>: <one-line reason>".to_string());
937 lines.push("```".to_string());
938 lines.push(String::new());
939 lines.push("Per-destination commits are independent — partial success is the accepted failure mode. No rollback.".to_string());
940 lines.push(String::new());
941
942 let archive = resolved
943 .post_actions
944 .as_ref()
945 .and_then(|p| p.get("archive_source"))
946 .and_then(serde_json::Value::as_bool)
947 .unwrap_or(false);
948 if archive {
949 lines.push("### Archive after run".to_string());
950 lines.push(String::new());
951 lines.push("After the report has been emitted, archive the source planning mem — `post_actions.archive_source` is set on this ingest.".to_string());
952 lines.push(String::new());
953 }
954
955 format!("{}\n", lines.join("\n"))
956}
957
958#[allow(clippy::too_many_arguments)]
963pub fn assemble_one_shot_brief(
964 resolved: &ResolvedIngest,
965 guidance: &ResolvedGuidance,
966 process_mem: &ProcessMemInfo,
967 destination_schema: Option<&str>,
968 destination_note: Option<&str>,
969 absent_sources: &[String],
970 destination_purpose: Option<&str>,
971) -> String {
972 let parts = [
973 render_situation(resolved, process_mem),
974 render_intent(resolved),
975 render_goal_and_avoid(guidance),
976 render_operative_data(
977 resolved,
978 process_mem,
979 destination_schema,
980 destination_note,
981 absent_sources,
982 ),
983 render_anchor_instruction(resolved),
984 render_one_shot_lens(resolved, destination_schema, destination_purpose),
985 ];
986 parts
987 .into_iter()
988 .filter(|p| !p.is_empty())
989 .collect::<Vec<_>>()
990 .join("")
991}
992
993use super::findings::{Finding, FindingClass, FindingTarget};
1003use super::prune::{PruneDisposition, PruneProposal};
1004
1005const FINDINGS_CAP: usize = SLICE_CAP;
1007
1008pub fn render_verify_brief(resolved: &ResolvedIngest, backlog: usize) -> String {
1017 let mut lines: Vec<String> = vec![
1018 "## Verify — measure fidelity, do not mutate".to_string(),
1019 String::new(),
1020 ];
1021 lines.push(format!(
1022 "You are measuring the fidelity of `{}` — how faithfully the destination mem \
1023 `{}` still matches its source. This pass **only measures**: read the source \
1024 and the mem's anchors, judge whether the graph still holds, and record what \
1025 you find. **You** write nothing into the destination mem — the run itself \
1026 records its findings store, backfills observed anchor hashes, and writes a \
1027 `#verified` baseline, which is engine bookkeeping, not your edits.",
1028 resolved.name, resolved.destination_mem
1029 ));
1030 lines.push(String::new());
1031
1032 lines.push(
1033 "Anchors may carry a `source` naming the binding entry point that produced them — \
1034 note it when recording findings, so fidelity stays measurable per source."
1035 .to_string(),
1036 );
1037 lines.push(String::new());
1038
1039 lines.push("### Adjudicate the queued findings (capped)".to_string());
1040 lines.push(String::new());
1041 if backlog == 0 {
1042 lines.push(
1043 "No findings are queued for adjudication this pass. Spot-check the resolving \
1044 anchors and the uncovered-artifact sample the fidelity report lists, and \
1045 record any drift you observe as a finding."
1046 .to_string(),
1047 );
1048 } else {
1049 lines.push(format!(
1050 "{backlog} finding(s) are queued for adjudication. Working up to the per-run \
1051 adjudication cap (an operations knob — the remainder stays queued and \
1052 re-presents on a later pass), take each queued finding and compare the \
1053 anchored source content against what the entity records. Classify it: still \
1054 accurate, or drifted. **Record the verdict — this is a measurement, not a \
1055 repair.** A drift you record becomes a finding the sync pass repairs; you do \
1056 not fix it here."
1057 ));
1058 }
1059 lines.push(String::new());
1060
1061 lines.push("### Out of scope for verify — no mutation".to_string());
1062 lines.push(String::new());
1063 lines.push(
1064 "Verify writes **no entity content**. Do not update a \
1065 `specifies` / `constraints` section, do not create or delete an entity, do not \
1066 add or remove a relationship. When measurement shows the graph is wrong, that \
1067 is a **finding** — the sync brief (`memstead projection brief --sync`) is the \
1068 one place those repairs are made. Leave every fix to it. (The run itself does \
1069 record its findings store, backfill observed anchor hashes, and write a \
1070 `#verified` baseline — engine bookkeeping, not your edits.)"
1071 .to_string(),
1072 );
1073 lines.push(String::new());
1074
1075 format!("{}\n", lines.join("\n"))
1076}
1077
1078fn finding_target_label(target: &FindingTarget) -> String {
1080 match target {
1081 FindingTarget::Anchor { entity, artifact } => format!("`{entity}` → `{artifact}`"),
1082 FindingTarget::Artifact { artifact } => format!("`{artifact}`"),
1083 }
1084}
1085
1086fn render_findings_group(
1089 lines: &mut Vec<String>,
1090 heading: &str,
1091 guidance: &str,
1092 items: &[&Finding],
1093) {
1094 if items.is_empty() {
1095 return;
1096 }
1097 lines.push(format!("### {heading}"));
1098 lines.push(String::new());
1099 lines.push(guidance.to_string());
1100 lines.push(String::new());
1101 let shown = items.len().min(FINDINGS_CAP);
1102 for f in &items[..shown] {
1103 lines.push(format!(
1104 "- {} — {}",
1105 finding_target_label(&f.target),
1106 f.detail
1107 ));
1108 }
1109 if items.len() > shown {
1110 lines.push(format!("- …and {} more", items.len() - shown));
1111 }
1112 lines.push(String::new());
1113}
1114
1115fn render_open_findings(findings: &[Finding]) -> String {
1120 if findings.is_empty() {
1121 return String::new();
1122 }
1123 let mut lines: Vec<String> = vec![
1124 "## Open findings to repair".to_string(),
1125 String::new(),
1126 "The verify pass recorded these against the current source state. Repair them \
1127 conservatively (see the rules below); a finding you judge already correct needs \
1128 no write."
1129 .to_string(),
1130 String::new(),
1131 ];
1132
1133 let group = |class: FindingClass| -> Vec<&Finding> {
1134 findings.iter().filter(|f| f.class == class).collect()
1135 };
1136
1137 render_findings_group(
1140 &mut lines,
1141 "Drifted — the anchored content changed",
1142 "The source the entity describes moved. Update the affected section to match — \
1143 only the part that changed. If the entity is still accurate, leave it.",
1144 &group(FindingClass::Drifted),
1145 );
1146 render_findings_group(
1147 &mut lines,
1148 "Wrong — an adjudicated content mismatch",
1149 "Adjudication found the entity no longer matches its source. Correct the \
1150 mismatched section; do not rewrite what still holds.",
1151 &group(FindingClass::Wrong),
1152 );
1153 render_findings_group(
1156 &mut lines,
1157 "Unresolvable anchor — the artifact is gone",
1158 "The source artifact an anchor references is no longer present. Delete the entity \
1159 **only** if the concept is removed entirely; otherwise leave it. Concept-level \
1160 removals are a prune concern with its own never-clobber / conflict-flag rules — \
1161 do not delete on a hunch here.",
1162 &group(FindingClass::UnresolvableAnchor),
1163 );
1164 render_findings_group(
1167 &mut lines,
1168 "Uncovered — a source artifact with no entity",
1169 "An in-scope source artifact has no anchor in the mem. Create an entity for it \
1170 **only** if it is a clearly-new concept with no existing entity; otherwise \
1171 extend the entity that already owns the concept, or leave it for a discovery \
1172 build.",
1173 &group(FindingClass::Uncovered),
1174 );
1175 render_findings_group(
1177 &mut lines,
1178 "Queued for adjudication — not yet judged",
1179 "These are not adjudicated yet — that is the verify pass's job, not sync's. \
1180 **Skip them here**; they become repairable only after verify classifies them as \
1181 drifted.",
1182 &group(FindingClass::QueuedForAdjudication),
1183 );
1184
1185 format!("{}\n", lines.join("\n"))
1186}
1187
1188fn render_prune_proposals(proposals: &[PruneProposal]) -> String {
1199 if proposals.is_empty() {
1200 return String::new();
1201 }
1202 let mut lines: Vec<String> = vec![
1203 "## Prune — proposed removals (you decide; nothing is auto-deleted)".to_string(),
1204 String::new(),
1205 "The source removed the artifacts these entities describe. Each item below is a \
1206 **proposal**: prune writes nothing — you enact (or reject) the removal through the \
1207 normal MCP mutation surface. An `authored` entity is never proposed here; a `derived` \
1208 entity is flagged, never proposed for deletion."
1209 .to_string(),
1210 String::new(),
1211 ];
1212
1213 let group = |d: PruneDisposition| -> Vec<&PruneProposal> {
1214 proposals.iter().filter(|p| p.disposition == d).collect()
1215 };
1216
1217 let clean = group(PruneDisposition::CleanDelete);
1220 if !clean.is_empty() {
1221 lines.push("### Clean delete — never-clobber three-way merge is clean".to_string());
1222 lines.push(String::new());
1223 lines.push(
1224 "The source base leg was retrievable and the three-way merge found no model-side \
1225 divergence, so removal is safe. **Confirm, then delete via the mutation surface** — \
1226 this is still your call, not an auto-delete."
1227 .to_string(),
1228 );
1229 lines.push(String::new());
1230 let shown = clean.len().min(FINDINGS_CAP);
1231 for p in &clean[..shown] {
1232 lines.push(format!(
1233 "- `{}` — source artifact(s) gone: {}",
1234 p.entity,
1235 artifact_list(&p.artifacts)
1236 ));
1237 }
1238 if clean.len() > shown {
1239 lines.push(format!("- …and {} more", clean.len() - shown));
1240 }
1241 lines.push(String::new());
1242 }
1243
1244 let conflict = group(PruneDisposition::ConflictFlag);
1246 if !conflict.is_empty() {
1247 lines.push("### Conflict-flag — decide, never overwrite a model-side edit".to_string());
1248 lines.push(String::new());
1249 lines.push(
1250 "No retrievable base leg to merge against (a non-git source, or an anchor with no \
1251 pinned version). **Both sides are shown — decide deliberately.** If the concept is \
1252 truly gone, delete via the mutation surface; if the model side was edited on \
1253 purpose, keep it. Prune never overwrites a model-side edit for you."
1254 .to_string(),
1255 );
1256 lines.push(String::new());
1257 let shown = conflict.len().min(FINDINGS_CAP);
1258 for p in &conflict[..shown] {
1259 lines.push(format!(
1260 "- `{}` — **source side:** artifact(s) gone: {}; **model side:** the entity is \
1261 still present (may carry edits) — you decide.",
1262 p.entity,
1263 artifact_list(&p.artifacts)
1264 ));
1265 }
1266 if conflict.len() > shown {
1267 lines.push(format!("- …and {} more", conflict.len() - shown));
1268 }
1269 lines.push(String::new());
1270 }
1271
1272 let derived = group(PruneDisposition::DerivedFlagged);
1274 if !derived.is_empty() {
1275 lines.push("### Derived — flagged, NOT proposed for deletion".to_string());
1276 lines.push(String::new());
1277 lines.push(
1278 "These entities were **derived** from other inputs. A derived entity is flagged, \
1279 never auto-proposed for deletion — its inputs may still hold even though one source \
1280 artifact vanished. Re-examine the inputs before removing anything."
1281 .to_string(),
1282 );
1283 lines.push(String::new());
1284 let shown = derived.len().min(FINDINGS_CAP);
1285 for p in &derived[..shown] {
1286 let inputs = if p.derived_inputs.is_empty() {
1287 "(no recorded inputs)".to_string()
1288 } else {
1289 artifact_list(&p.derived_inputs)
1290 };
1291 lines.push(format!(
1292 "- `{}` — derived from: {}; source artifact(s) gone: {}.",
1293 p.entity,
1294 inputs,
1295 artifact_list(&p.artifacts)
1296 ));
1297 }
1298 if derived.len() > shown {
1299 lines.push(format!("- …and {} more", derived.len() - shown));
1300 }
1301 lines.push(String::new());
1302 }
1303
1304 format!("{}\n", lines.join("\n"))
1305}
1306
1307fn artifact_list(artifacts: &[String]) -> String {
1309 if artifacts.is_empty() {
1310 return "(none)".to_string();
1311 }
1312 artifacts
1313 .iter()
1314 .map(|a| format!("`{a}`"))
1315 .collect::<Vec<_>>()
1316 .join(", ")
1317}
1318
1319fn render_sync_situation(resolved: &ResolvedIngest) -> String {
1322 format!(
1323 "## Sync — repair the graph to match the source\n\n\
1324 You are running the sync pass for `{}`. Sync is the graph's **sole maintenance \
1325 writer**: the only place the destination mem `{}` is repaired to match its \
1326 source. Two inputs steer this pass — the source changes since the last sync, and \
1327 the open verify findings — both below. Work them: update, create, relate, and \
1328 (rarely) delete entities so the graph again matches the source.\n\n\
1329 Every mutation routes through the normal MCP mutation surface, and the engine \
1330 commits each one **per-mutation** to the mem's own gitdir. You **stage nothing \
1331 and commit nothing yourself** — not the graph, not the code. Sync commits \
1332 nothing.\n\n",
1333 resolved.name, resolved.destination_mem
1334 )
1335}
1336
1337fn render_adopt_framing(resolved: &ResolvedIngest) -> String {
1341 format!(
1342 "## First sync — adopting `{}`\n\n\
1343 This mem predates its binding: it has no anchors and no prior sync baseline, so \
1344 **0% anchored is expected — this is onboarding, not a failure.** Do not read it \
1345 as drift or a red verdict. There is no cursor to diff against, so the baseline is \
1346 the **current** source HEAD — do **not** replay the whole history; treat the \
1347 current source state as the starting point, and this is a **first sync**.\n\n\
1348 **Backfill path:** run `memstead projection verify {}` to enumerate the in-scope \
1349 source artifacts that carry no entity yet, then cover the clearly-new concepts \
1350 among them through the normal MCP mutation surface — the same conservative rules \
1351 below apply. Backfilling is incremental: a partial pass is fine, and the next \
1352 sync continues where you left off.\n\n",
1353 resolved.destination_mem, resolved.name
1354 )
1355}
1356
1357fn render_stale_claim_search(resolved: &ResolvedIngest) -> String {
1369 format!(
1370 "## Stale claims beyond the slice — search, then judge\n\n\
1371 A changed fact can be claimed by an entity whose anchors are all outside the \
1372 changed slice — anchor-steered repairs alone would leave that claim standing \
1373 falsified. Extract the **changed facts** from the changed artifacts above: \
1374 renamed identifiers, changed values or defaults, changed behaviors (e.g. an \
1375 exit code, a flag's meaning), removed or moved concepts. For each changed \
1376 fact, search the destination mem `{}` for claims about it (`memstead_search` \
1377 and its variants — try the new name, the old name/value, and close synonyms), \
1378 and judge **only** the entities whose claims actually mention a changed fact: \
1379 repair a claim the change falsifies, leave everything else untouched.\n\n\
1380 This is a bounded fact-search, not a live-verify of every entity and not a \
1381 rewrite license. If the changes carry no factual claims (formatting, \
1382 comments, cosmetic moves), the fact set is empty and this step ends with no \
1383 search and no edits.\n\n",
1384 resolved.destination_mem
1385 )
1386}
1387
1388fn render_sync_conservatism() -> String {
1392 let lines: Vec<&str> = vec![
1393 "## How to repair — be conservative",
1394 "",
1395 "Repair only what the source changes and the findings above actually justify:",
1396 "",
1397 "- **Unsure whether an entity is affected — skip it.** A missed update is a later \
1399 finding; a wrong rewrite is damage.",
1400 "- **Do not create a new entity unless the change clearly introduces a new concept \
1401 with no existing entity.** Prefer updating the entity that already owns the \
1402 concept.",
1403 "- **Do not delete an entity unless the change removes the concept entirely.** \
1404 Deletions a prune pass surfaces follow prune's own never-clobber / conflict-flag \
1405 rules — never delete on a hunch here.",
1406 "- **Never rewrite a section that has not changed** — touch only the part the \
1407 change or finding actually affects.",
1408 "- **No speculative edges — add only relationships the diff literally introduces** \
1409 (a new `use` / `import` / dependency you can point at in the change).",
1410 "- **A dropped dependency FLAGS, it does not auto-remove.** If the change removes an \
1412 import or dependency, leave the matching edge intact and note it for a later \
1413 audit — removals are ambiguous (temporary refactor vs. permanent cut), and a \
1414 stale edge is less damaging than an erased real one. **Edge removal is out of \
1415 scope for sync.**",
1416 "- **Rationale is reasoning, not a changelog.** When you record why a change was \
1418 made, append the *reasoning* (why this approach, which trade-offs) — never \
1419 `[commit <hash>]` log-style entries.",
1420 "",
1421 ];
1422
1423 format!("{}\n", lines.join("\n"))
1424}
1425
1426pub fn render_sync_brief(
1453 resolved: &ResolvedIngest,
1454 cursor: &SourceCursor,
1455 findings: &[Finding],
1456 prune: &[PruneProposal],
1457 adopt: bool,
1458) -> String {
1459 let preface = render_changed_slice(cursor);
1460 let open_findings = render_open_findings(findings);
1461 let prune_block = render_prune_proposals(prune);
1462 let has_work =
1463 adopt || !preface.is_empty() || !open_findings.is_empty() || !prune_block.is_empty();
1464
1465 let mut parts: Vec<String> = vec![render_sync_situation(resolved)];
1466
1467 if !has_work {
1468 parts.push(
1469 "## Nothing to sync\n\nThe source has not moved since the last sync, no \
1470 verify findings are open, and no prune proposals stand. There is nothing to \
1471 repair this pass — reporting \"no changes\" is a valid outcome.\n\n"
1472 .to_string(),
1473 );
1474 return parts
1475 .into_iter()
1476 .filter(|p| !p.is_empty())
1477 .collect::<Vec<_>>()
1478 .join("");
1479 }
1480
1481 if adopt {
1482 parts.push(render_adopt_framing(resolved));
1483 }
1484 parts.push(preface);
1485 if cursor.any_changes {
1489 parts.push(render_stale_claim_search(resolved));
1490 }
1491 parts.push(open_findings);
1492 parts.push(prune_block);
1493 parts.push(render_anchor_instruction(resolved));
1494 parts.push(render_sync_conservatism());
1495
1496 parts
1497 .into_iter()
1498 .filter(|p| !p.is_empty())
1499 .collect::<Vec<_>>()
1500 .join("")
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505 use super::*;
1506 use crate::ingest::resolve::Source;
1507 use crate::pipeline::{IngestTrigger, PatternEntry};
1508
1509 fn guidance(goal: Option<&str>, avoid: Option<&str>) -> ResolvedGuidance {
1510 ResolvedGuidance {
1511 goal: goal.map(str::to_string),
1512 avoid: avoid.map(str::to_string),
1513 }
1514 }
1515
1516 #[test]
1519 fn renders_goal_and_avoid_blocks() {
1520 let out = render_goal_and_avoid(&guidance(Some(" build coverage "), Some("no stubs")));
1521 assert_eq!(
1522 out,
1523 "## Goal\n\nbuild coverage\n\n## Failure modes to avoid\n\nno stubs\n\n"
1524 );
1525 }
1526
1527 #[test]
1529 fn renders_goal_only() {
1530 assert_eq!(
1531 render_goal_and_avoid(&guidance(Some("build coverage"), None)),
1532 "## Goal\n\nbuild coverage\n\n"
1533 );
1534 }
1535
1536 #[test]
1538 fn renders_avoid_only() {
1539 assert_eq!(
1540 render_goal_and_avoid(&guidance(None, Some("no stubs"))),
1541 "## Failure modes to avoid\n\nno stubs\n\n"
1542 );
1543 }
1544
1545 #[test]
1548 fn empty_guidance_yields_a_newline() {
1549 assert_eq!(render_goal_and_avoid(&guidance(None, None)), "\n");
1550 assert_eq!(render_goal_and_avoid(&guidance(Some(" "), None)), "\n");
1552 }
1553
1554 fn primary(medium_type: MediumType, scope: Vec<PatternEntry>) -> ResolvedSource {
1555 ResolvedSource::Primary(Source {
1556 name: "f".to_string(),
1557 medium_type,
1558 pointer: "../src".to_string(),
1559 change_detection: None,
1560 scope,
1561 engagement: None,
1562 preparation: None,
1563 })
1564 }
1565
1566 fn resolved(name: &str, intent: Option<&str>, sources: Vec<ResolvedSource>) -> ResolvedIngest {
1567 ResolvedIngest {
1568 name: name.to_string(),
1569 mode: BuildMode::Discovery,
1570 trigger: IngestTrigger::Loop,
1571 batch_size: 20,
1572 deny_paths: vec![],
1573 projection_ref: format!("{name}/p"),
1574 projection_mem: name.to_string(),
1575 projection_name: "p".to_string(),
1576 intent: intent.map(str::to_string),
1577 sources,
1578 destination_mem: name.to_string(),
1579 rules: None,
1580 post_actions: None,
1581 }
1582 }
1583
1584 fn process_present(name: &str) -> ProcessMemInfo {
1585 ProcessMemInfo {
1586 present: true,
1587 skipped: false,
1588 notice: None,
1589 leaf_name: name.to_string(),
1590 mem_label: format!("ingest/{name}"),
1591 }
1592 }
1593
1594 fn allow(path: &str) -> PatternEntry {
1595 PatternEntry {
1596 path: path.to_string(),
1597 mode: PatternMode::Allow,
1598 }
1599 }
1600
1601 fn deny(path: &str) -> PatternEntry {
1602 PatternEntry {
1603 path: path.to_string(),
1604 mode: PatternMode::Deny,
1605 }
1606 }
1607
1608 #[test]
1610 fn renders_intent() {
1611 let r = resolved("macos", Some(" Swift app source. "), vec![]);
1612 assert_eq!(
1613 render_intent(&r),
1614 "## About the source\n\nSwift app source.\n\n"
1615 );
1616 let none = resolved("macos", None, vec![]);
1617 assert_eq!(render_intent(&none), "");
1618 }
1619
1620 #[test]
1623 fn renders_situation_with_present_process_mem() {
1624 let r = resolved("macos", None, vec![]);
1625 let out = render_situation(&r, &process_present("macos"));
1626 assert!(out.starts_with("## Situation\n\nYou are running one iteration of `macos` (discovery mode) inside a loop."));
1627 assert!(out.contains("Mutating the destination is this run's mandate:"));
1628 assert!(out.contains("The `PreCompact` hook fires near the limit"));
1629 assert!(out.contains("A paired process mem `ingest/macos` (schema `ingest@0.5.0`) carries destination-quality debt"));
1630 assert!(
1631 out.ends_with("write rules.\n\n"),
1632 "block ends in a blank line"
1633 );
1634 }
1635
1636 #[test]
1639 fn situation_process_mem_branches() {
1640 let mut r = resolved("os", None, vec![]);
1641 r.mode = BuildMode::OneShot;
1642 let skipped = ProcessMemInfo {
1643 present: false,
1644 skipped: true,
1645 notice: None,
1646 leaf_name: "os".to_string(),
1647 mem_label: "ingest/os".to_string(),
1648 };
1649 assert!(
1650 render_situation(&r, &skipped)
1651 .contains("No process mem is paired with this ingest (mode=one-shot;")
1652 );
1653
1654 let failed = ProcessMemInfo {
1655 present: false,
1656 skipped: false,
1657 notice: Some("engine offline".to_string()),
1658 leaf_name: "os".to_string(),
1659 mem_label: "ingest/os".to_string(),
1660 };
1661 let out = render_situation(&resolved("os", None, vec![]), &failed);
1662 assert!(out.contains("could not be auto-created — engine offline."));
1663 assert!(out.contains("memstead mem init os --org-path ingest --schema ingest@0.5.0"));
1664 }
1665
1666 #[test]
1670 fn renders_operative_data_full() {
1671 let r = resolved(
1672 "macos",
1673 None,
1674 vec![
1675 primary(
1676 MediumType::Codebase,
1677 vec![allow("src/**/*.swift"), deny("src/gen/**")],
1678 ),
1679 ResolvedSource::Reference {
1680 mem: "engine".to_string(),
1681 },
1682 ],
1683 );
1684 let out = render_operative_data(
1685 &r,
1686 &process_present("macos"),
1687 Some("macos-code@0.1.0"),
1688 None,
1689 &[],
1690 );
1691 let expected = "\
1692## Operative data
1693
1694### Sources
1695
1696- **f** (codebase, primary) — `../src`
1697 - Paths: src/**/*.swift
1698 - Ignore: src/gen/**
1699- **graph** (reference) — mem: engine
1700
1701Sources tagged `(reference)` are read-only context for cross-mem edges — search them, never write into them. Only `(primary)` sources are ingested into the destination.
1702
1703**Cross-mem references:** consult `memstead_search mem=engine` before authoring cross-mem edges. The target entity must exist — a wiki-link or relationship to a missing target either auto-stubs (silent) or fails authorization (`CROSS_MEM_RELATION`).
1704
1705### Destination
1706
1707- **macos** — schema: `macos-code@0.1.0`
1708
1709### Paired process mem
1710
1711- **ingest/macos** — schema: `ingest@0.5.0`. Inspect via `memstead_overview` / `memstead_search mem=macos`.
1712\n";
1713 assert_eq!(out, expected);
1714 }
1715
1716 #[test]
1719 fn renders_operative_data_minimal() {
1720 let r = resolved("g", None, vec![primary(MediumType::Filesystem, vec![])]);
1721 let skipped = ProcessMemInfo {
1722 present: false,
1723 skipped: true,
1724 notice: None,
1725 leaf_name: "g".to_string(),
1726 mem_label: "ingest/g".to_string(),
1727 };
1728 let out = render_operative_data(&r, &skipped, None, Some("**absent** — probe"), &[]);
1729 assert!(out.contains("- **f** (filesystem, primary) — `"));
1732 assert!(!out.contains("Cross-mem references"), "no reference note");
1733 assert!(out.contains("### Destination\n\n- **g**\n"));
1734 assert!(
1737 out.contains("**absent** — probe"),
1738 "the caller's destination note must be rendered: {out}",
1739 );
1740 assert!(
1741 !out.contains("Paired process mem"),
1742 "skipped process mem omitted"
1743 );
1744 }
1745
1746 #[test]
1749 fn assembles_discovery_brief() {
1750 let r = resolved(
1751 "macos",
1752 Some("Swift source."),
1753 vec![primary(MediumType::Codebase, vec![allow("src/**")])],
1754 );
1755 let g = guidance(Some("build coverage"), None);
1756 let pm = process_present("macos");
1757 let brief = assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], "");
1758
1759 let sit = brief.find("## Situation").unwrap();
1761 let src = brief.find("## About the source").unwrap();
1762 let goal = brief.find("## Goal").unwrap();
1763 let op = brief.find("## Operative data").unwrap();
1764 let anchors = brief.find("## Provenance — anchor your writes").unwrap();
1765 assert!(
1766 sit < src && src < goal && goal < op && op < anchors,
1767 "blocks in brief order"
1768 );
1769 assert!(
1770 !brief.contains("## Source changes"),
1771 "no changed-slice block when preface empty"
1772 );
1773
1774 let with_slice = assemble_discovery_brief(
1776 &r,
1777 &g,
1778 &pm,
1779 Some("s@1"),
1780 None,
1781 &[],
1782 "## Source changes\n\n…\n\n",
1783 );
1784 assert!(with_slice.ends_with("## Source changes\n\n…\n\n"));
1785 }
1786
1787 fn slice(deleted: &[&str], modified: &[&str], added: &[&str]) -> Slice {
1788 Slice {
1789 deleted: deleted.iter().map(|s| s.to_string()).collect(),
1790 modified: modified.iter().map(|s| s.to_string()).collect(),
1791 added: added.iter().map(|s| s.to_string()).collect(),
1792 }
1793 }
1794
1795 fn cmd(key: &str, token: &str) -> SyncCommand {
1796 SyncCommand {
1797 key: key.to_string(),
1798 token: token.to_string(),
1799 }
1800 }
1801
1802 fn note(source: &str, reason: NoSignalReason) -> NoSignalNote {
1803 NoSignalNote {
1804 medium_type: None,
1805 source: source.to_string(),
1806 reason,
1807 }
1808 }
1809
1810 #[test]
1814 fn anchor_instruction_names_prepared_form_sources() {
1815 let mut resolved = resolved("home", None, vec![primary(MediumType::Codebase, vec![])]);
1816 let plain = render_anchor_instruction(&resolved);
1817 assert!(!plain.contains("hash a prepared form"));
1818 if let Some(ResolvedSource::Primary(src)) = resolved.sources.first_mut() {
1819 src.preparation = Some(crate::preparation::CODE_MAP.to_string());
1820 }
1821 let prepared = render_anchor_instruction(&resolved);
1822 assert!(
1823 prepared.contains("hash a prepared form (`code-map`)"),
1824 "{prepared}"
1825 );
1826 assert!(prepared.contains("interface digest"));
1827 assert!(prepared.contains("for a `file` or `span` anchor pass the artifact's `content`"));
1828 assert!(prepared.contains("a `tree` anchor takes no content"));
1829 }
1830
1831 #[test]
1836 fn changed_slice_renders_delivery_sequences_in_order() {
1837 use crate::preparation::UnitChange;
1838 let unit = |id: &str, order: &str, change: UnitChange, disposed: bool| DeliveredUnit {
1839 id: id.to_string(),
1840 order_key: order.to_string(),
1841 change,
1842 disposed,
1843 };
1844 let units = vec![
1845 unit(
1846 "log/b.md#2026-08-20T00:00:00",
1847 "2026-08-20T00:00:00",
1848 UnitChange::Added,
1849 true,
1850 ),
1851 unit(
1852 "log/a.md#2026-08-21T00:00:00",
1853 "2026-08-21T00:00:00",
1854 UnitChange::Deleted,
1855 false,
1856 ),
1857 unit(
1858 "log/b.md#2026-08-22T00:00:00",
1859 "2026-08-22T00:00:00",
1860 UnitChange::Modified,
1861 false,
1862 ),
1863 unit(
1864 "log/a.md#2026-08-23T00:00:00",
1865 "2026-08-23T00:00:00",
1866 UnitChange::Added,
1867 false,
1868 ),
1869 ];
1870 let cursor = SourceCursor {
1871 union: slice(
1873 &["log/a.md#2026-08-21T00:00:00"],
1874 &["log/b.md#2026-08-22T00:00:00"],
1875 &[
1876 "log/a.md#2026-08-23T00:00:00",
1877 "log/b.md#2026-08-20T00:00:00",
1878 "other/x.rs",
1879 ],
1880 ),
1881 write_commands: vec![],
1882 reseed: vec![],
1883 no_signal: vec![],
1884 any_changes: true,
1885 degraded: false,
1886 dead_denies: vec![],
1887 dest_mem: "home".to_string(),
1888 binding_id: "home/log".to_string(),
1889 delivery: vec![DeliverySequence {
1890 source: "log".to_string(),
1891 preparation: "dated-entries".to_string(),
1892 first_run: false,
1893 degraded: true,
1894 batch: 2,
1895 units,
1896 }],
1897 };
1898 let out = render_changed_slice(&cursor);
1899 assert!(
1900 out.contains("### Delivery sequence: `log` (`dated-entries`)"),
1901 "{out}"
1902 );
1903 assert!(out.contains("The units that changed since the last pass"));
1904 assert!(out.contains("No baseline content was retrievable"));
1905 let listed: Vec<&str> = out
1906 .lines()
1907 .filter(|l| l.starts_with(|c: char| c.is_ascii_digit()))
1908 .collect();
1909 assert_eq!(
1910 listed,
1911 vec![
1912 "2. `log/a.md#2026-08-21T00:00:00` (deleted)",
1913 "3. `log/b.md#2026-08-22T00:00:00` (changed)",
1914 ],
1915 "positions are total-order positions; the disposed first unit is skipped"
1916 );
1917 assert!(out.contains("…and 1 more, presented in order once these are disposed"));
1918 assert!(out.contains("1 unit of this sequence already disposed"));
1919 assert!(out.contains("**Added:**\n- `other/x.rs`\n"), "{out}");
1921 assert!(!out.contains("**Modified:**"));
1922 assert!(!out.contains("**Deleted:**"));
1923 }
1924
1925 #[test]
1927 fn changed_slice_empty_when_nothing_moved() {
1928 let cursor = SourceCursor {
1929 union: slice(&[], &[], &[]),
1930 write_commands: vec![],
1931 reseed: vec![],
1932 no_signal: vec![],
1933 any_changes: false,
1934 degraded: false,
1935 dead_denies: vec![],
1936 dest_mem: "engine".to_string(),
1937 binding_id: "engine/graph".to_string(),
1938 delivery: vec![],
1939 };
1940 assert_eq!(render_changed_slice(&cursor), "");
1941 }
1942
1943 #[test]
1947 fn changed_slice_renders_dead_deny_warning() {
1948 let cursor = SourceCursor {
1949 union: slice(&[], &[], &[]),
1950 write_commands: vec![],
1951 reseed: vec![],
1952 no_signal: vec![],
1953 any_changes: false,
1954 degraded: false,
1955 dead_denies: vec!["dev".to_string(), "typo/**".to_string()],
1956 dest_mem: "engine".to_string(),
1957 binding_id: "engine/graph".to_string(),
1958 delivery: vec![],
1959 };
1960 let out = render_changed_slice(&cursor);
1961 assert!(out.contains("deny_paths` entries match nothing"));
1962 assert!(out.contains("- `dev`"));
1963 assert!(out.contains("- `typo/**`"));
1964 }
1965
1966 #[test]
1970 fn changed_slice_renders_slice_and_recording() {
1971 let cursor = SourceCursor {
1972 union: slice(&["a.rs"], &["b.rs"], &[]),
1973 write_commands: vec![cmd("engine-graph/source", "HEADSHA")],
1974 reseed: vec![],
1975 no_signal: vec![],
1976 any_changes: true,
1977 degraded: false,
1978 dead_denies: vec![],
1979 dest_mem: "engine".to_string(),
1980 binding_id: "engine/graph".to_string(),
1981 delivery: vec![],
1982 };
1983 let expected_lines = [
1984 "## Source changes since the last sync\n",
1985 "The source moved since this graph was last synced. Steer this pass at these changed artifacts **first** — they are where the graph is most likely now wrong.\n",
1986 "**Deleted:**",
1987 "- `a.rs`",
1988 "",
1989 "**Modified:**",
1990 "- `b.rs`",
1991 "",
1992 "### Recording your dispositions (do this LAST)\n",
1993 "Only after you have worked the changed artifacts above — and only for the artifacts you actually judged — record a disposition for each, so the next pass targets just what changes next. This advance is resumable and non-stalling: a partial pass is honored, and if the source moves mid-pass the remaining slice re-presents (remaining + new) without losing your recorded work.\n",
1994 "Anchored work disposes itself: at advance time, every listed artifact that an anchor in the destination mem references is marked `worked` automatically (an explicit disposition you pass wins over the auto-mark). Supply dispositions only for the residue — artifacts you skipped, judged out of intent, or worked without anchors. The gate accepts only artifact ids listed above — an unknown id refuses the whole call. When every artifact is disposed, the sync baseline advances automatically. Run:\n",
1995 "```sh",
1996 r#"memstead projection advance engine/graph --dispositions '{"<artifact>": "<disposition>", ...}'"#,
1997 "```",
1998 "If you were interrupted before finishing, that is fine — your recorded dispositions persist, and the next run re-presents only what is left.\n",
1999 ];
2000 assert_eq!(
2001 render_changed_slice(&cursor),
2002 format!("{}\n", expected_lines.join("\n"))
2003 );
2004 }
2005
2006 #[test]
2009 fn changed_slice_reseed_only() {
2010 let cursor = SourceCursor {
2011 union: slice(&[], &[], &[]),
2012 write_commands: vec![],
2013 reseed: vec![cmd("ing/f", "TOK")],
2014 no_signal: vec![],
2015 any_changes: false,
2016 degraded: false,
2017 dead_denies: vec![],
2018 dest_mem: "d".to_string(),
2019 binding_id: "d/p".to_string(),
2020 delivery: vec![],
2021 };
2022 let out = render_changed_slice(&cursor);
2023 assert!(out.starts_with("## Source changes since the last sync\n\n"));
2024 assert!(out.contains(
2025 "No usable sync baseline exists for `ing/f` — none was recorded, or the recorded one is not a commit of the source's repo (foreign or garbage-collected). Treating the current source state as the baseline. No priority slice from it this pass; proceed as usual."
2026 ));
2027 assert!(out.contains(
2028 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2029 ));
2030 assert!(
2031 !out.contains("The source moved"),
2032 "no 'moved' copy when only reseeding"
2033 );
2034 }
2035
2036 #[test]
2042 fn changed_slice_renders_no_signal_reasons_distinguishably() {
2043 let cursor = SourceCursor {
2044 union: slice(&[], &[], &[]),
2045 write_commands: vec![],
2046 reseed: vec![],
2047 no_signal: vec![
2048 note("code-facet", NoSignalReason::Unscoped),
2049 note("plan-facet", NoSignalReason::DetectionNone),
2050 note("git-facet", NoSignalReason::GitUnavailable),
2051 note("ref-mem", NoSignalReason::GraphSnapshotMissing),
2052 ],
2053 any_changes: false,
2054 degraded: false,
2055 dead_denies: vec![],
2056 dest_mem: "d".to_string(),
2057 binding_id: "d/p".to_string(),
2058 delivery: vec![],
2059 };
2060 let out = render_changed_slice(&cursor);
2061 assert!(out.starts_with("## Source changes since the last sync\n"));
2062 assert!(out.contains("Some sources produced **no change signal**"));
2063 assert!(out.contains("- `code-facet`: unscoped facet (no allow patterns)"));
2065 assert!(
2066 out.contains("- `plan-facet`: `signal:none`"),
2067 "detection-none renders the literal signal:none state"
2068 );
2069 assert!(out.contains("- `git-facet`: git signal unavailable"));
2070 assert!(out.contains("- `ref-mem`: graph snapshot missing"));
2071 let texts = [
2073 no_signal_reason_text(NoSignalReason::Unscoped, None),
2074 no_signal_reason_text(NoSignalReason::DetectionNone, None),
2075 no_signal_reason_text(NoSignalReason::GitUnavailable, None),
2076 no_signal_reason_text(NoSignalReason::GraphSnapshotMissing, None),
2077 ];
2078 for (i, a) in texts.iter().enumerate() {
2079 for b in &texts[i + 1..] {
2080 assert_ne!(a, b, "each no-signal reason must render distinctly");
2081 }
2082 }
2083 assert!(!out.contains("### Recording your dispositions"));
2085 assert!(!out.contains("The source moved"));
2086 }
2087
2088 #[test]
2092 fn changed_slice_mixes_changes_and_no_signal() {
2093 let cursor = SourceCursor {
2094 union: slice(&[], &["b.rs"], &[]),
2095 write_commands: vec![cmd("ing/f", "HEAD")],
2096 reseed: vec![],
2097 no_signal: vec![note("other", NoSignalReason::Unscoped)],
2098 any_changes: true,
2099 degraded: false,
2100 dead_denies: vec![],
2101 dest_mem: "d".to_string(),
2102 binding_id: "d/p".to_string(),
2103 delivery: vec![],
2104 };
2105 let out = render_changed_slice(&cursor);
2106 assert!(out.contains("The source moved"));
2107 assert!(out.contains("**Modified:**"));
2108 assert!(out.contains("- `other`: unscoped facet"));
2109 assert!(out.contains("### Recording your dispositions"));
2110 assert!(out.contains(
2111 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2112 ));
2113 }
2114
2115 #[test]
2118 fn renders_one_shot_lens_block() {
2119 let mut r = resolved("os", Some("plan source"), vec![]);
2120 r.rules = Some(serde_json::json!({ "routing": "route each entity to its spec" }));
2121 r.post_actions = Some(serde_json::json!({ "archive_source": true }));
2122
2123 let out = render_one_shot_lens(&r, Some("planning@0.1.0"), Some("the plan graph"));
2124 assert!(out.starts_with("## Mode: one-shot — lens routing\n\n"));
2125 assert!(out.contains(
2126 "### Destination set\n\n| Mem | Schema | Purpose |\n|-------|--------|---------|\n| os | planning@0.1.0 | the plan graph |\n"
2127 ));
2128 assert!(out.contains("### Routing rule\n\n```\nroute each entity to its spec\n```\n"));
2129 assert!(out.contains("### Idempotency"));
2130 assert!(out.contains("### Report: os"));
2131 assert!(out.contains("### Archive after run"));
2132 assert!(out.ends_with("is set on this ingest.\n\n"));
2133
2134 let bare = resolved("os", None, vec![]);
2137 let out2 = render_one_shot_lens(&bare, None, None);
2138 assert!(out2.contains("| os | (none) | (no purpose declared) |"));
2139 assert!(!out2.contains("### Routing rule"));
2140 assert!(!out2.contains("### Archive after run"));
2141 assert!(out2.contains("### End-of-run report"));
2142 }
2143
2144 #[test]
2147 fn assembles_one_shot_brief() {
2148 let mut r = resolved(
2149 "os",
2150 Some("src"),
2151 vec![primary(MediumType::Filesystem, vec![])],
2152 );
2153 r.mode = BuildMode::OneShot;
2154 let g = guidance(Some("goal"), None);
2155 let skipped = ProcessMemInfo {
2156 present: false,
2157 skipped: true,
2158 notice: None,
2159 leaf_name: "os".to_string(),
2160 mem_label: "ingest/os".to_string(),
2161 };
2162 let brief =
2163 assemble_one_shot_brief(&r, &g, &skipped, Some("s@1"), None, &[], Some("purpose"));
2164 assert!(brief.contains("(one-shot mode)"));
2165 assert!(brief.contains("No process mem is paired with this ingest (mode=one-shot;"));
2166 assert!(brief.contains("## Mode: one-shot — lens routing"));
2167 assert!(
2168 brief.contains("## Provenance — anchor your writes"),
2169 "one-shot carries the anchor instruction"
2170 );
2171 assert!(
2172 !brief.contains("## Source changes"),
2173 "one-shot has no changed-slice"
2174 );
2175 }
2176
2177 #[test]
2181 fn changed_slice_caps_and_degrades_and_quotes() {
2182 let many: Vec<String> = (0..SLICE_CAP + 3).map(|i| format!("f{i}.rs")).collect();
2183 let cursor = SourceCursor {
2184 union: Slice {
2185 deleted: vec![],
2186 modified: vec![],
2187 added: many,
2188 },
2189 write_commands: vec![cmd("ing/f", r#"{"v":1,"aggregate":"x"}"#)],
2190 reseed: vec![],
2191 no_signal: vec![],
2192 any_changes: true,
2193 degraded: true,
2194 dead_denies: vec![],
2195 dest_mem: "d".to_string(),
2196 binding_id: "d/p".to_string(),
2197 delivery: vec![],
2198 };
2199 let out = render_changed_slice(&cursor);
2200 assert!(out.contains(&format!("- …and {} more added", 3)));
2201 assert!(out.contains("Precise change history for one or more facets was unavailable"));
2202 assert!(out.contains(
2205 r#"memstead projection advance d/p --dispositions '{"<artifact>": "<disposition>", ...}'"#
2206 ));
2207 }
2208
2209 fn finding(class: FindingClass, target: FindingTarget, detail: &str) -> Finding {
2212 Finding {
2213 key: crate::ingest::findings::FindingKey {
2214 binding_hash: "h".to_string(),
2215 source_head: "s".to_string(),
2216 },
2217 facet: "src".to_string(),
2218 target,
2219 class,
2220 detail: detail.to_string(),
2221 created_at: "1".to_string(),
2222 }
2223 }
2224
2225 fn anchor_target(entity: &str, artifact: &str) -> FindingTarget {
2226 FindingTarget::Anchor {
2227 entity: entity.to_string(),
2228 artifact: artifact.to_string(),
2229 }
2230 }
2231
2232 fn artifact_target(artifact: &str) -> FindingTarget {
2233 FindingTarget::Artifact {
2234 artifact: artifact.to_string(),
2235 }
2236 }
2237
2238 fn empty_cursor() -> SourceCursor {
2239 SourceCursor {
2240 union: slice(&[], &[], &[]),
2241 write_commands: vec![],
2242 reseed: vec![],
2243 no_signal: vec![],
2244 any_changes: false,
2245 degraded: false,
2246 dead_denies: vec![],
2247 dest_mem: "engine".to_string(),
2248 binding_id: "engine/graph".to_string(),
2249 delivery: vec![],
2250 }
2251 }
2252
2253 #[test]
2257 fn verify_brief_measures_and_refuses_mutation() {
2258 let r = resolved("engine", None, vec![]);
2259 let out = render_verify_brief(&r, 3);
2260 assert!(out.starts_with("## Verify — measure fidelity, do not mutate"));
2262 assert!(out.contains("3 finding(s) are queued for adjudication"));
2263 assert!(out.contains("per-run adjudication cap"));
2264 assert!(out.contains("this is a measurement, not a repair"));
2265 assert!(out.contains("Verify writes **no entity content**"));
2278 assert!(out.contains("`#verified` baseline"));
2279 assert!(out.contains("memstead projection brief --sync"));
2280 assert!(out.contains("do not create or delete an entity"));
2283 assert!(!out.contains("via `memstead_create`"));
2284 assert!(!out.contains("Run `memstead_update`"));
2285
2286 let zero = render_verify_brief(&r, 0);
2288 assert!(zero.contains("No findings are queued for adjudication"));
2289 assert!(zero.contains("record any drift you observe as a finding"));
2290 assert!(zero.contains("Verify writes **no entity content**"));
2291 }
2292
2293 #[test]
2297 fn sync_brief_carries_both_cursor_and_findings() {
2298 let r = resolved("engine", None, vec![]);
2299 let cursor = SourceCursor {
2300 union: slice(&["gone.rs"], &["moved.rs"], &[]),
2301 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2302 reseed: vec![],
2303 no_signal: vec![],
2304 any_changes: true,
2305 degraded: false,
2306 dead_denies: vec![],
2307 dest_mem: "engine".to_string(),
2308 binding_id: "engine/graph".to_string(),
2309 delivery: vec![],
2310 };
2311 let findings = vec![
2312 finding(
2313 FindingClass::Drifted,
2314 anchor_target("engine--e", "src/moved.rs"),
2315 "prepared-content hash drifted",
2316 ),
2317 finding(
2318 FindingClass::Uncovered,
2319 artifact_target("src/new.rs"),
2320 "in scope, no anchor",
2321 ),
2322 ];
2323 let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2324 assert!(out.contains("## Source changes since the last sync"));
2326 assert!(out.contains("`moved.rs`"));
2327 assert!(out.contains("## Open findings to repair"));
2328 assert!(out.contains("`engine--e` → `src/moved.rs`"));
2329 assert!(out.contains("`src/new.rs`"));
2330 assert!(out.contains("sole maintenance writer"));
2332 assert!(out.contains("commits each one **per-mutation**"));
2333 assert!(out.contains("Sync commits nothing."));
2334 }
2335
2336 #[test]
2341 fn sync_brief_absorbs_reconcile_conservatism() {
2342 let r = resolved("engine", None, vec![]);
2343 let findings = vec![finding(
2344 FindingClass::Uncovered,
2345 artifact_target("src/x.rs"),
2346 "d",
2347 )];
2348 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2349 assert!(out.contains("Unsure whether an entity is affected — skip it."));
2351 assert!(out.contains(
2352 "Do not create a new entity unless the change clearly introduces a new concept"
2353 ));
2354 assert!(
2355 out.contains("Do not delete an entity unless the change removes the concept entirely.")
2356 );
2357 assert!(out.contains("Never rewrite a section that has not changed"));
2358 assert!(out.contains(
2359 "No speculative edges — add only relationships the diff literally introduces"
2360 ));
2361 assert!(out.contains("A dropped dependency FLAGS, it does not auto-remove."));
2363 assert!(out.contains("Edge removal is out of scope for sync."));
2364 assert!(out.contains("Rationale is reasoning, not a changelog."));
2366 assert!(out.contains("`[commit <hash>]` log-style entries"));
2367 }
2368
2369 #[test]
2373 fn sync_brief_renders_adopt_framing() {
2374 let mut r = resolved("engine", None, vec![]);
2375 r.name = "engine/graph".to_string();
2379 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], true);
2380 assert!(out.contains("## First sync — adopting `engine`"));
2381 assert!(out.contains("0% anchored is expected — this is onboarding, not a failure."));
2382 assert!(out.contains("do **not** replay the whole history"));
2383 assert!(out.contains("**Backfill path:**"));
2384 assert!(out.contains("memstead projection verify engine/graph"));
2385 }
2386
2387 #[test]
2390 fn sync_brief_inherits_first_sync_reseed_framing() {
2391 let r = resolved("engine", None, vec![]);
2392 let mut cursor = empty_cursor();
2393 cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2394 let out = render_sync_brief(&r, &cursor, &[], &[], false);
2395 assert!(out.contains("No usable sync baseline exists for"));
2396 assert!(out.contains("Treating the current source state as the baseline"));
2397 }
2398
2399 #[test]
2402 fn sync_brief_nothing_to_sync() {
2403 let r = resolved("engine", None, vec![]);
2404 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2405 assert!(out.contains("## Nothing to sync"));
2406 assert!(!out.contains("## How to repair"));
2407 assert!(!out.contains("## Open findings"));
2408 }
2409
2410 #[test]
2415 fn only_sync_brief_carries_repair_instructions() {
2416 let r = resolved("engine", None, vec![]);
2417 let findings = vec![finding(
2418 FindingClass::Drifted,
2419 anchor_target("engine--e", "src/a.rs"),
2420 "d",
2421 )];
2422 let verify = render_verify_brief(&r, 1);
2423 let sync = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2424 assert!(!verify.contains("## How to repair"));
2426 assert!(!verify.contains("Update the affected section"));
2427 assert!(sync.contains("## How to repair — be conservative"));
2429 assert!(sync.contains("## Open findings to repair"));
2430 assert!(sync.contains("Update the affected section to match"));
2431 }
2432
2433 #[test]
2437 fn sync_brief_changed_slice_renders_stale_claim_search() {
2438 let r = resolved("engine", None, vec![]);
2439 let cursor = SourceCursor {
2440 union: slice(&[], &["moved.rs"], &[]),
2441 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2442 reseed: vec![],
2443 no_signal: vec![],
2444 any_changes: true,
2445 degraded: false,
2446 dead_denies: vec![],
2447 dest_mem: "engine".to_string(),
2448 binding_id: "engine/graph".to_string(),
2449 delivery: vec![],
2450 };
2451 let out = render_sync_brief(&r, &cursor, &[], &[], false);
2452 assert!(out.contains("## Stale claims beyond the slice — search, then judge"));
2453 assert!(out.contains("Extract the **changed facts** from the changed artifacts above"));
2455 assert!(out.contains("search the destination mem `engine`"));
2456 assert!(out.contains("`memstead_search`"));
2457 assert!(out.contains("judge **only** the entities whose claims actually mention"));
2458 assert!(out.contains("not a live-verify of every entity"));
2461 assert!(out.contains("not a rewrite license"));
2462 assert!(out.contains("the fact set is empty and this step ends with no"));
2463 assert!(out.contains("Never rewrite a section that has not changed"));
2466 }
2467
2468 #[test]
2472 fn sync_brief_without_changes_renders_no_stale_claim_search() {
2473 let r = resolved("engine", None, vec![]);
2474 let heading = "## Stale claims beyond the slice";
2475
2476 let findings = vec![finding(
2478 FindingClass::Uncovered,
2479 artifact_target("src/x.rs"),
2480 "d",
2481 )];
2482 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2483 assert!(!out.contains(heading), "findings-only pass must not search");
2484
2485 let mut reseed_cursor = empty_cursor();
2487 reseed_cursor.reseed = vec![cmd("engine/graph/src#synced", "TOK")];
2488 let out = render_sync_brief(&r, &reseed_cursor, &[], &[], false);
2489 assert!(!out.contains(heading), "reseed-only pass must not search");
2490
2491 let out = render_sync_brief(&r, &empty_cursor(), &[], &[], false);
2493 assert!(!out.contains(heading));
2494 }
2495
2496 #[test]
2499 fn sync_brief_caps_large_findings_group() {
2500 let r = resolved("engine", None, vec![]);
2501 let findings: Vec<Finding> = (0..FINDINGS_CAP + 4)
2502 .map(|i| {
2503 finding(
2504 FindingClass::Uncovered,
2505 artifact_target(&format!("src/f{i}.rs")),
2506 "d",
2507 )
2508 })
2509 .collect();
2510 let out = render_sync_brief(&r, &empty_cursor(), &findings, &[], false);
2511 assert!(out.contains("- …and 4 more"));
2512 assert!(!out.contains(&format!("src/f{}.rs", FINDINGS_CAP + 3)));
2514 }
2515
2516 #[test]
2527 fn sync_brief_block_sequence_locked_for_changed_slice() {
2528 let r = resolved("engine", None, vec![]);
2529 let cursor = SourceCursor {
2530 union: slice(&["gone.rs"], &["moved.rs"], &["new.rs"]),
2531 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2532 reseed: vec![],
2533 no_signal: vec![],
2534 any_changes: true,
2535 degraded: false,
2536 dead_denies: vec![],
2537 dest_mem: "engine".to_string(),
2538 binding_id: "engine/graph".to_string(),
2539 delivery: vec![],
2540 };
2541 let findings = vec![
2542 finding(
2543 FindingClass::Drifted,
2544 anchor_target("engine--e", "src/moved.rs"),
2545 "prepared-content hash drifted",
2546 ),
2547 finding(
2548 FindingClass::Uncovered,
2549 artifact_target("src/new.rs"),
2550 "in scope, no anchor",
2551 ),
2552 ];
2553 let out = render_sync_brief(&r, &cursor, &findings, &[], false);
2554 let headings: Vec<&str> = out
2555 .lines()
2556 .filter(|l| l.starts_with("## ") || l.starts_with("### "))
2557 .collect();
2558 assert_eq!(
2559 headings,
2560 vec![
2561 "## Sync — repair the graph to match the source",
2562 "## Source changes since the last sync",
2563 "### Recording your dispositions (do this LAST)",
2564 "## Stale claims beyond the slice — search, then judge",
2565 "## Open findings to repair",
2566 "### Drifted — the anchored content changed",
2567 "### Uncovered — a source artifact with no entity",
2568 "## Provenance — anchor your writes",
2572 "## How to repair — be conservative",
2573 ],
2574 "the loop-path sync brief carries exactly these blocks, in this order"
2575 );
2576 assert!(out.ends_with("`[commit <hash>]` log-style entries.\n\n"));
2579 }
2580
2581 #[test]
2592 fn no_default_path_brief_carries_inventory_machinery() {
2593 let inventory_terms = [
2596 "--full",
2597 "inventory",
2598 "full measurement",
2599 "did not converge",
2600 "quiescence",
2601 ];
2602 let assert_clean = |label: &str, text: &str| {
2603 let lower = text.to_lowercase();
2604 for term in inventory_terms {
2605 assert!(
2606 !lower.contains(term),
2607 "{label} must carry no inventory machinery (found {term:?})"
2608 );
2609 }
2610 };
2611
2612 let r = resolved("engine", None, vec![]);
2613 let g = guidance(Some("build coverage"), None);
2614 let pm = process_present("engine");
2615
2616 let changed_cursor = SourceCursor {
2618 union: slice(&[], &["moved.rs"], &[]),
2619 write_commands: vec![cmd("engine/graph/src#synced", "HEAD")],
2620 reseed: vec![],
2621 no_signal: vec![],
2622 any_changes: true,
2623 degraded: false,
2624 dead_denies: vec![],
2625 dest_mem: "engine".to_string(),
2626 binding_id: "engine/graph".to_string(),
2627 delivery: vec![],
2628 };
2629 let preface = render_changed_slice(&changed_cursor);
2630 assert_clean(
2631 "discovery build brief (plain roam)",
2632 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], ""),
2633 );
2634 assert_clean(
2635 "discovery build brief (changed slice)",
2636 &assemble_discovery_brief(&r, &g, &pm, Some("s@1"), None, &[], &preface),
2637 );
2638 assert_clean(
2639 "one-shot build brief",
2640 &assemble_one_shot_brief(&r, &g, &pm, Some("s@1"), None, &[], Some("purpose")),
2641 );
2642
2643 assert_clean("verify brief (backlog)", &render_verify_brief(&r, 3));
2645 assert_clean("verify brief (no backlog)", &render_verify_brief(&r, 0));
2646
2647 let findings = vec![finding(
2649 FindingClass::Drifted,
2650 anchor_target("engine--e", "src/moved.rs"),
2651 "d",
2652 )];
2653 assert_clean(
2654 "sync brief (changed slice + findings)",
2655 &render_sync_brief(&r, &changed_cursor, &findings, &[], false),
2656 );
2657 assert_clean(
2658 "sync brief (findings-only)",
2659 &render_sync_brief(&r, &empty_cursor(), &findings, &[], false),
2660 );
2661 assert_clean(
2662 "sync brief (nothing to sync)",
2663 &render_sync_brief(&r, &empty_cursor(), &[], &[], false),
2664 );
2665 assert_clean(
2666 "sync brief (adopt)",
2667 &render_sync_brief(&r, &empty_cursor(), &[], &[], true),
2668 );
2669 }
2670}