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