Skip to main content

memstead_base/engine/query/
anchors.rs

1//! Anchor resolution: the per-entity and per-mem anchor reads, the observation and verification passes with their clock, and the free functions that resolve an artifact ref across a binding's sources.
2
3use super::*;
4
5impl Engine {
6    /// Convenience: look up a parsed entity by id. Returns `None` for
7    /// unknown ids, including stub entries created for unresolved
8    /// inline-link targets — callers that want to distinguish real
9    /// from stub branch on `Entity::stub`.
10    pub fn get_entity(&self, id: &EntityId) -> Option<&Entity> {
11        self.store.get(id)
12    }
13
14    /// The stored provenance anchors for `id`, read from its mem's
15    /// anchors sidecar. Empty for an entity with none, an unknown mem, or
16    /// a backend that does not persist anchors (a pre-anchor archive / any
17    /// sealed read-only mount). Additive read surface: the
18    /// resolution *model* lives in [`crate::anchor`]
19    /// ([`crate::anchor::resolve_anchor`] / [`crate::anchor::compose_entity_anchors`]);
20    /// the live per-anchor *state* (which requires observing the source
21    /// artifacts through the medium/preparation pipeline) is the anchor
22    /// observation pass's concern.
23    /// The anchors sidecar's parse error for `mem`, if it has one.
24    ///
25    /// The anchor readers below degrade a malformed sidecar to "no anchors",
26    /// which keeps a read path alive but makes a corrupt file
27    /// indistinguishable from an empty one. For a *reader* that is the right
28    /// trade; for anything that draws a conclusion from the absence of
29    /// anchors it is not — a fidelity pass would report every artifact
30    /// uncovered and call it a finding, when the truth is that it could not
31    /// read the file. Callers that need that distinction ask here first and
32    /// refuse. `None` means the sidecar is absent (legitimately no anchors
33    /// yet) or parses cleanly; the binding store draws the same distinction
34    /// with its quarantine path.
35    /// The entities of `mem` that hold at least one anchor row — the
36    /// sidecar's key set, no observation performed. What a coverage reading
37    /// subtracts from the mem's entity roster to name the entities no
38    /// artifact stands behind. Empty for a mem with no sidecar, an unmounted
39    /// mem, or an unreadable sidecar (the latter is reported by
40    /// [`Self::anchors_sidecar_error`], never inferred from an empty set).
41    pub fn mem_anchor_holders(&self, mem: &str) -> std::collections::BTreeSet<String> {
42        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
43            return Default::default();
44        };
45        let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
46            return Default::default();
47        };
48        let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
49            return Default::default();
50        };
51        sc.entities
52            .iter()
53            .filter(|(_, rows)| !rows.is_empty())
54            .map(|(eid, _)| eid.clone())
55            .collect()
56    }
57
58    pub fn anchors_sidecar_error(&self, mem: &str) -> Option<String> {
59        let mount = self.mounts.iter().find(|m| m.mount.mem == mem)?;
60        // Three distinct ways to be unreadable, and only one of them is a
61        // parse error. `.ok().flatten()` would collapse the first into
62        // "absent", which is the very confusion this exists to prevent.
63        let bytes = match mount.backend.read_anchors_sidecar() {
64            // A backend error — permission denied, an IO fault. The file may
65            // be perfectly well-formed; we simply could not look at it.
66            Err(e) => return Some(format!("could not read the sidecar: {e}")),
67            // Genuinely absent: a mem with no anchors yet. Not an error.
68            Ok(None) => return None,
69            Ok(Some(b)) => b,
70        };
71        // An empty or whitespace-only file parses as "no anchors" by a
72        // deliberate tolerance in `from_bytes`. That tolerance is right for a
73        // reader and wrong here: a sidecar truncated to zero by an
74        // interrupted write is not a mem that never had anchors.
75        if bytes.iter().all(|b| b.is_ascii_whitespace()) {
76            return Some(
77                "the sidecar file is empty — an interrupted write leaves this state, and it is                  not the same as having no anchors; remove the file if the mem genuinely has none"
78                    .to_string(),
79            );
80        }
81        match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
82            Ok(_) => None,
83            Err(e) => Some(e.to_string()),
84        }
85    }
86
87    /// [`Self::entity_anchors`] for a write that copies them: a sidecar
88    /// that cannot be read or parsed refuses instead of reading as none,
89    /// which would drop the anchors from the copy.
90    pub(crate) fn entity_anchors_for_write(
91        &self,
92        id: &EntityId,
93    ) -> Result<Vec<crate::anchor::Anchor>, crate::engine::EngineError> {
94        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == id.mem()) else {
95            return Ok(Vec::new());
96        };
97        let Some(bytes) = mount.backend.read_anchors_sidecar()? else {
98            return Ok(Vec::new());
99        };
100        let sidecar = crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
101            crate::engine::EngineError::InvalidInput(format!(
102                "the anchors sidecar of `{}` does not parse: {e}",
103                id.mem()
104            ))
105        })?;
106        Ok(sidecar.get(id.as_ref()).to_vec())
107    }
108
109    pub fn entity_anchors(&self, id: &EntityId) -> Vec<crate::anchor::Anchor> {
110        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == id.mem()) else {
111            return Vec::new();
112        };
113        let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
114            return Vec::new();
115        };
116        match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
117            Ok(sc) => sc.get(id.as_ref()).to_vec(),
118            // Deliberate degrade-to-empty for the read path; a caller that
119            // must not confuse "unreadable" with "none" checks
120            // [`Self::anchors_sidecar_error`] first.
121            Err(_) => Vec::new(),
122        }
123    }
124
125    /// The stored anchors for `id`, each paired with its **live** resolution
126    /// state when the engine could observe the source artifact this pass.
127    ///
128    /// Additive over [`Self::entity_anchors`]: the durable data is unchanged;
129    /// `state` is the [`crate::anchor::resolve_anchor`] outcome against an
130    /// observation the engine produces here. A `path`-namespace anchor
131    /// (codebase / filesystem / git) is observed against the working tree at
132    /// the current HEAD; an `entity`-namespace anchor is observed against the
133    /// live graph by [`Self::observe_entity_anchor`]:
134    ///
135    /// - artifact absent ⇒ [`AnchorState::Orphaned`](crate::anchor::AnchorState::Orphaned);
136    /// - artifact present, non-hash class (`authored` / `informed-by`) ⇒
137    ///   [`Resolves`](crate::anchor::AnchorState::Resolves);
138    /// - artifact present, hash-bearing class (`anchored` / `derived`) ⇒ the
139    ///   prepared-content hash comparison decides:
140    ///   [`Resolves`](crate::anchor::AnchorState::Resolves) on a match,
141    ///   [`Drifted`](crate::anchor::AnchorState::Drifted) on a stable-medium
142    ///   mismatch, [`Recheck`](crate::anchor::AnchorState::Recheck) on an
143    ///   unstable medium or when a hash is unavailable on either side (a
144    ///   hash-less anchor, a `tree` grain, an unreadable artifact).
145    ///
146    /// For an `entity` grain the same table applies, read off the store
147    /// rather than the filesystem: the entity missing (or present only as a
148    /// stub) is `Orphaned`, and a hash-bearing class compares the canonical
149    /// rendered markdown.
150    ///
151    /// `state` is `None` (unobserved — never a fabricated state) when there is
152    /// no workspace root, when the grain is `url` (the engine never fetches;
153    /// a url anchor's hash is the registry's prepared form of the content
154    /// its observer supplied at write time), when an `entity` anchor's
155    /// source declares a preparation the registry does not know (the form
156    /// cannot be computed), or when an `entity` anchor's mem is **not
157    /// mounted** — an unmounted mem is not a mem of deleted entities, and
158    /// saying so would route a deletion proposal to prune.
159    pub fn entity_anchors_resolved(&self, id: &EntityId) -> Vec<ResolvedAnchor> {
160        let anchors = self.entity_anchors(id);
161        let source_roots = self.anchor_source_roots(id.mem());
162        let none = SuppliedObservations::new();
163        anchors
164            .into_iter()
165            .map(|anchor| self.resolve_one(anchor, &source_roots, &none))
166            .collect()
167    }
168
169    /// Observe one stored anchor and pair it with its resolution — the
170    /// shared step behind every anchor read.
171    fn resolve_one(
172        &self,
173        anchor: crate::anchor::Anchor,
174        source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
175        supplied: &SuppliedObservations,
176    ) -> ResolvedAnchor {
177        let observed = self.observe_anchor(&anchor, source_roots, supplied);
178        let (state, observed_hash, observed_at) = match observed {
179            Some(o) => (Some(o.state), o.hash, o.at),
180            None => (None, None, None),
181        };
182        ResolvedAnchor {
183            anchor,
184            state,
185            observed_hash,
186            observed_at,
187        }
188    }
189
190    /// Per-anchor observation — THE one resolution mechanism, shared by
191    /// binding-backed verify (`mem_anchors_resolved`, which the ingest
192    /// render/report/prune/findings paths consume), the per-entity read
193    /// (`entity_anchors_resolved`), and the standalone
194    /// `verify_mem_anchors` operation. Path-shaped grains
195    /// (`span`/`file`/`tree`) observe under the **decision-29 candidate
196    /// priority** (an earlier plana): the anchor's artifact path is
197    /// SOURCE-relative first — when its `source` name resolves through
198    /// `source_roots` to a declared pointer, the pointer-joined path is
199    /// authoritative — and workspace-relative only as the fallback, tried
200    /// when the source-join does not resolve. A path resolving under both
201    /// joins is decided by that priority, deterministically. An anchor
202    /// without a `source` (a hand-authored mem, a binding-less write)
203    /// observes workspace-relative exactly as before. A `url`
204    /// grain has no engine-side observation and returns `None` (the report
205    /// vocabulary's `unresolvable`) — the engine never fetches; its hash is
206    /// recorded from observation-supplied content at write time — as does a
207    /// workspace-root-less engine. An `entity`
208    /// grain is not a filesystem path but is not unobservable either — it
209    /// resolves against the live graph via
210    /// [`Self::observe_entity_anchor`], under the preparation its source
211    /// declares (touchpoint A of [`crate::preparation`]: the registry
212    /// decides the prepared form the artifact hashes as). This replaces the retired `single_path_medium_root` gate,
213    /// whose single-source assumption nulled every anchor of a mem with
214    /// zero or several bindings — the honest per-anchor answer supersedes
215    /// the all-or-nothing mem-level one.
216    ///
217    /// A `url` grain is the one grain the engine cannot observe itself: it
218    /// resolves from a SUPPLIED observation when the caller passed one for
219    /// its artifact (`memstead verify-anchors --observations`), else from
220    /// the row's recorded `last_observed` (sidecar version 2) — an
221    /// observation that was made, carrying its own date so the row ages
222    /// visibly — else it is unobserved (`None`), never fabricated. A
223    /// supplied `absent` resolves `recheck`, not `orphaned`: an observer
224    /// failing to retrieve a web resource is not the medium saying the
225    /// artifact is gone, and prune must never act on it.
226    fn observe_anchor(
227        &self,
228        anchor: &crate::anchor::Anchor,
229        source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
230        supplied: &SuppliedObservations,
231    ) -> Option<Observed> {
232        if anchor.grain == crate::anchor::AnchorGrain::Url {
233            if let Some(obs) = supplied
234                .get(&anchor.artifact)
235                .filter(|obs| observation_adjudicates(obs, anchor))
236            {
237                return Some(match &obs.outcome {
238                    crate::anchor::SuppliedOutcome::Absent => Observed {
239                        state: crate::anchor::AnchorState::Recheck,
240                        hash: None,
241                        at: Some(obs.at.clone()),
242                    },
243                    // A row quoting a span is adjudicated on the span's
244                    // presence in the retrieved text; the document's hash
245                    // rides along as what was observed (the row's last
246                    // observation), never as the verdict. `observation_adjudicates`
247                    // has already excluded a hash-only observation here.
248                    crate::anchor::SuppliedOutcome::Present {
249                        hash,
250                        content: Some(text),
251                    } if anchor.span.is_some() => Observed {
252                        state: crate::anchor::resolve_span_anchor(anchor, text),
253                        hash: Some(hash.clone()),
254                        at: Some(obs.at.clone()),
255                    },
256                    crate::anchor::SuppliedOutcome::Present { hash, content } => {
257                        // Touchpoint A for a url row: supplied CONTENT is
258                        // re-prepared under the anchor's source preparation,
259                        // the rule the write path applied to the anchor's
260                        // own `content`, so a `quoted-phrase` row is
261                        // adjudicated on its phrase. A phrase the retrieved
262                        // page no longer carries is the medium saying the
263                        // unit is gone — `orphaned` — unlike a failed
264                        // retrieval, which stays `recheck`. A supplied hash,
265                        // or a source with no preparation, compares as is.
266                        let preparation = anchor
267                            .source
268                            .as_deref()
269                            .and_then(|name| source_roots.get(name))
270                            .and_then(|j| j.preparation.as_deref());
271                        let current = match (preparation, content) {
272                            (Some(_), Some(text)) => crate::preparation::path_prepared_hash(
273                                preparation,
274                                &anchor.artifact,
275                                anchor.grain,
276                                text.as_bytes(),
277                            ),
278                            _ => crate::preparation::PathPrepared::NoHash,
279                        };
280                        match current {
281                            crate::preparation::PathPrepared::UnitAbsent => Observed {
282                                state: crate::anchor::resolve_anchor(
283                                    anchor,
284                                    &crate::anchor::ArtifactObservation::Absent,
285                                ),
286                                hash: None,
287                                at: Some(obs.at.clone()),
288                            },
289                            crate::preparation::PathPrepared::Hash(h) => Observed {
290                                state: crate::anchor::resolve_anchor(
291                                    anchor,
292                                    &crate::anchor::ArtifactObservation::Present {
293                                        current_hash: Some(h.clone()),
294                                    },
295                                ),
296                                hash: Some(h),
297                                at: Some(obs.at.clone()),
298                            },
299                            crate::preparation::PathPrepared::NoHash => Observed {
300                                state: crate::anchor::resolve_anchor(
301                                    anchor,
302                                    &crate::anchor::ArtifactObservation::Present {
303                                        current_hash: Some(hash.clone()),
304                                    },
305                                ),
306                                hash: Some(hash.clone()),
307                                at: Some(obs.at.clone()),
308                            },
309                        }
310                    }
311                });
312            }
313            return anchor.last_observed.as_ref().map(|rec| Observed {
314                state: rec.state,
315                hash: rec.hash.clone(),
316                at: Some(rec.at.clone()),
317            });
318        }
319        let join = anchor
320            .source
321            .as_deref()
322            .and_then(|name| source_roots.get(name));
323        // An `entity`-grain anchor points into a mem's graph, not a file
324        // tree. It has always returned `None` here — "unobserved this pass" —
325        // which meant it could never be drifted, never be orphaned, and always
326        // blocked prune. That bail showed in practice: a
327        // deliberately stale anchor over a changed source entity went unflagged
328        // while the capability matrix claimed full parity.
329        if anchor.grain == crate::anchor::AnchorGrain::Entity {
330            return self
331                .observe_entity_anchor(anchor, join.and_then(|j| j.preparation.as_deref()))
332                .map(Observed::live);
333        }
334        let root = self.workspace_root.as_deref()?;
335        observe_path_anchor(root, anchor, join).map(Observed::live)
336    }
337
338    /// The prepared hash of an `entity`-grain artifact's target as it stands
339    /// NOW, under `preparation`: what the write-time pin records on a
340    /// hash-bearing `entity` row written without a hash, and the same form
341    /// [`Self::observe_entity_anchor`] later compares against. `None` when
342    /// the target cannot be resolved (its mem not mounted, the entity absent
343    /// or a stub, an addressed unit the entity does not carry, or a
344    /// preparation with no entity form): the row then stays hash-less rather
345    /// than carrying a guess.
346    pub(crate) fn entity_anchor_target_hash(
347        &self,
348        artifact: &str,
349        preparation: Option<&str>,
350    ) -> Option<String> {
351        let (id_part, locator) = crate::preparation::split_unit_id(artifact);
352        let id = EntityId::canonical(id_part);
353        if !self.mounts.iter().any(|m| m.mount.mem == id.mem()) {
354            return None;
355        }
356        let entity = self.store.get(&id).filter(|e| !e.stub)?;
357        let type_def = self
358            .schema_for(id.mem())
359            .and_then(|schema| schema.get_type(&entity.entity_type));
360        match crate::preparation::entity_prepared(entity, type_def.as_deref(), preparation, locator)
361        {
362            crate::preparation::PathPrepared::Hash(h) => Some(h),
363            crate::preparation::PathPrepared::UnitAbsent
364            | crate::preparation::PathPrepared::NoHash => None,
365        }
366    }
367
368    /// Observe an `entity`-grain anchor against the live graph — the entity-
369    /// namespace counterpart of [`observe_path_anchor`], and the mechanism
370    /// that makes a graph-medium binding's drift real.
371    ///
372    /// The artifact is an entity id. Present/absent comes from the store, so
373    /// this works uniformly across backends — a git-branch mem has no
374    /// working-tree file to stat, which is exactly why observation cannot go
375    /// through the filesystem here. The compared form is the preparation
376    /// registry's **prepared form** for `preparation` (the anchor's source's
377    /// declared preparation, [`crate::preparation::entity_prepared_hash`]):
378    /// the **canonical rendered markdown** when the source declares none —
379    /// byte-for-byte today's form — or the load-bearing serialization under
380    /// `entity-load-bearing`; hashed with the same `prepared_content_hash`
381    /// the path arm uses, so an anchor's recorded hash means the same thing
382    /// in both namespaces. An identifier the registry does not know cannot
383    /// be prepared: the anchor is reported unobserved (`None`), never hashed
384    /// under a fabricated form.
385    ///
386    /// A stub is treated as absent: a stub is the engine's placeholder for an
387    /// unresolved reference, not the entity the anchor claims to pin. Scoring
388    /// it as present would let a dangling anchor resolve clean.
389    fn observe_entity_anchor(
390        &self,
391        anchor: &crate::anchor::Anchor,
392        preparation: Option<&str>,
393    ) -> Option<(crate::anchor::AnchorState, Option<String>)> {
394        // A `#<locator>` on an entity artifact is the preparation's business
395        // (`quoted-phrase`: the phrase the entity must still carry); the id
396        // is what stands before it.
397        let (id_part, locator) = crate::preparation::split_unit_id(&anchor.artifact);
398        let id = EntityId::canonical(id_part);
399
400        // The mem the anchor points into must be MOUNTED before a store miss
401        // can mean anything. If it is not, every entity in it is missing from
402        // the store, and reporting `Orphaned` would say "the source deleted
403        // these" about entities sitting untouched on disk. `None` — genuinely
404        // unobserved — is the honest answer.
405        //
406        // This guard lives here, at the one observation site, and not at the
407        // callers. An earlier fix put it in `run_verify` alone; `prune` reaches
408        // anchor resolution by its own path (`mem_anchors_resolved`), so the
409        // sync brief went on proposing the deletion of every destination
410        // entity — a data-loss suggestion routed to the graph's only
411        // maintenance writer, from a mem merely being unmounted. A guard that
412        // protects one caller is not a guard on the behaviour.
413        if !self.mounts.iter().any(|m| m.mount.mem == id.mem()) {
414            return None;
415        }
416
417        let entity = self.store.get(&id).filter(|e| !e.stub);
418        let Some(entity) = entity else {
419            return Some((
420                crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
421                None,
422            ));
423        };
424        let current_hash = if anchor.class.is_hash_bearing() {
425            let type_def = self
426                .schema_for(id.mem())
427                .and_then(|schema| schema.get_type(&entity.entity_type));
428            match crate::preparation::entity_prepared(
429                entity,
430                type_def.as_deref(),
431                preparation,
432                locator,
433            ) {
434                crate::preparation::PathPrepared::Hash(h) => Some(h),
435                // The entity stands but no longer carries the addressed
436                // unit (a `quoted-phrase` the markdown lost): an absent
437                // artifact, adjudicated like a file's vanished unit.
438                crate::preparation::PathPrepared::UnitAbsent => {
439                    return Some((
440                        crate::anchor::resolve_anchor(
441                            anchor,
442                            &crate::anchor::ArtifactObservation::Absent,
443                        ),
444                        None,
445                    ));
446                }
447                crate::preparation::PathPrepared::NoHash => return None,
448            }
449        } else {
450            None
451        };
452        let observation = crate::anchor::ArtifactObservation::Present {
453            current_hash: current_hash.clone(),
454        };
455        Some((
456            crate::anchor::resolve_anchor(anchor, &observation),
457            current_hash,
458        ))
459    }
460
461    /// The `source name → join` map for `mem`'s bindings: the filesystem
462    /// roots that anchors written in the source dialect join onto (anchor
463    /// artifact paths are source-relative first) and the
464    /// preparation each source declares (touchpoint A: what the registry
465    /// prepares the artifact as before hashing). Empty when the workspace
466    /// has no root, the pipeline store does not load, or `mem` has no
467    /// bindings — resolution then degrades to the workspace-relative dialect
468    /// alone with no preparation, which is exactly the hand-authored-mem
469    /// posture.
470    pub(crate) fn anchor_source_roots(
471        &self,
472        mem: &str,
473    ) -> std::collections::BTreeMap<String, AnchorSourceJoin> {
474        let mut roots = std::collections::BTreeMap::new();
475        let Some(root) = self.workspace_root.as_deref() else {
476            return roots;
477        };
478        let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root) else {
479            return roots;
480        };
481        for record in configs.bindings.iter().filter(|r| r.mem == mem) {
482            for source in &record.config.sources {
483                roots
484                    .entry(source.name.clone())
485                    .or_insert_with(|| AnchorSourceJoin {
486                        pointer: source.pointer.clone(),
487                        preparation: source.preparation.clone(),
488                        source: source.clone(),
489                        deny_paths: record.config.deny_paths.clone(),
490                    });
491            }
492        }
493        roots
494    }
495
496    /// Reverse anchor lookup: every `(entity_id, anchor)` across all mems
497    /// whose anchor references `artifact_path`. This is the query the
498    /// rebuilt check-realization hook consumes — given the file an agent
499    /// just edited, which entities anchored to it. A `span`/`file`/`tree`
500    /// anchor references the path when its base path (locator suffix
501    /// `@commit` / `#span` stripped) equals the path, or — for a `tree`
502    /// grain — when the path lies under the tree. Path-shaped grains only;
503    /// `url` / `entity` anchors are matched by exact base equality.
504    pub fn anchors_referencing_artifact(
505        &self,
506        artifact_path: &str,
507    ) -> Vec<(EntityId, crate::anchor::Anchor)> {
508        let mut out = Vec::new();
509        for mount in &self.mounts {
510            let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
511                continue;
512            };
513            let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
514                continue;
515            };
516            // Source-dialect anchors reference the same
517            // artifact under its pointer-joined workspace form — match both.
518            let source_roots = self.anchor_source_roots(&mount.mount.mem);
519            for (eid, anchors) in &sc.entities {
520                for a in anchors {
521                    // The shared decision-29 candidate rule: the join
522                    // candidate exists only where the rule produces one (a
523                    // climbing `../…` artifact never joins); the
524                    // workspace-relative form is the `anchor_references_path`
525                    // arm below.
526                    let joined = a
527                        .source
528                        .as_deref()
529                        .and_then(|name| source_roots.get(name))
530                        .map(|join| {
531                            artifact_candidates(&join.pointer, anchor_base_path(&a.artifact))
532                        })
533                        .and_then(|mut c| (c.len() > 1).then(|| c.remove(0)));
534                    if anchor_references_path(a, artifact_path)
535                        || joined.is_some_and(|j| {
536                            path_references(
537                                &j,
538                                a.grain == crate::anchor::AnchorGrain::Tree,
539                                artifact_path,
540                            )
541                        })
542                    {
543                        out.push((EntityId(eid.clone()), a.clone()));
544                    }
545                }
546            }
547        }
548        out
549    }
550
551    /// Every `(entity_id, resolved anchor)` in `mem`, read from its anchors
552    /// sidecar once and each paired with its **live** resolution state (the
553    /// same observation [`Self::entity_anchors_resolved`] produces per entity,
554    /// computed here mem-wide in a single sidecar read). Empty for an unknown
555    /// mem, a backend that persists no anchors, or a mem with none.
556    ///
557    /// Additive read surface: the durable data is unchanged; `state` is the
558    /// [`crate::anchor::resolve_anchor`] outcome against an observation the
559    /// engine produces — the working tree for a `path`-namespace anchor, the
560    /// live graph for an `entity` one — or `None` when unobserved (never
561    /// fabricated). The verify pipeline consumes it to adjudicate a mem's
562    /// anchors against the source; audit/health can reuse it.
563    /// Whether `mem`'s anchor sidecar records ANY anchor row — the cheap
564    /// existence check [`Self::mem_anchors_resolved`] cannot serve: that
565    /// walk OBSERVES every anchor (hashing live source artifacts, and for
566    /// path anchors enumerating the facet's file scope) when a caller only
567    /// needs to know the sidecar is non-empty. Parses the sidecar and stops
568    /// there; false for an unknown mem, a backend without anchors, or an
569    /// empty sidecar — the same population `mem_anchors_resolved` would
570    /// report empty for, minus the observation cost.
571    pub fn mem_has_anchors(&self, mem: &str) -> bool {
572        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
573            return false;
574        };
575        let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
576            return false;
577        };
578        let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
579            return false;
580        };
581        sc.entities.values().any(|anchors| !anchors.is_empty())
582    }
583
584    pub fn mem_anchors_resolved(&self, mem: &str) -> Vec<(EntityId, ResolvedAnchor)> {
585        self.mem_anchors_resolved_with(mem, &SuppliedObservations::new())
586    }
587
588    /// [`Self::mem_anchors_resolved`] with observer-supplied observations
589    /// for the grains the engine cannot observe itself (`url`), keyed by
590    /// artifact. Rows without a supplied observation resolve as they would
591    /// without the map.
592    pub fn mem_anchors_resolved_with(
593        &self,
594        mem: &str,
595        supplied: &SuppliedObservations,
596    ) -> Vec<(EntityId, ResolvedAnchor)> {
597        let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
598            return Vec::new();
599        };
600        let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
601            return Vec::new();
602        };
603        let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
604            return Vec::new();
605        };
606        let mut out = Vec::new();
607        let source_roots = self.anchor_source_roots(mem);
608        for (eid, anchors) in &sc.entities {
609            for anchor in anchors {
610                out.push((
611                    EntityId(eid.clone()),
612                    self.resolve_one(anchor.clone(), &source_roots, supplied),
613                ));
614            }
615        }
616        out
617    }
618
619    /// Standalone anchor verification — "do my sources still say what I
620    /// recorded?" for one mem, regardless of how it was built. Walks the
621    /// mem's anchor sidecar through the shared per-anchor mechanism
622    /// ([`Self::observe_anchor`] via [`Self::mem_anchors_resolved`]) and
623    /// classifies every anchor into the report vocabulary: `resolved`
624    /// (source present, hash matches or non-hash class), `drifted`
625    /// (present, hash differs, stability `stable`), `recheck` (hash
626    /// differs under `unstable`, or a hash is missing on either side),
627    /// `unresolvable` (source absent, or a grain/medium the mechanism
628    /// does not reach — never fabricated into drift). Read-only on mem
629    /// content: pure sidecar read + filesystem observation, no commit on
630    /// any backend. A mem with no anchors returns an empty report.
631    pub fn verify_mem_anchors(&self, mem: &str) -> Result<MemAnchorVerification, EngineError> {
632        self.verify_mem_anchors_with(mem, &SuppliedObservations::new())
633    }
634
635    /// The stale axis defers to anchor state: an entity carrying at least
636    /// one adjudicated hash-bearing anchor (`resolves`, `drifted` or
637    /// `recheck`) reads by its anchors, not by the day threshold. `drifted`
638    /// and `recheck` list the entity as their own condition whatever its
639    /// age; `resolves` keeps it off the list, and when the threshold would
640    /// have listed it the row moves to `anchor_fresh` so the reading names
641    /// the clock that overruled the threshold. Entities with no adjudicated
642    /// anchor (none at all, or only `unresolvable` / `unobserved` rows)
643    /// keep the day-threshold reading, byte for byte. Derived at read time
644    /// from the same verification the anchors axis runs; nothing stored.
645    pub(super) fn apply_anchor_clock(
646        &self,
647        summary: &mut crate::ops::HealthSummary,
648        mem: Option<&str>,
649    ) {
650        use std::collections::HashMap;
651        // Dominant adjudicated state per entity: drifted > recheck > resolves.
652        fn rank(state: &str) -> Option<u8> {
653            match state {
654                "drifted" | "span_absent" => Some(3),
655                "recheck" => Some(2),
656                "resolves" => Some(1),
657                _ => None,
658            }
659        }
660        let mut by_entity: HashMap<String, (u8, String)> = HashMap::new();
661        let mut mems: Vec<String> = self.mem_names().iter().map(|s| s.to_string()).collect();
662        mems.retain(|m| mem.is_none_or(|scope| scope == m));
663        for m in mems {
664            let Ok(report) = self.verify_mem_anchors(&m) else {
665                continue;
666            };
667            for row in &report.anchors {
668                let Some(r) = rank(&row.state) else { continue };
669                let entry = by_entity
670                    .entry(row.entity_id.clone())
671                    .or_insert((0, String::new()));
672                if r > entry.0 {
673                    *entry = (r, row.state.clone());
674                }
675            }
676        }
677        if by_entity.is_empty() {
678            return;
679        }
680        let today = crate::ops::health::days_since_epoch();
681        let mut stale = std::mem::take(&mut summary.stale_entities);
682        // Day-threshold rows on anchored entities leave the list: a
683        // resolving anchor makes them fresh, a drifted or recheck one is
684        // re-listed below under its own condition.
685        let mut fresh = Vec::new();
686        stale.retain(|row| match by_entity.get(row.id.0.as_str()) {
687            None => true,
688            Some((_, state)) => {
689                if state == "resolves" {
690                    fresh.push(crate::ops::StaleEntity {
691                        id: row.id.clone(),
692                        title: row.title.clone(),
693                        days_since_modified: row.days_since_modified,
694                        anchor_state: Some(state.clone()),
695                    });
696                }
697                false
698            }
699        });
700        let mut by_anchor: Vec<crate::ops::StaleEntity> = by_entity
701            .iter()
702            .filter(|(_, (_, state))| state != "resolves")
703            .filter_map(|(id, (_, state))| {
704                let entity = self.store.get(&crate::EntityId(id.clone()))?;
705                if entity.stub || mem.is_some_and(|scope| entity.mem != scope) {
706                    return None;
707                }
708                let days = entity
709                    .metadata
710                    .get("last_modified")
711                    .and_then(|v| crate::ops::health::parse_iso_to_days(&v.to_frontmatter_string()))
712                    .map(|d| today.saturating_sub(d))
713                    .unwrap_or(0);
714                Some(crate::ops::StaleEntity {
715                    id: entity.id.clone(),
716                    title: entity.title.clone(),
717                    days_since_modified: days,
718                    anchor_state: Some(state.clone()),
719                })
720            })
721            .collect();
722        stale.append(&mut by_anchor);
723        stale.sort_by(|a, b| a.id.0.cmp(&b.id.0));
724        fresh.sort_by(|a, b| a.id.0.cmp(&b.id.0));
725        summary.stale_entities = stale;
726        summary.anchor_fresh = fresh;
727    }
728
729    /// [`Self::verify_mem_anchors`] with observer-supplied observations
730    /// (the `--observations` file of `memstead verify-anchors`). A `url`
731    /// row whose artifact has a supplied observation adjudicates through
732    /// the shared funnel exactly like a file row; a supplied row matching
733    /// no `url` anchor of the mem is reported in `unmatched_observations`
734    /// and changes nothing. The report's `recordable_observations` are the
735    /// `last_observed` records the caller commits with
736    /// [`Self::record_anchor_observations`] — the verification itself
737    /// writes nothing.
738    pub fn verify_mem_anchors_with(
739        &self,
740        mem: &str,
741        supplied: &SuppliedObservations,
742    ) -> Result<MemAnchorVerification, EngineError> {
743        if !self.mem_router.is_visible(mem) {
744            return Err(self.unknown_mem_error(mem));
745        }
746        let now = self.now_iso();
747        // An unreadable sidecar is a condition, never zero rows: the readers
748        // below would degrade it to "no anchors" and the report would then
749        // describe a clean mem it never measured.
750        if let Some(why) = self.anchors_sidecar_error(mem) {
751            let mut report = MemAnchorVerification {
752                mem: mem.to_string(),
753                sidecar_error: Some(why),
754                ..Default::default()
755            };
756            report.figure = report.figure_over(0);
757            return Ok(report);
758        }
759        let mut report = MemAnchorVerification {
760            mem: mem.to_string(),
761            unreconciled: self
762                .entity_set_is_reconcilable(mem)
763                .err()
764                .map(str::to_string),
765            ..Default::default()
766        };
767        let reconciled = report.unreconciled.is_none();
768        let mut resolves = 0usize;
769        let mut matched: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
770        for (eid, resolved) in self.mem_anchors_resolved_with(mem, supplied) {
771            let is_url = resolved.anchor.grain == crate::anchor::AnchorGrain::Url;
772            let supplied_here = is_url
773                && supplied
774                    .get(&resolved.anchor.artifact)
775                    .is_some_and(|obs| observation_adjudicates(obs, &resolved.anchor));
776            if supplied_here {
777                matched.insert(resolved.anchor.artifact.clone());
778            }
779            let observed_at = resolved.observed_at.clone();
780            let unobserved_for_days = observed_at
781                .as_deref()
782                .and_then(|at| crate::anchor::days_between(at, &now));
783            if let (true, Some(state), Some(at)) = (supplied_here, resolved.state, &observed_at) {
784                report.recordable_observations.push(RecordedObservation {
785                    entity: eid.to_string(),
786                    artifact: resolved.anchor.artifact.clone(),
787                    span: resolved.anchor.span.clone(),
788                    observation: crate::anchor::AnchorObservation {
789                        at: at.clone(),
790                        hash: resolved.observed_hash.clone(),
791                        state,
792                    },
793                });
794            }
795            // The entity end first: a row whose holder is gone is adjudicated
796            // against its artifact alone otherwise, and a matching hash then
797            // reports it as `resolved` for an entity that does not exist.
798            if reconciled && self.entity_is_absent(&eid) {
799                report.dangling += 1;
800                report.anchors.push(VerifiedAnchor {
801                    entity_id: eid.to_string(),
802                    artifact: resolved.anchor.artifact.clone(),
803                    grain: resolved.anchor.grain.as_wire().to_string(),
804                    class: resolved.anchor.class.as_wire().to_string(),
805                    span: resolved.anchor.span.clone(),
806                    state: "dangling".to_string(),
807                    observed_hash: resolved.observed_hash,
808                    observed_at,
809                    unobserved_for_days,
810                    observation_supplied: supplied_here,
811                });
812                continue;
813            }
814            let state = match resolved.state {
815                Some(crate::anchor::AnchorState::Resolves) => {
816                    resolves += 1;
817                    crate::anchor::AnchorState::Resolves.as_wire()
818                }
819                Some(crate::anchor::AnchorState::Drifted) => {
820                    report.drifted += 1;
821                    crate::anchor::AnchorState::Drifted.as_wire()
822                }
823                Some(crate::anchor::AnchorState::Recheck) => {
824                    report.recheck += 1;
825                    crate::anchor::AnchorState::Recheck.as_wire()
826                }
827                // The row spells the enum's wire name (`orphaned`); the
828                // summary count beside it keeps its surface name,
829                // `unresolvable` (the artifact is gone: a measured failure).
830                Some(crate::anchor::AnchorState::Orphaned) => {
831                    report.unresolvable += 1;
832                    crate::anchor::AnchorState::Orphaned.as_wire()
833                }
834                // The words a row quotes are gone while the document stands:
835                // adjudicated (the claim's basis was looked for and not
836                // found), its own count beside drifted and unresolvable.
837                Some(crate::anchor::AnchorState::SpanAbsent) => {
838                    report.span_absent += 1;
839                    crate::anchor::AnchorState::SpanAbsent.as_wire()
840                }
841                // Split from `unresolvable`: the artifact
842                // being GONE is a measurement; the pass not reaching the
843                // artifact at all is the absence of one, and the repairs
844                // differ.
845                None => {
846                    report.unobserved += 1;
847                    "unobserved"
848                }
849            };
850            report.anchors.push(VerifiedAnchor {
851                entity_id: eid.to_string(),
852                artifact: resolved.anchor.artifact.clone(),
853                grain: resolved.anchor.grain.as_wire().to_string(),
854                class: resolved.anchor.class.as_wire().to_string(),
855                span: resolved.anchor.span.clone(),
856                state: state.to_string(),
857                observed_hash: resolved.observed_hash,
858                observed_at,
859                unobserved_for_days,
860                observation_supplied: supplied_here,
861            });
862        }
863        report.unmatched_observations = supplied
864            .keys()
865            .filter(|artifact| !matched.contains(*artifact))
866            .cloned()
867            .collect();
868        report.figure = report.figure_over(resolves);
869        Ok(report)
870    }
871}
872
873/// The base path of an anchor artifact ref — the locator suffixes a
874/// medium may append (`@<commit>`, `#<span>`) stripped so the reverse
875/// lookup compares paths, not versioned/located refs.
876pub fn anchor_base_path(artifact: &str) -> &str {
877    let cut = artifact.find(['@', '#']).unwrap_or(artifact.len());
878    &artifact[..cut]
879}
880
881/// One mem's standalone anchor-verification report — the counts plus
882/// the per-anchor rows, in sidecar order.
883#[derive(Debug, Clone, Default, serde::Serialize)]
884pub struct MemAnchorVerification {
885    pub mem: String,
886    /// The anchors sidecar could not be read: the parse or IO reason. When
887    /// set, no row was counted — every count below is zero because nothing
888    /// was measured, not because the mem is clean — `fully_adjudicated`
889    /// reads false and the population reads unknown. One condition, one
890    /// code (`ANCHORS_SIDECAR_UNREADABLE`), rendered by every surface from
891    /// this field; no surface parses the sidecar on its own.
892    #[serde(skip_serializing_if = "Option::is_none")]
893    pub sidecar_error: Option<String>,
894    /// The positive figure with the population it was computed over
895    /// ([`crate::anchor::AnchorResolutionFigure`]): `resolves` (the wire
896    /// name is the `AnchorState` wire form; `resolved` was retired on
897    /// 2026-09-02, one name per state), `population` and
898    /// `fully_adjudicated`, serialized at this level. The count is never
899    /// reachable apart from its statement.
900    #[serde(flatten)]
901    pub figure: crate::anchor::AnchorResolutionFigure,
902    /// Source present, hash differs, stability `stable` — real drift.
903    pub drifted: usize,
904    /// Hash differs under `unstable` stability, or a hash is missing on
905    /// either side — flagged for re-examination, never called drift.
906    pub recheck: usize,
907    /// Source absent: a MEASURED failure. The artifact the anchor names is
908    /// not there.
909    pub unresolvable: usize,
910    /// The artifact is present but the words the row quotes (its `span`)
911    /// no longer occur in it: a measured failure of the row's claim, apart
912    /// from `drifted` (the claim is the span, not the page) and from
913    /// `unresolvable` (the document is there).
914    pub span_absent: usize,
915    /// The anchor could not be observed at all this pass, so nothing about it
916    /// was measured. Its own count,
917    /// because `unresolvable` used to swallow it: a reader on the surface you
918    /// reach WITHOUT a binding could not tell a measured failure from an
919    /// absent measurement, which is the one distinction that surface exists to
920    /// make.
921    pub unobserved: usize,
922    /// Rows whose ENTITY is gone. Its own class,
923    /// counted apart from the states above: those describe the artifact end,
924    /// and a vanished entity says nothing about the source. Folding it into
925    /// `unresolvable` would name the wrong repair.
926    pub dangling: usize,
927    /// Why the entity end could not be reconciled this pass, when it could
928    /// not. `dangling: 0` means "none found" only when this is `None`.
929    pub unreconciled: Option<String>,
930    pub anchors: Vec<VerifiedAnchor>,
931    /// Supplied observations whose artifact matched no `url` anchor of the
932    /// mem — reported, never silently dropped, never applied to anything.
933    #[serde(default, skip_serializing_if = "Vec::is_empty")]
934    pub unmatched_observations: Vec<String>,
935    /// The `last_observed` records this verification produced from supplied
936    /// observations, for the caller to commit through
937    /// [`Engine::record_anchor_observations`]. Engine-internal.
938    #[serde(skip)]
939    pub recordable_observations: Vec<RecordedObservation>,
940}
941
942/// One observation to record onto a sidecar row (the `last_observed`
943/// field), addressed by the row's identity: the entity, the artifact and
944/// the span (compared in the canonical span form, as the merge and the
945/// unset selector compare it). Exactly the row the verify adjudicated
946/// takes the record; a sibling row on the same artifact with another span,
947/// or with none, is another row with its own observation.
948#[derive(Debug, Clone, PartialEq, Eq)]
949pub struct RecordedObservation {
950    pub entity: String,
951    pub artifact: String,
952    pub span: Option<String>,
953    pub observation: crate::anchor::AnchorObservation,
954}
955
956/// Observer-supplied observations keyed by artifact — the input of
957/// [`Engine::verify_mem_anchors_with`].
958pub type SuppliedObservations =
959    std::collections::BTreeMap<String, crate::anchor::SuppliedObservation>;
960
961/// Whether a supplied observation can adjudicate `anchor`. A row quoting a
962/// span needs TEXT to look in: a hash-only observation (`{"hash": …}`)
963/// cannot say whether the words are there, so it leaves such a row as it
964/// was (its recorded observation, else unobserved this pass) rather than
965/// pretending to have adjudicated it. Every other pairing adjudicates.
966fn observation_adjudicates(
967    obs: &crate::anchor::SuppliedObservation,
968    anchor: &crate::anchor::Anchor,
969) -> bool {
970    anchor.span.is_none()
971        || !matches!(
972            obs.outcome,
973            crate::anchor::SuppliedOutcome::Present { content: None, .. }
974        )
975}
976
977/// What one observation of an anchor yielded: the resolved state, the
978/// hash it saw (when any), and — for an observation that was not made
979/// live this pass — when it was made.
980#[derive(Debug, Clone, PartialEq, Eq)]
981struct Observed {
982    state: crate::anchor::AnchorState,
983    hash: Option<String>,
984    at: Option<String>,
985}
986
987impl Observed {
988    /// A live observation made this pass (path and entity grains).
989    fn live((state, hash): (crate::anchor::AnchorState, Option<String>)) -> Self {
990        Observed {
991            state,
992            hash,
993            at: None,
994        }
995    }
996}
997
998impl MemAnchorVerification {
999    /// The figure this report's counts yield for `resolves` resolving rows:
1000    /// the count with the population statement it was computed over:
1001    /// what the figures cover,
1002    /// and how much of it the pass could not adjudicate.
1003    ///
1004    /// A resolution figure alone is read as health. Every such finding made that
1005    /// figure mean less than a reader assumes, and none of them made it wrong
1006    /// in a way anyone could see. The figure type renders the number and its
1007    /// population as ONE unit, so a surface cannot show the number and omit
1008    /// the caveat: it gets both or neither.
1009    fn figure_over(&self, resolves: usize) -> crate::anchor::AnchorResolutionFigure {
1010        // `recheck` belongs on ONE side of this sentence. A first version put
1011        // it in both: counted as adjudicated and then reported as not, so the
1012        // same rows appeared twice and the two numbers could not be reconciled
1013        // by a reader. A recheck row is a row whose drift could NOT be
1014        // asserted, which is the definition of unadjudicated.
1015        if let Some(why) = &self.sidecar_error {
1016            return crate::anchor::AnchorResolutionFigure::uncounted(format!(
1017                "population unknown: the anchors sidecar could not be read ({why}); no row was \
1018                 counted, and zero counts here are not a clean mem"
1019            ));
1020        }
1021        let adjudicated = resolves + self.drifted + self.unresolvable + self.span_absent;
1022        let unadjudicated = self.recheck + self.unobserved;
1023        let mut s = format!(
1024            "over {} counted row(s): {adjudicated} adjudicated, {unadjudicated} not (recheck {}, unobserved {})",
1025            adjudicated + unadjudicated,
1026            self.recheck,
1027            self.unobserved
1028        );
1029        if self.dangling > 0 {
1030            s.push_str(&format!(
1031                "; {} row(s) excluded, naming an entity the mem no longer holds",
1032                self.dangling
1033            ));
1034        }
1035        if let Some(why) = &self.unreconciled {
1036            s.push_str(&format!(
1037                "; the entity end was NOT reconciled ({why}), so dangling rows would not have been detected"
1038            ));
1039        }
1040        // False means the figures rest on an incomplete measurement, which
1041        // is not the same as a failed one.
1042        let fully_adjudicated =
1043            self.recheck == 0 && self.unobserved == 0 && self.unreconciled.is_none();
1044        crate::anchor::AnchorResolutionFigure::new(resolves, s, fully_adjudicated)
1045            .expect("the population statement is never empty")
1046    }
1047}
1048
1049/// One anchor's verification row.
1050#[derive(Debug, Clone, serde::Serialize)]
1051pub struct VerifiedAnchor {
1052    pub entity_id: String,
1053    pub artifact: String,
1054    pub grain: String,
1055    pub class: String,
1056    /// The words the row quotes, when it quotes any: the row is then
1057    /// adjudicated on their presence, and `state` reads `span_absent` once
1058    /// they are gone.
1059    #[serde(skip_serializing_if = "Option::is_none")]
1060    pub span: Option<String>,
1061    /// `resolves` | `drifted` | `recheck` | `orphaned` (artifact gone,
1062    /// counted as `unresolvable`) | `span_absent` (the quoted words gone) |
1063    /// `unobserved` (not measured this pass) | `dangling` (the entity is
1064    /// gone). The wire vocabulary of this field, which is NOT the engine's
1065    /// `AnchorState` enum: that has five variants describing the artifact
1066    /// end, and the last two here are conditions beside them.
1067    pub state: String,
1068    #[serde(skip_serializing_if = "Option::is_none")]
1069    pub observed_hash: Option<String>,
1070    /// When the observation this row's state rests on was made — present
1071    /// only for a row resolved from a supplied or recorded observation (a
1072    /// `url` row); live observations carry none.
1073    #[serde(skip_serializing_if = "Option::is_none")]
1074    pub observed_at: Option<String>,
1075    /// Whole days between `observed_at` and this run — how long the row has
1076    /// gone unobserved. `Some(0)` for an observation made today.
1077    #[serde(skip_serializing_if = "Option::is_none")]
1078    pub unobserved_for_days: Option<u64>,
1079    /// Whether this row's state came from an observation supplied to this
1080    /// run (as opposed to a live or a previously recorded one).
1081    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1082    pub observation_supplied: bool,
1083}
1084
1085/// Whether `anchor` references `path`. `tree`-grain anchors match `path`
1086/// itself and anything beneath the tree; every other grain matches by
1087/// exact base-path equality.
1088/// A stored anchor paired with its live resolution state, when observable.
1089/// See [`Engine::entity_anchors_resolved`] for how `state` is produced and
1090/// when it is `None` (unobserved, never fabricated).
1091#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1092pub struct ResolvedAnchor {
1093    /// The durable anchor record (flattened on the wire so the resolved shape
1094    /// is the stored anchor plus a `state` field).
1095    #[serde(flatten)]
1096    pub anchor: crate::anchor::Anchor,
1097    /// The live resolution state, or `None` when the engine could not observe
1098    /// the source artifact this pass: a `url` grain, no workspace root, an
1099    /// ambiguous or absent path medium, or an `entity` grain whose mem is not
1100    /// mounted. That last case is load-bearing — an unmounted mem is not a mem
1101    /// of deleted entities, so it must read as unobserved rather than
1102    /// `Orphaned`, which prune would act on.
1103    #[serde(skip_serializing_if = "Option::is_none")]
1104    pub state: Option<crate::anchor::AnchorState>,
1105    /// The prepared-content hash the observation computed this pass —
1106    /// present only for a hash-bearing (`anchored` / `derived`) anchor whose
1107    /// artifact could be read: a `file` / `span` anchor resolving to a
1108    /// readable file, or an `entity` anchor whose mem is mounted (hashed over
1109    /// the canonical rendered markdown, so the value means the same thing in
1110    /// both namespaces). The verify pass's backfill leg records it onto a
1111    /// hash-less anchor. Engine-internal
1112    /// observation detail, deliberately not serialized: the wire shape stays
1113    /// the stored anchor plus `state`.
1114    #[serde(skip)]
1115    pub observed_hash: Option<String>,
1116    /// When the observation `state` rests on was made, for a row whose
1117    /// observation is supplied or recorded rather than live (a `url` row).
1118    /// Additive: absent on every live-observed row.
1119    #[serde(skip_serializing_if = "Option::is_none")]
1120    pub observed_at: Option<String>,
1121}
1122
1123/// What an anchor's `source` name resolves to in its mem's bindings: the
1124/// declared pointer (the filesystem root a source-dialect artifact path
1125/// joins onto) and the declared preparation (what the
1126/// preparation registry prepares the artifact as before hashing —
1127/// touchpoint A of [`crate::preparation`]).
1128#[derive(Debug, Clone, PartialEq, Eq)]
1129pub(crate) struct AnchorSourceJoin {
1130    /// The source's declared `pointer`.
1131    pub(crate) pointer: String,
1132    /// The source's declared `preparation`, if any.
1133    pub(crate) preparation: Option<String>,
1134    /// The declaring source itself — its scope is what a `tree` anchor's
1135    /// prepared form enumerates under a code-map preparation.
1136    pub(crate) source: crate::pipeline::Source,
1137    /// The binding's `deny_paths`, applied on top of the source scope.
1138    pub(crate) deny_paths: Vec<String>,
1139}
1140
1141/// Observe a single path-namespace anchor against `root` (its medium's
1142/// filesystem root) and resolve its live state plus — for a present
1143/// hash-bearing (`anchored` / `derived`) `file` / `span` anchor — the
1144/// artifact's **prepared-content hash**
1145/// ([`crate::anchor::prepared_content_hash`]). `None` when the anchor's
1146/// grain does not reference a filesystem path.
1147///
1148/// The computed hash is what lets [`crate::anchor::resolve_anchor`]
1149/// adjudicate `drifted` vs `resolves` deterministically against the recorded
1150/// hash. The prepared form is the registry's rule for the anchor's
1151/// source's preparation ([`crate::preparation::path_prepared_hash`]): a
1152/// `span` anchor hashes its whole containing file (the span locator selects
1153/// within it; the file is the hashed unit), except under a **delivery
1154/// preparation**, where a `<path>#<key>` span names one delivery unit (the
1155/// unit's own text is the hashed unit, and a key the file no longer yields
1156/// is an absent artifact); under a **code-map** preparation a file or span
1157/// hashes the interface digest, and a `tree` hashes the code map of every
1158/// scoped file under it. A `tree` under any other preparation hashes the
1159/// plain per-file prepared-content map of its scoped files, so tree anchors
1160/// adjudicate deterministically like file anchors. A `tree` with no
1161/// resolvable source-join (the enumeration scope is undefined without one),
1162/// a partial enumeration, and a read failure observe no hash — those
1163/// resolve `recheck`, never a fabricated `drifted`. Non-hash classes
1164/// (`authored` / `informed-by`) skip the read entirely, so an anchor-less or
1165/// hash-free mem pays no observation cost.
1166fn observe_path_anchor(
1167    root: &Path,
1168    anchor: &crate::anchor::Anchor,
1169    join: Option<&AnchorSourceJoin>,
1170) -> Option<(crate::anchor::AnchorState, Option<String>)> {
1171    use crate::anchor::AnchorGrain;
1172    match anchor.grain {
1173        AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => {}
1174        AnchorGrain::Url | AnchorGrain::Entity => return None,
1175    }
1176    let source_pointer = join.map(|j| j.pointer.as_str());
1177    let preparation = join.and_then(|j| j.preparation.as_deref());
1178    let base = anchor_base_path(&anchor.artifact);
1179    // Decision 29: the source-join is authoritative — an artifact path is
1180    // source-relative first (joined onto the declaring source's pointer,
1181    // which may deliberately leave the workspace root for out-of-root
1182    // pointers); the workspace-relative form is tried only when the
1183    // source-join does not resolve. The candidate set is the shared
1184    // [`artifact_candidates`] rule, so resolution, the write gate, and the
1185    // population matcher read one artifact the same way.
1186    let path = {
1187        let candidates = artifact_candidates(source_pointer.unwrap_or(""), base);
1188        candidates
1189            .iter()
1190            .map(|c| root.join(c))
1191            .find(|p| p.exists())
1192            .unwrap_or_else(|| root.join(base))
1193    };
1194    if !path.exists() {
1195        return Some((
1196            crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
1197            None,
1198        ));
1199    }
1200    // A row quoting a span is adjudicated on the span's presence in the
1201    // file's text; the file's prepared hash rides along as the observed
1202    // hash. An unreadable file observes no hash and no text: recheck.
1203    if anchor.span.is_some() && matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span) {
1204        let Some(bytes) = (path.is_file())
1205            .then(|| std::fs::read(&path).ok())
1206            .flatten()
1207        else {
1208            return Some((crate::anchor::AnchorState::Recheck, None));
1209        };
1210        let text = String::from_utf8_lossy(&bytes);
1211        let state = crate::anchor::resolve_span_anchor(anchor, &text);
1212        let hash = match crate::preparation::path_prepared_hash(
1213            preparation,
1214            &anchor.artifact,
1215            anchor.grain,
1216            &bytes,
1217        ) {
1218            crate::preparation::PathPrepared::Hash(h) => Some(h),
1219            _ => None,
1220        };
1221        return Some((state, hash));
1222    }
1223    let current_hash = if !anchor.class.is_hash_bearing() {
1224        None
1225    } else if matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span) && path.is_file() {
1226        match std::fs::read(&path).ok().map(|bytes| {
1227            crate::preparation::path_prepared_hash(
1228                preparation,
1229                &anchor.artifact,
1230                anchor.grain,
1231                &bytes,
1232            )
1233        }) {
1234            Some(crate::preparation::PathPrepared::Hash(h)) => Some(h),
1235            Some(crate::preparation::PathPrepared::UnitAbsent) => {
1236                return Some((
1237                    crate::anchor::resolve_anchor(
1238                        anchor,
1239                        &crate::anchor::ArtifactObservation::Absent,
1240                    ),
1241                    None,
1242                ));
1243            }
1244            Some(crate::preparation::PathPrepared::NoHash) | None => None,
1245        }
1246    } else if anchor.grain == AnchorGrain::Tree
1247        && path.is_dir()
1248        && let Some(join) = join
1249    {
1250        // The tree's prepared form: a digest over every scoped file under
1251        // the tree, by the declaring source's own scope and the binding's
1252        // deny paths — the code map under a code-map preparation, the plain
1253        // per-file prepared-content map otherwise, so a tree anchor
1254        // adjudicates deterministically instead of resting in `recheck`
1255        // forever. The path the anchor names is workspace-relative or
1256        // source-relative; the enumeration is workspace-relative, so compare
1257        // the resolved absolute paths. A PARTIAL enumeration (malformed or
1258        // retired-dialect scope pattern) observes no hash — a digest over a
1259        // set that is not the population would silently change a stored
1260        // tree-anchor hash; no-hash resolves `recheck`, the same posture as
1261        // a failed read.
1262        let enumeration = crate::source_scope::enumerate_facet_files_reported(
1263            &join.source,
1264            &join.deny_paths,
1265            root,
1266        );
1267        if enumeration.is_partial() {
1268            None
1269        } else if preparation == Some(crate::preparation::CODE_MAP) {
1270            let files: Vec<(String, String)> = enumeration
1271                .files
1272                .into_iter()
1273                .filter(|f| root.join(f).starts_with(&path))
1274                .filter_map(|f| {
1275                    std::fs::read(root.join(&f))
1276                        .ok()
1277                        .map(|bytes| (f, String::from_utf8_lossy(&bytes).into_owned()))
1278                })
1279                .collect();
1280            Some(crate::anchor::prepared_content_hash(
1281                crate::preparation::code_map_tree_digest(&files).as_bytes(),
1282            ))
1283        } else {
1284            let files: Vec<(String, Vec<u8>)> = enumeration
1285                .files
1286                .into_iter()
1287                .filter(|f| root.join(f).starts_with(&path))
1288                .filter_map(|f| std::fs::read(root.join(&f)).ok().map(|bytes| (f, bytes)))
1289                .collect();
1290            Some(crate::anchor::prepared_content_hash(
1291                crate::preparation::plain_tree_digest(&files).as_bytes(),
1292            ))
1293        }
1294    } else {
1295        None
1296    };
1297    let observation = crate::anchor::ArtifactObservation::Present {
1298        current_hash: current_hash.clone(),
1299    };
1300    Some((
1301        crate::anchor::resolve_anchor(anchor, &observation),
1302        current_hash,
1303    ))
1304}
1305
1306/// Deterministic fingerprint of a PARSED schema for the
1307/// authoring-drift equivalence check. Compares semantic content, never
1308/// raw bytes: YAML comments (the CLI-injected editor-header lines) and
1309/// whitespace vanish at parse time, and `Schema.types` — a `HashMap`
1310/// with nondeterministic iteration order — is rendered sorted by type
1311/// name so two loads of equivalent packages always fingerprint alike.
1312pub(super) fn schema_parsed_fingerprint(schema: &memstead_schema::Schema) -> String {
1313    let mut keys: Vec<&String> = schema.types.keys().collect();
1314    keys.sort();
1315    let types: Vec<String> = keys
1316        .iter()
1317        .map(|k| format!("{k}={:?}", schema.types[k.as_str()]))
1318        .collect();
1319    format!(
1320        "{:?}|{}|{}",
1321        schema.manifest,
1322        schema.version,
1323        types.join(";")
1324    )
1325}
1326
1327fn anchor_references_path(anchor: &crate::anchor::Anchor, path: &str) -> bool {
1328    let base = anchor_base_path(&anchor.artifact);
1329    path_references(base, anchor.grain == crate::anchor::AnchorGrain::Tree, path)
1330}
1331
1332/// Whether `base` (a file path, or a tree root when `is_tree`) references
1333/// `path` — exact match, or containment for a tree.
1334fn path_references(base: &str, is_tree: bool, path: &str) -> bool {
1335    if base == path {
1336        return true;
1337    }
1338    if is_tree {
1339        let prefix = base.strip_suffix('/').unwrap_or(base);
1340        return path.starts_with(&format!("{prefix}/"));
1341    }
1342    false
1343}
1344
1345/// Join a source pointer and a source-relative artifact path into the
1346/// pointer-joined (workspace-relative) form — the decision-26 dialect
1347/// bridge. Plain string concatenation with a separator: the pointer is
1348/// workspace-relative (and may climb out via `..`), the artifact is
1349/// source-relative; no canonicalization here, the filesystem resolves it.
1350pub fn join_pointer(pointer: &str, base: &str) -> String {
1351    let pointer = pointer.trim_end_matches('/');
1352    if pointer.is_empty() || pointer == "." {
1353        base.to_string()
1354    } else {
1355        format!("{pointer}/{base}")
1356    }
1357}
1358
1359/// How a source-relative artifact id resolved ACROSS a binding's primary
1360/// sources — the cross-source counterpart of [`artifact_candidates`], which
1361/// answers only within ONE source.
1362///
1363/// The two questions are genuinely different and only this one can be
1364/// ambiguous. `artifact_candidates` settles which reading wins under a single
1365/// pointer (source-join first, workspace-relative fallback). It
1366/// takes one pointer and has no opinion on two sources both carrying
1367/// `docs/a.md`. That case has exactly one home, the exclude fold, and used to
1368/// take the first source that matched — so the source listed first in the
1369/// binding silently won, which is the wrong-target write this type exists to
1370/// prevent.
1371#[derive(Debug, Clone, PartialEq, Eq)]
1372pub enum CrossSourceArtifact {
1373    /// No source's join lands on a member of the enumerated set.
1374    Unresolved,
1375    /// Exactly one does; this is the canonical id to record.
1376    Unique(String),
1377    /// Several do. Sorted and deduplicated, so the refusal names them in a
1378    /// stable order and the caller never has to pick.
1379    Ambiguous(Vec<String>),
1380}
1381
1382/// Resolve a requested artifact id against a binding's primary sources.
1383///
1384/// `canonical_for` maps one source's base and the requested id to the
1385/// workspace-relative form, returning `None` when that form is not a member
1386/// of the enumerated source set. The caller owns that predicate because the
1387/// membership test differs by surface; what is shared, and what lives here,
1388/// is the rule that several matches are an ambiguity to refuse rather than a
1389/// choice to make silently.
1390pub fn resolve_across_sources<'a, I, F>(
1391    bases: I,
1392    requested: &str,
1393    canonical_for: F,
1394) -> CrossSourceArtifact
1395where
1396    I: IntoIterator<Item = &'a std::path::PathBuf>,
1397    F: Fn(&std::path::PathBuf, &str) -> Option<String>,
1398{
1399    let mut hits: Vec<String> = bases
1400        .into_iter()
1401        .filter_map(|base| canonical_for(base, requested))
1402        .collect();
1403    hits.sort();
1404    hits.dedup();
1405    match hits.len() {
1406        0 => CrossSourceArtifact::Unresolved,
1407        1 => CrossSourceArtifact::Unique(hits.remove(0)),
1408        _ => CrossSourceArtifact::Ambiguous(hits),
1409    }
1410}
1411
1412/// The candidate workspace-relative forms an anchor artifact could denote
1413/// under its declaring source's pointer, in the ratified priority: the source-join first, the workspace-relative form as the
1414/// fallback. **The single implementation of that rule** — resolution, the
1415/// write-time gate, and the population scope matcher all construct their
1416/// candidate set here, so one artifact cannot read differently across the
1417/// three (each site then applies its own predicate: existence for
1418/// resolution and the gate, glob membership for the matcher).
1419///
1420/// One lexical clarification rides with the rule: an artifact that climbs
1421/// (`../…`) never joins. An artifact of a source never climbs OUT of that
1422/// source, so such a path is already the workspace-relative form; joining
1423/// anyway fabricates `<ptr>/../…`, which the filesystem then resolves into a
1424/// sibling tree — a false resolution for an existence test and a false
1425/// in-scope for a `**` glob. An artifact already carrying the pointer prefix
1426/// is NOT suppressed: on a self-nested layout both readings exist and the
1427/// decision's priority — source-join wins — settles it deterministically.
1428pub fn artifact_candidates(pointer: &str, base: &str) -> Vec<String> {
1429    let pointer = pointer.trim_end_matches('/');
1430    if pointer.is_empty() || pointer == "." {
1431        return vec![base.to_string()];
1432    }
1433    if base.starts_with("../") || base == ".." {
1434        return vec![base.to_string()];
1435    }
1436    vec![format!("{pointer}/{base}"), base.to_string()]
1437}