memstead_base/ingest/prune.rs
1//! Prune — deletion **proposal** machinery (bundle plan `05-verify-sync-engine`,
2//! group F).
3//!
4//! Prune answers "the source removed this artifact entirely — should the entity
5//! describing it be deleted?". It **never** mutates the destination mem: it
6//! produces [`PruneProposal`]s the **sync brief** surfaces, and the deletion
7//! reaches the mem only when an agent acts on that brief through the normal MCP
8//! mutation surface (A5 holds — there is no engine path from here that deletes
9//! or writes a mem entity). [`prune_proposals`] takes a shared `&Engine`, so it
10//! is structurally incapable of a mem mutation.
11//!
12//! ## Guarantee (F1) and degradation (F2)
13//!
14//! A binding requests a [`crate::binding::PruneGuarantee`]. The guarantee a
15//! medium can *support* is stated at binding-validation time (a `never-clobber`
16//! request over a non-base-retrievable medium is refused there, never at run
17//! time). At proposal time prune resolves the **effective** posture per
18//! candidate:
19//!
20//! - **never-clobber** — where the candidate's source **base leg is
21//! retrievable** (a git-pinned anchor: `at_version` is a commit), a three-way
22//! merge can tell a model-side edit apart from a clean removal, so a clean
23//! removal can be proposed as a confident (agent-enacted) delete.
24//! - **conflict-flag degradation** — everywhere else (a `conflict-flag`
25//! request, or a candidate with **no** retrievable base leg — a non-git
26//! source): prune presents **both** sides and never proposes a clean delete,
27//! so a model-side edit is never silently clobbered. This is the decided
28//! posture; span-snapshot base legs for non-git sources are out of scope (no
29//! current payer).
30//!
31//! ## Provenance guards (F3)
32//!
33//! - an `authored`-provenance entity is **never** a prune target (excluded
34//! entirely — no proposal is produced);
35//! - a `derived` entity is **flagged with its inputs**, never auto-proposed for
36//! deletion — its inputs must be re-examined first;
37//! - only `anchored` / `informed-by` entities whose whole source basis vanished
38//! become delete proposals, and only conservatively (every anchor orphaned).
39
40use std::collections::BTreeMap;
41use std::path::Path;
42
43use crate::Engine;
44use crate::anchor::{AnchorProvenanceClass, AnchorState, AnchorVersion};
45use crate::binding::{Binding, PruneGuarantee};
46
47use super::resolve::ResolvedIngest;
48
49/// The **effective** prune posture for a candidate (F1/F2) — the requested
50/// guarantee resolved against what is actually retrievable.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PruneMode {
53 /// Never-clobber three-way merge is in force (a `never-clobber` request).
54 /// Whether a *given* candidate can use it still depends on that candidate's
55 /// base-leg retrievability — a candidate with no retrievable base degrades
56 /// to conflict-flagging.
57 NeverClobber,
58 /// Conflict-flag degradation is in force (a `conflict-flag` request): both
59 /// sides are always presented, a clean delete is never proposed.
60 ConflictFlag,
61}
62
63impl PruneMode {
64 /// The effective posture a binding's requested guarantee selects.
65 pub fn from_guarantee(guarantee: PruneGuarantee) -> Self {
66 match guarantee {
67 PruneGuarantee::NeverClobber => PruneMode::NeverClobber,
68 PruneGuarantee::ConflictFlag => PruneMode::ConflictFlag,
69 }
70 }
71}
72
73/// The three-way-merge outcome for a never-clobber candidate whose base leg was
74/// retrieved: did the model side diverge from the retrieved base?
75///
76/// The model-divergence signal (comparing the current entity against the base
77/// leg) is not wired this cycle, so [`prune_proposals`] supplies `None` and
78/// every candidate conservatively conflict-flags. The [`PruneMerge::Clean`]
79/// branch is the reachable, tested seam a future model-divergence check drives.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum PruneMerge {
82 /// Base retrieved, model side unchanged from it — a clean removal.
83 Clean,
84 /// Base retrieved, model side diverged (a hand edit) — a real conflict.
85 Conflict,
86}
87
88/// The disposition a prune proposal carries (F2/F3).
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum PruneDisposition {
91 /// Never-clobber, base leg retrieved, three-way merge clean → a confident
92 /// (still agent-enacted) delete proposal.
93 CleanDelete,
94 /// Both sides presented; the agent decides. Never an auto-write — the model
95 /// side may carry a deliberate edit. Conflict-flag degradation, or a
96 /// never-clobber merge that found (or could not rule out) a divergence.
97 ConflictFlag,
98 /// A `derived` entity — flagged with its inputs, never auto-proposed for
99 /// deletion (F3).
100 DerivedFlagged,
101}
102
103impl PruneDisposition {
104 /// Stable wire form.
105 pub fn as_wire(&self) -> &'static str {
106 match self {
107 PruneDisposition::CleanDelete => "clean-delete",
108 PruneDisposition::ConflictFlag => "conflict-flag",
109 PruneDisposition::DerivedFlagged => "derived-flagged",
110 }
111 }
112}
113
114/// Classify one candidate entity into a prune disposition, or `None` when it is
115/// **excluded entirely** — an `authored`-provenance entity is never a prune
116/// target (F3).
117///
118/// - `authored` → `None` (never targeted);
119/// - `derived` → [`PruneDisposition::DerivedFlagged`] (flagged with inputs,
120/// never a delete);
121/// - `anchored` / `informed-by`:
122/// - conflict-flag mode → [`PruneDisposition::ConflictFlag`] (both sides);
123/// - never-clobber mode → [`PruneDisposition::CleanDelete`] **only** when the
124/// base leg is retrievable **and** the merge is clean; otherwise
125/// [`PruneDisposition::ConflictFlag`] (no retrievable base, or a divergent /
126/// undetermined merge — never a silent clobber).
127pub fn classify_prune_candidate(
128 class: AnchorProvenanceClass,
129 mode: PruneMode,
130 base_retrievable: bool,
131 merge: Option<PruneMerge>,
132) -> Option<PruneDisposition> {
133 match class {
134 // F3 — an authored entity is never a prune target.
135 AnchorProvenanceClass::Authored => None,
136 // F3 — a derived entity is flagged with its inputs, never a delete.
137 AnchorProvenanceClass::Derived => Some(PruneDisposition::DerivedFlagged),
138 AnchorProvenanceClass::Anchored | AnchorProvenanceClass::InformedBy => match mode {
139 PruneMode::ConflictFlag => Some(PruneDisposition::ConflictFlag),
140 PruneMode::NeverClobber => {
141 if base_retrievable && matches!(merge, Some(PruneMerge::Clean)) {
142 Some(PruneDisposition::CleanDelete)
143 } else {
144 // No retrievable base, a divergent merge, or an
145 // undetermined merge — degrade, never clobber.
146 Some(PruneDisposition::ConflictFlag)
147 }
148 }
149 },
150 }
151}
152
153/// A single prune proposal — a proposed removal the sync brief surfaces. The
154/// engine never enacts it: an agent acting on the sync brief deletes (or keeps)
155/// the entity through the MCP mutation surface (A5).
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct PruneProposal {
158 /// The destination-mem entity id (`mem--slug`) the proposal concerns.
159 pub entity: String,
160 /// The now-gone source artifacts the entity's (all-orphaned) anchors
161 /// referenced, deduplicated and sorted.
162 pub artifacts: Vec<String>,
163 /// The entity's dominant provenance class wire string (the class the
164 /// disposition was decided from).
165 pub class: String,
166 /// The disposition (F2/F3).
167 pub disposition: PruneDisposition,
168 /// Whether the candidate's source base leg is retrievable (a git-pinned
169 /// anchor). Drives the never-clobber vs. conflict-flag posture and is
170 /// surfaced so the brief can state which one applies.
171 pub base_retrievable: bool,
172 /// For a `derived` candidate: the input artifact refs to re-examine before
173 /// any removal (F3). Empty for every other class.
174 pub derived_inputs: Vec<String>,
175}
176
177/// Gather the prune proposals for a binding — **read-only** on the destination
178/// mem (shared `&Engine`; no mutation is structurally possible, A5). Returns an
179/// empty vec when the binding declares no `prune` block (prune disabled).
180///
181/// A **candidate** is an entity whose *entire* source basis vanished — every one
182/// of its anchors resolves [`AnchorState::Orphaned`] against the live source
183/// (the conservative "concept removed entirely" signal; an entity with any
184/// still-resolving anchor is left to sync's ordinary drift path, not prune). An
185/// entity with any *unobserved* anchor is skipped — prune never asserts a
186/// removal it could not observe.
187pub fn prune_proposals(
188 engine: &Engine,
189 _workspace_root: &Path,
190 binding: &Binding,
191 resolved: &ResolvedIngest,
192) -> Vec<PruneProposal> {
193 // Prune disabled → no proposals.
194 let Some(prune) = binding.prune.as_ref() else {
195 return Vec::new();
196 };
197 let mode = PruneMode::from_guarantee(prune.guarantee);
198
199 // Group the destination mem's resolved anchors by entity.
200 struct Acc {
201 classes: Vec<AnchorProvenanceClass>,
202 artifacts: Vec<String>,
203 base_retrievable: bool,
204 derived_inputs: Vec<String>,
205 all_orphaned: bool,
206 any: bool,
207 }
208 let mut by_entity: BTreeMap<String, Acc> = BTreeMap::new();
209 for (eid, resolved_anchor) in engine.mem_anchors_resolved(&resolved.destination_mem) {
210 let entry = by_entity.entry(eid.as_ref().to_string()).or_insert(Acc {
211 classes: Vec::new(),
212 artifacts: Vec::new(),
213 base_retrievable: false,
214 derived_inputs: Vec::new(),
215 all_orphaned: true,
216 any: false,
217 });
218 entry.any = true;
219 let anchor = &resolved_anchor.anchor;
220 entry.classes.push(anchor.class);
221 entry.artifacts.push(anchor.artifact.clone());
222 // A git-pinned commit is a retrievable base leg for the three-way merge.
223 if matches!(anchor.at_version, Some(AnchorVersion::Commit(_))) {
224 entry.base_retrievable = true;
225 }
226 if anchor.class == AnchorProvenanceClass::Derived {
227 entry
228 .derived_inputs
229 .extend(anchor.derived_from.iter().cloned());
230 }
231 // Every anchor must resolve orphaned for the whole basis to be gone;
232 // an unobserved anchor (state None) blocks the candidate — prune never
233 // asserts a removal it could not observe.
234 match resolved_anchor.state {
235 Some(AnchorState::Orphaned) => {}
236 _ => entry.all_orphaned = false,
237 }
238 }
239
240 let mut proposals: Vec<PruneProposal> = Vec::new();
241 for (entity, acc) in by_entity {
242 if !acc.any || !acc.all_orphaned {
243 continue;
244 }
245 // Dominant class precedence: authored (exclude) > derived (flag) >
246 // anchored > informed-by.
247 let dominant = if acc.classes.contains(&AnchorProvenanceClass::Authored) {
248 AnchorProvenanceClass::Authored
249 } else if acc.classes.contains(&AnchorProvenanceClass::Derived) {
250 AnchorProvenanceClass::Derived
251 } else if acc.classes.contains(&AnchorProvenanceClass::Anchored) {
252 AnchorProvenanceClass::Anchored
253 } else {
254 AnchorProvenanceClass::InformedBy
255 };
256
257 // Merge outcome is unwired this cycle → None → conservative conflict-flag.
258 let Some(disposition) =
259 classify_prune_candidate(dominant, mode, acc.base_retrievable, None)
260 else {
261 // Authored → excluded, never a prune target (F3).
262 continue;
263 };
264
265 let mut artifacts = acc.artifacts;
266 artifacts.sort();
267 artifacts.dedup();
268 let mut derived_inputs = acc.derived_inputs;
269 derived_inputs.sort();
270 derived_inputs.dedup();
271
272 proposals.push(PruneProposal {
273 entity,
274 artifacts,
275 class: dominant.as_wire().to_string(),
276 disposition,
277 base_retrievable: acc.base_retrievable,
278 derived_inputs,
279 });
280 }
281 proposals
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 // ---- F2/F3: pure classifier -----------------------------------------
289
290 /// F3 — an authored entity is never a prune target: excluded (no proposal),
291 /// in either mode.
292 #[test]
293 fn authored_is_never_a_prune_target() {
294 for mode in [PruneMode::NeverClobber, PruneMode::ConflictFlag] {
295 assert_eq!(
296 classify_prune_candidate(
297 AnchorProvenanceClass::Authored,
298 mode,
299 true,
300 Some(PruneMerge::Clean),
301 ),
302 None,
303 "authored must never be proposed for deletion"
304 );
305 }
306 }
307
308 /// F3 — a derived entity is flagged (with inputs), never auto-proposed for
309 /// deletion, in either mode.
310 #[test]
311 fn derived_is_flagged_not_deleted() {
312 for mode in [PruneMode::NeverClobber, PruneMode::ConflictFlag] {
313 assert_eq!(
314 classify_prune_candidate(
315 AnchorProvenanceClass::Derived,
316 mode,
317 true,
318 Some(PruneMerge::Clean),
319 ),
320 Some(PruneDisposition::DerivedFlagged),
321 "derived is flagged, never a clean delete"
322 );
323 }
324 }
325
326 /// F2 — conflict-flag mode always presents both sides (never a clean
327 /// delete), whatever the base/merge state.
328 #[test]
329 fn conflict_flag_mode_never_clean_deletes() {
330 for base in [true, false] {
331 for merge in [None, Some(PruneMerge::Clean), Some(PruneMerge::Conflict)] {
332 assert_eq!(
333 classify_prune_candidate(
334 AnchorProvenanceClass::Anchored,
335 PruneMode::ConflictFlag,
336 base,
337 merge,
338 ),
339 Some(PruneDisposition::ConflictFlag),
340 "conflict-flag mode never auto-clean-deletes"
341 );
342 }
343 }
344 }
345
346 /// F2 — never-clobber degrades to conflict-flag when the base leg is not
347 /// retrievable (a non-git source), or when the merge is divergent /
348 /// undetermined; it clean-deletes only with a retrievable base AND a clean
349 /// merge.
350 #[test]
351 fn never_clobber_clean_delete_needs_base_and_clean_merge() {
352 let anchored = AnchorProvenanceClass::Anchored;
353 // Retrievable base + clean merge → the one clean-delete path.
354 assert_eq!(
355 classify_prune_candidate(
356 anchored,
357 PruneMode::NeverClobber,
358 true,
359 Some(PruneMerge::Clean)
360 ),
361 Some(PruneDisposition::CleanDelete)
362 );
363 // No retrievable base (non-git) → conflict-flag degradation.
364 assert_eq!(
365 classify_prune_candidate(
366 anchored,
367 PruneMode::NeverClobber,
368 false,
369 Some(PruneMerge::Clean)
370 ),
371 Some(PruneDisposition::ConflictFlag),
372 "no base leg degrades to conflict-flag"
373 );
374 // Divergent merge → conflict-flag (never clobber the model edit).
375 assert_eq!(
376 classify_prune_candidate(
377 anchored,
378 PruneMode::NeverClobber,
379 true,
380 Some(PruneMerge::Conflict)
381 ),
382 Some(PruneDisposition::ConflictFlag),
383 "a divergent merge is never a clean delete"
384 );
385 // Undetermined merge (signal unwired) → conflict-flag (safe default).
386 assert_eq!(
387 classify_prune_candidate(anchored, PruneMode::NeverClobber, true, None),
388 Some(PruneDisposition::ConflictFlag),
389 "an undetermined merge conservatively conflict-flags"
390 );
391 }
392
393 /// `informed-by` is a delete candidate too (a non-hash class that still owns
394 /// a concept), following the same mode rules as `anchored`.
395 #[test]
396 fn informed_by_follows_the_same_mode_rules() {
397 assert_eq!(
398 classify_prune_candidate(
399 AnchorProvenanceClass::InformedBy,
400 PruneMode::ConflictFlag,
401 false,
402 None,
403 ),
404 Some(PruneDisposition::ConflictFlag)
405 );
406 }
407
408 // ---- F2/F3: end-to-end over a real engine ----------------------------
409
410 use crate::anchor::{Anchor, AnchorGrain, AnchorHashStability, AnchorSidecar};
411 use crate::binding::{
412 BINDING_VERSION, BuildMode, BuildOperation, DEFAULT_ADJUDICATION_CAP,
413 DEFAULT_FULL_RESYNC_EVERY, Operations, PruneConfig, VerifyOperation,
414 };
415 use crate::ingest::render::render_sync_brief_for;
416 use crate::ingest::resolve::resolve_binding_run;
417 use crate::pipeline::{IngestTrigger, MediumType, PatternEntry, PatternMode};
418 use crate::pipeline_store::write_binding;
419 use crate::workspace::{
420 Mount, MountCapability, MountLifecycle, MountStorage, Workspace, WorkspaceSettings,
421 };
422 use crate::workspace_store::WorkspaceStoreAdapter;
423
424 /// An orphan-bound anchor of `class` on `artifact`, git-pinned when
425 /// `commit` is set (a retrievable base leg).
426 fn orphan_anchor(
427 artifact: &str,
428 class: AnchorProvenanceClass,
429 derived_from: Vec<&str>,
430 commit: Option<&str>,
431 ) -> Anchor {
432 Anchor {
433 artifact: artifact.to_string(),
434 grain: AnchorGrain::File,
435 class,
436 at_version: commit.map(|c| AnchorVersion::Commit(c.to_string())),
437 hash: class.is_hash_bearing().then(|| "recorded".to_string()),
438 hash_stability: AnchorHashStability::Stable,
439 derived_from: derived_from.into_iter().map(str::to_string).collect(),
440 binding: None,
441 source: None,
442 }
443 }
444
445 /// Scaffold a filesystem-medium mem whose anchors reference **absent** source
446 /// files (so every anchor resolves orphaned), with a `prune` block at
447 /// `guarantee`. Returns the engine, workspace root, binding and resolved run.
448 /// The source is deliberately **non-git** (a plain filesystem medium, no
449 /// `at_version` unless the fixture pins one) so the base leg is not
450 /// retrievable — the F2 degradation case.
451 fn setup(
452 tmp: &Path,
453 guarantee: PruneGuarantee,
454 entity_anchors: &[(&str, Vec<Anchor>)],
455 ) -> (Engine, std::path::PathBuf, Binding, ResolvedIngest) {
456 let root = tmp.to_path_buf();
457 let mem_dir = root.join("mem");
458 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
459 std::fs::write(
460 mem_dir.join(".memstead").join("config.json"),
461 r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
462 )
463 .unwrap();
464 std::fs::create_dir_all(root.join(".memstead")).unwrap();
465 std::fs::write(
466 root.join(".memstead").join("workspace.toml"),
467 "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
468 )
469 .unwrap();
470 let mount = Mount {
471 mem: "engine".to_string(),
472 schema: Some("default@1.0.0".parse().unwrap()),
473 storage: MountStorage::Folder {
474 path: mem_dir.clone(),
475 },
476 capability: MountCapability::Write,
477 lifecycle: MountLifecycle::Eager,
478 cross_linkable: false,
479 migration_target: None,
480 };
481 crate::FileWorkspaceStore::new()
482 .save_state(
483 &root,
484 &Workspace {
485 mounts: vec![mount],
486 settings: WorkspaceSettings::default(),
487 },
488 )
489 .unwrap();
490
491 // Seed the anchors sidecar (test fixture — the production write path is
492 // the mutation surface, not prune). No source files are created, so every
493 // anchor resolves orphaned.
494 let mut sidecar = AnchorSidecar::default();
495 for (eid, anchors) in entity_anchors {
496 sidecar.set(eid, anchors.clone());
497 }
498 std::fs::write(
499 mem_dir.join(crate::anchor::ANCHOR_SIDECAR_PATH),
500 sidecar.to_bytes(),
501 )
502 .unwrap();
503
504 // A filesystem-source binding (namespace `path`, so mem_anchors_resolved
505 // observes it) with the requested prune guarantee.
506 let binding = Binding {
507 version: BINDING_VERSION,
508 intent: None,
509 sources: vec![crate::pipeline::Source {
510 name: "graph".to_string(),
511 medium_type: MediumType::Filesystem,
512 pointer: String::new(),
513 change_detection: None,
514 scope: vec![PatternEntry {
515 path: "src/**/*.rs".to_string(),
516 mode: PatternMode::Allow,
517 }],
518 engagement: None,
519 preparation: None,
520 }],
521 reference_mems: Vec::new(),
522 destination_mem: "engine".to_string(),
523 deny_paths: Vec::new(),
524 coverage_semantics: None,
525 rules: None,
526 prune: Some(PruneConfig { guarantee }),
527 operations: Operations {
528 build: Some(BuildOperation {
529 mode: BuildMode::Discovery,
530 trigger: IngestTrigger::Loop,
531 batch_size: 20,
532 post_actions: None,
533 }),
534 sync: Some(crate::binding::SyncOperation {
535 trigger: IngestTrigger::Manual,
536 batch_size: 20,
537 }),
538 verify: Some(VerifyOperation {
539 trigger: IngestTrigger::Manual,
540 batch_size: 20,
541 adjudication_cap: DEFAULT_ADJUDICATION_CAP,
542 full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
543 }),
544 },
545 };
546 write_binding(&root, "engine", "graph", &binding).unwrap();
547
548 let engine = Engine::from_workspace_root(&root).unwrap();
549 let resolved = resolve_binding_run("engine/graph", &binding).unwrap();
550 (engine, root, binding, resolved)
551 }
552
553 /// F2 — conflict-flag degradation on a **non-git** source: a model-side
554 /// entity whose source artifact was removed surfaces BOTH sides in the sync
555 /// brief and is NEVER auto-deleted. Requesting never-clobber over a non-git
556 /// anchor (no retrievable base leg) degrades to conflict-flag.
557 #[test]
558 fn f2_conflict_flag_on_non_git_surfaces_both_sides_no_auto_delete() {
559 let tmp = tempfile::tempdir().unwrap();
560 // Request never-clobber; the non-git anchor has no base leg → degrades.
561 let (engine, root, binding, resolved) = setup(
562 tmp.path(),
563 PruneGuarantee::NeverClobber,
564 &[(
565 "engine--removed",
566 vec![orphan_anchor(
567 "src/removed.rs",
568 AnchorProvenanceClass::Anchored,
569 vec![],
570 None, // non-git: no retrievable base leg
571 )],
572 )],
573 );
574
575 let proposals = prune_proposals(&engine, &root, &binding, &resolved);
576 assert_eq!(proposals.len(), 1, "the orphaned entity is a candidate");
577 let p = &proposals[0];
578 assert_eq!(p.entity, "engine--removed");
579 assert!(
580 !p.base_retrievable,
581 "non-git anchor has no retrievable base"
582 );
583 assert_eq!(
584 p.disposition,
585 PruneDisposition::ConflictFlag,
586 "no base leg → conflict-flag degradation, never a clean delete"
587 );
588
589 // The rendered sync brief presents BOTH sides and frames it as a proposal.
590 let brief = render_sync_brief_for(&engine, &root, "engine/graph").unwrap();
591 assert!(brief.contains("Prune — proposed removals"));
592 assert!(brief.contains("source side:"), "source side surfaced");
593 assert!(brief.contains("model side:"), "model side surfaced");
594 assert!(
595 brief.contains("never overwrites a model-side edit"),
596 "no auto-overwrite is stated"
597 );
598 // A5: the pass never mutated the mem — the entity's anchor is still there
599 // (prune_proposals took a shared &Engine; a delete is structurally
600 // impossible). Re-read the sidecar to confirm.
601 let after = engine.mem_anchors_resolved("engine");
602 assert!(
603 after.iter().any(|(e, _)| e.as_ref() == "engine--removed"),
604 "prune must not delete the entity's anchors — it only proposes"
605 );
606 }
607
608 /// F3 — provenance guards: an `authored` entity is NEVER a prune target
609 /// (excluded, no proposal); a `derived` entity is flagged with its inputs,
610 /// never proposed for deletion; a plain `anchored` entity is proposed.
611 #[test]
612 fn f3_authored_excluded_and_derived_flagged_not_deleted() {
613 let tmp = tempfile::tempdir().unwrap();
614 let (engine, root, binding, resolved) = setup(
615 tmp.path(),
616 PruneGuarantee::ConflictFlag,
617 &[
618 (
619 "engine--handwritten",
620 vec![orphan_anchor(
621 "src/authored.rs",
622 AnchorProvenanceClass::Authored,
623 vec![],
624 None,
625 )],
626 ),
627 (
628 "engine--synthesised",
629 vec![orphan_anchor(
630 "src/derived.rs",
631 AnchorProvenanceClass::Derived,
632 vec!["src/in_a.rs", "src/in_b.rs"],
633 None,
634 )],
635 ),
636 (
637 "engine--plain",
638 vec![orphan_anchor(
639 "src/plain.rs",
640 AnchorProvenanceClass::Anchored,
641 vec![],
642 None,
643 )],
644 ),
645 ],
646 );
647
648 let proposals = prune_proposals(&engine, &root, &binding, &resolved);
649
650 // F3 — authored is never a prune target: no proposal names it.
651 assert!(
652 !proposals.iter().any(|p| p.entity == "engine--handwritten"),
653 "an authored entity is never proposed for deletion"
654 );
655
656 // F3 — derived is flagged with its inputs, not proposed for deletion.
657 let derived = proposals
658 .iter()
659 .find(|p| p.entity == "engine--synthesised")
660 .expect("the derived entity is flagged");
661 assert_eq!(derived.disposition, PruneDisposition::DerivedFlagged);
662 assert_eq!(derived.class, "derived");
663 assert_eq!(
664 derived.derived_inputs,
665 vec!["src/in_a.rs".to_string(), "src/in_b.rs".to_string()],
666 "the derived entity carries its inputs to re-examine"
667 );
668
669 // The plain anchored entity IS proposed (conflict-flag).
670 let plain = proposals
671 .iter()
672 .find(|p| p.entity == "engine--plain")
673 .expect("a plain anchored entity is proposed");
674 assert_eq!(plain.disposition, PruneDisposition::ConflictFlag);
675
676 // The rendered sync brief flags the derived entity as NOT-for-deletion,
677 // never emits an auto-delete instruction, and never names the authored one.
678 let brief = render_sync_brief_for(&engine, &root, "engine/graph").unwrap();
679 assert!(brief.contains("flagged, NOT proposed for deletion"));
680 assert!(brief.contains("`engine--synthesised`"));
681 assert!(
682 !brief.contains("engine--handwritten"),
683 "the authored entity never appears in a prune proposal"
684 );
685 assert!(brief.contains("nothing is auto-deleted"));
686 }
687
688 /// A `never-clobber` binding whose anchor IS git-pinned has a retrievable
689 /// base leg — the proposal reports it (the never-clobber posture), while
690 /// still degrading to conflict-flag until the model-divergence merge signal
691 /// is wired (the gatherer supplies no merge outcome this cycle).
692 #[test]
693 fn git_pinned_anchor_reports_a_retrievable_base_leg() {
694 let tmp = tempfile::tempdir().unwrap();
695 let (engine, root, binding, resolved) = setup(
696 tmp.path(),
697 PruneGuarantee::NeverClobber,
698 &[(
699 "engine--pinned",
700 vec![orphan_anchor(
701 "src/pinned.rs",
702 AnchorProvenanceClass::Anchored,
703 vec![],
704 Some("deadbeef"),
705 )],
706 )],
707 );
708 let proposals = prune_proposals(&engine, &root, &binding, &resolved);
709 assert_eq!(proposals.len(), 1);
710 assert!(
711 proposals[0].base_retrievable,
712 "a git-pinned anchor exposes a retrievable base leg"
713 );
714 // Merge outcome unwired → still conflict-flag (never a silent clobber).
715 assert_eq!(proposals[0].disposition, PruneDisposition::ConflictFlag);
716 }
717
718 /// An entity with a **still-resolving** anchor is NOT a prune candidate —
719 /// the whole basis must be gone (conservatism). Here one anchor's file
720 /// exists, so the entity is skipped.
721 #[test]
722 fn entity_with_a_surviving_anchor_is_not_pruned() {
723 let tmp = tempfile::tempdir().unwrap();
724 let (engine, root, binding, resolved) = setup(
725 tmp.path(),
726 PruneGuarantee::ConflictFlag,
727 &[(
728 "engine--partly-gone",
729 vec![
730 orphan_anchor("src/gone.rs", AnchorProvenanceClass::Anchored, vec![], None),
731 orphan_anchor(
732 "src/present.rs",
733 AnchorProvenanceClass::InformedBy,
734 vec![],
735 None,
736 ),
737 ],
738 )],
739 );
740 // Create only the second file so its anchor resolves (not orphaned).
741 std::fs::create_dir_all(root.join("src")).unwrap();
742 std::fs::write(root.join("src").join("present.rs"), "fn a() {}\n").unwrap();
743
744 let proposals = prune_proposals(&engine, &root, &binding, &resolved);
745 assert!(
746 proposals.is_empty(),
747 "an entity whose basis is not entirely gone is not a prune candidate"
748 );
749 }
750}