memstead_base/anchor.rs
1//! Anchors — engine-owned durable provenance records tying an entity to
2//! the source artifacts it describes.
3//!
4//! An anchor is the projection pipeline's single new load-bearing
5//! primitive: which artifact (in the medium's own namespace), at which
6//! *grain*, under which *provenance class*, at which medium-typed
7//! *version*, hashed over the **prepared** artifact form (never raw
8//! bytes) where the class carries hash semantics, and the medium's
9//! declared *hash stability* — so an unstable-source hash break resolves
10//! as [`AnchorState::Recheck`], not [`AnchorState::Drifted`].
11//!
12//! ## Naming
13//!
14//! The `Anchor*` family is deliberately distinct from the three
15//! provenance-adjacent type families already in the tree — it never
16//! reuses `Provenance` / `ProvenanceKind` (the mutation-log record in
17//! [`crate::provenance`]), nor `ArchiveProvenance` / `EntityProvenance` /
18//! `History` (the authoring-provenance payload in
19//! [`memstead_schema::archive_provenance`]). Those stay; anchors are a
20//! separate concern (source→entity provenance, not mutation history nor
21//! authoring lineage).
22//!
23//! ## Wire vocabulary (fixed contract)
24//!
25//! - provenance classes: `anchored` / `derived` / `authored` /
26//! `informed-by`
27//! - grains: `span` / `file` / `tree` / `url` / `entity`
28//! - hash stability: `stable` / `unstable`
29//! - resolution states: `resolves` / `drifted` / `recheck` / `orphaned`
30//!
31//! The Rust identifiers around this vocabulary are the implementer's
32//! choice; the wire strings are the contract and are locked by the
33//! `*_wire_strings_are_stable` tests below.
34//!
35//! ## Storage
36//!
37//! Anchors persist in an engine-owned sidecar on the mem branch under
38//! [`ANCHOR_SIDECAR_PATH`] (`.memstead/anchors.json`) — see
39//! [`AnchorSidecar`]. The sidecar is written only through engine commits
40//! (the [`crate::backend::MemBackend`] sidecar seam); every external
41//! reader already filters the `.memstead/` namespace, so an anchor-only
42//! commit yields no entity deltas and does not participate in `_hash`.
43//!
44//! ## Scope of this module
45//!
46//! Pure value types, wire (de)serialisation, validation (typed
47//! `INVALID_ANCHOR` refusals with recovery detail), and the resolution
48//! model. No storage or IO lives here — the backend seam and the
49//! mutation/CLI wiring consume these types.
50
51use std::collections::BTreeMap;
52
53use serde::{Deserialize, Serialize};
54
55/// Mem-relative path of the engine-owned anchors sidecar on the mem
56/// branch. Lives under the `.memstead/` umbrella every external reader
57/// already treats as non-entity, so an anchor-only commit produces zero
58/// entity deltas.
59pub const ANCHOR_SIDECAR_PATH: &str = ".memstead/anchors.json";
60
61/// The sidecar document schema version every sidecar is written at unless
62/// a row needs a newer one. Version 2 added the per-row `last_observed`
63/// record; version 1 files load unchanged (the field is absent) and are
64/// rewritten as version 2 on the next sidecar write.
65pub const ANCHOR_SIDECAR_VERSION: u32 = 2;
66
67/// The version a sidecar carries once any row holds a quoted `span` (with
68/// its `span_hash`) or a `pinned` hash source: the two things an engine
69/// that reads only versions 1 and 2 cannot understand. The version moves
70/// up only when such a row is written ([`AnchorSidecar::required_version`])
71/// and a sidecar without one keeps [`ANCHOR_SIDECAR_VERSION`], so nothing
72/// written before spans existed changes its bytes. An older engine reading
73/// a version-3 sidecar refuses it typed (`unsupported anchors sidecar
74/// version 3`); it never loads the rows with the span dropped.
75pub const ANCHOR_SIDECAR_SPAN_VERSION: u32 = 3;
76
77/// Every sidecar version this engine reads. Anything else refuses typed:
78/// a document written by a later engine is not parsed optimistically.
79pub const ANCHOR_SIDECAR_VERSIONS_READ: &[u32] = &[1, 2, 3];
80
81/// Stable typed error code returned when an `anchors[]` element is
82/// malformed. Mirrors the engine's other typed-envelope codes; the whole
83/// mutation refuses and the entity is not written.
84pub const INVALID_ANCHOR_CODE: &str = "INVALID_ANCHOR";
85
86/// The pinned sentinel a publish-time redaction writes into every
87/// artifact reference (`artifact`, `derived_from` entries). A fixed,
88/// visibly-artificial form rather than an empty string: the anchor entry
89/// stays readable (class, counts, `at_version`, hash — the trust
90/// metadata), while the reference discloses nothing — and an empty
91/// reference stays what it always was, malformed
92/// ([`AnchorSidecar::validate_artifact_references`]).
93pub const REDACTED_ARTIFACT_SENTINEL: &str = "[redacted]";
94
95// ---------------------------------------------------------------------------
96// Provenance class
97// ---------------------------------------------------------------------------
98
99/// The epistemic standing of an anchor — how the entity relates to the
100/// artifact it references.
101///
102/// - [`Anchored`](Self::Anchored) — the entity directly reflects specific
103/// artifact content (carries hash semantics).
104/// - [`Derived`](Self::Derived) — the entity was computed/synthesised from
105/// one or more input artifacts (carries hash semantics; lists inputs).
106/// - [`Authored`](Self::Authored) — a human/agent authored the entity with
107/// the artifact in view (no hash semantics; excluded from drift
108/// adjudication).
109/// - [`InformedBy`](Self::InformedBy) — the artifact informed the entity
110/// without a content-fidelity claim (no hash semantics; excluded from
111/// drift adjudication).
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "kebab-case")]
114pub enum AnchorProvenanceClass {
115 Anchored,
116 Derived,
117 Authored,
118 InformedBy,
119}
120
121impl AnchorProvenanceClass {
122 /// Every wire string, in declaration order — the allowed set a
123 /// refusal echoes for recovery.
124 pub const WIRE_VALUES: &'static [&'static str] =
125 &["anchored", "derived", "authored", "informed-by"];
126
127 /// Stable wire form.
128 pub fn as_wire(&self) -> &'static str {
129 match self {
130 AnchorProvenanceClass::Anchored => "anchored",
131 AnchorProvenanceClass::Derived => "derived",
132 AnchorProvenanceClass::Authored => "authored",
133 AnchorProvenanceClass::InformedBy => "informed-by",
134 }
135 }
136
137 /// Inverse of [`Self::as_wire`]; `None` for an unknown string so the
138 /// validator can refuse it typed rather than misclassify.
139 pub fn from_wire(s: &str) -> Option<Self> {
140 match s {
141 "anchored" => Some(AnchorProvenanceClass::Anchored),
142 "derived" => Some(AnchorProvenanceClass::Derived),
143 "authored" => Some(AnchorProvenanceClass::Authored),
144 "informed-by" => Some(AnchorProvenanceClass::InformedBy),
145 _ => None,
146 }
147 }
148
149 /// Whether this class carries hash semantics. `anchored` and
150 /// `derived` assert content fidelity and participate in hash-drift
151 /// adjudication; `authored` and `informed-by` do not — a content
152 /// change under them produces no drift state, and supplying a hash on
153 /// them is a validation refusal.
154 pub fn is_hash_bearing(&self) -> bool {
155 matches!(
156 self,
157 AnchorProvenanceClass::Anchored | AnchorProvenanceClass::Derived
158 )
159 }
160}
161
162// ---------------------------------------------------------------------------
163// Grain
164// ---------------------------------------------------------------------------
165
166/// The granularity of the artifact reference an anchor carries.
167///
168/// `span` / `file` / `tree` select within a path-shaped namespace; `url`
169/// selects a web resource; `entity` selects another mem's entity. The
170/// medium-capability matrix ([`crate::binding::medium_capabilities`])
171/// decides which grains a given medium's namespace can support — a
172/// mismatch (e.g. `span` on a `url`-namespace medium) refuses typed at
173/// validation.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "lowercase")]
176pub enum AnchorGrain {
177 Span,
178 File,
179 Tree,
180 Url,
181 Entity,
182}
183
184impl AnchorGrain {
185 /// Every wire string, in declaration order.
186 pub const WIRE_VALUES: &'static [&'static str] = &["span", "file", "tree", "url", "entity"];
187
188 /// Stable wire form.
189 pub fn as_wire(&self) -> &'static str {
190 match self {
191 AnchorGrain::Span => "span",
192 AnchorGrain::File => "file",
193 AnchorGrain::Tree => "tree",
194 AnchorGrain::Url => "url",
195 AnchorGrain::Entity => "entity",
196 }
197 }
198
199 /// Inverse of [`Self::as_wire`]; `None` for an unknown string.
200 pub fn from_wire(s: &str) -> Option<Self> {
201 match s {
202 "span" => Some(AnchorGrain::Span),
203 "file" => Some(AnchorGrain::File),
204 "tree" => Some(AnchorGrain::Tree),
205 "url" => Some(AnchorGrain::Url),
206 "entity" => Some(AnchorGrain::Entity),
207 _ => None,
208 }
209 }
210
211 /// Whether this grain can be expressed in the medium's declared anchor
212 /// namespace (the `anchor_namespace` string from the E2 capability
213 /// matrix: `path` / `path+commit` / `entity` / `url`).
214 ///
215 /// - `span` / `file` / `tree` require a path-shaped namespace
216 /// (`path` or `path+commit`);
217 /// - `url` is admitted beside every namespace: a URL is an absolute
218 /// reference that never enters a path or entity namespace, so it
219 /// collides with nothing there — and the engine never observes it
220 /// itself, so no medium capability is claimed by admitting it;
221 /// - `entity` requires the `entity` namespace.
222 pub fn supported_by_namespace(&self, anchor_namespace: &str) -> bool {
223 let path_shaped = matches!(anchor_namespace, "path" | "path+commit");
224 match self {
225 AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => path_shaped,
226 AnchorGrain::Url => true,
227 AnchorGrain::Entity => anchor_namespace == "entity",
228 }
229 }
230
231 /// Whether this grain selects within a path-shaped namespace.
232 pub fn is_path_shaped(&self) -> bool {
233 matches!(
234 self,
235 AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree
236 )
237 }
238}
239
240// ---------------------------------------------------------------------------
241// Hash stability
242// ---------------------------------------------------------------------------
243
244/// The medium's declared hash stability — whether a change in the
245/// prepared-content hash is a reliable drift signal.
246///
247/// A `stable` medium's hash break resolves [`AnchorState::Drifted`]; an
248/// `unstable` medium's hash break resolves [`AnchorState::Recheck`]
249/// (the hash may have moved for reasons unrelated to the entity's claim,
250/// so the engine flags it for re-examination rather than asserting drift).
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
252#[serde(rename_all = "lowercase")]
253pub enum AnchorHashStability {
254 Stable,
255 Unstable,
256}
257
258impl AnchorHashStability {
259 /// Every wire string.
260 pub const WIRE_VALUES: &'static [&'static str] = &["stable", "unstable"];
261
262 /// Stable wire form.
263 pub fn as_wire(&self) -> &'static str {
264 match self {
265 AnchorHashStability::Stable => "stable",
266 AnchorHashStability::Unstable => "unstable",
267 }
268 }
269
270 /// Inverse of [`Self::as_wire`]; `None` for an unknown string.
271 pub fn from_wire(s: &str) -> Option<Self> {
272 match s {
273 "stable" => Some(AnchorHashStability::Stable),
274 "unstable" => Some(AnchorHashStability::Unstable),
275 _ => None,
276 }
277 }
278}
279
280// ---------------------------------------------------------------------------
281// Medium-typed version
282// ---------------------------------------------------------------------------
283
284/// A medium-typed pinned version the anchor was recorded against.
285///
286/// Which variant applies follows from the medium's namespace: a git /
287/// `path+commit` medium pins a [`Commit`](Self::Commit); a graph / `entity`
288/// medium pins a [`Snapshot`](Self::Snapshot) token; a web / `url` medium
289/// pins an [`Etag`](Self::Etag). A plain `path` medium (mtime change
290/// signal, no retrievable version) records **absent** — represented as
291/// `None` on [`Anchor::at_version`], never a variant here.
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
293#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
294pub enum AnchorVersion {
295 /// A git commit id (`path+commit` / git namespace).
296 Commit(String),
297 /// A graph snapshot token (`entity` namespace).
298 Snapshot(String),
299 /// A web ETag (`url` namespace).
300 Etag(String),
301}
302
303// ---------------------------------------------------------------------------
304// Anchor
305// ---------------------------------------------------------------------------
306
307/// One durable anchor record: an entity's provenance tie to a single
308/// source artifact.
309///
310/// This is the persisted + read shape. Malformed wire input is refused
311/// upstream via [`AnchorInput::validate`], which produces this strict type
312/// only when every rule holds.
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
314pub struct Anchor {
315 /// Artifact reference in the medium's own namespace — a repo-relative
316 /// path, a `path@commit`, a URL, or an entity id, interpreted per
317 /// [`Self::grain`] and the medium.
318 pub artifact: String,
319 /// The granularity of [`Self::artifact`].
320 pub grain: AnchorGrain,
321 /// The anchor's epistemic standing.
322 pub class: AnchorProvenanceClass,
323 /// The medium-typed pinned version, or `None` when the medium has no
324 /// retrievable version (plain `path` / mtime).
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub at_version: Option<AnchorVersion>,
327 /// Content hash over the **prepared** artifact form (never raw bytes),
328 /// present only when [`Self::class`] carries hash semantics. `None`
329 /// for `authored` / `informed-by`.
330 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub hash: Option<String>,
332 /// The medium's declared hash stability — governs whether a hash break
333 /// resolves `drifted` or `recheck`.
334 pub hash_stability: AnchorHashStability,
335 /// For a `derived` class: the input artifact refs the entity was
336 /// derived from. Empty for every other class.
337 #[serde(default, skip_serializing_if = "Vec::is_empty")]
338 pub derived_from: Vec<String>,
339 /// `hash(D)` of the binding that produced this anchor, when a
340 /// binding produced it. `None` for a manually-authored anchor with no
341 /// producing binding.
342 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub binding: Option<String>,
344 /// The NAME of the source (as declared in the producing binding's
345 /// `sources[]`) that produced this anchor — so a discovery run can
346 /// be measured per entry point. Optional and additive: pre-existing
347 /// sidecars load unchanged and are never backfilled (a guessed
348 /// provenance is worse than an absent one). Validated against the
349 /// producing binding's declared names only when [`Self::binding`]
350 /// still resolves in the workspace.
351 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub source: Option<String>,
353 /// The verbatim words this row quotes from the artifact (sidecar
354 /// version 3), on the `url`, `span` and `file` grains. A row carrying a
355 /// span is adjudicated on the span's PRESENCE in the observed text (in
356 /// the canonical span form, [`crate::preparation::canonical_span_form`]),
357 /// not on the document hash: it resolves while the words stand, whatever
358 /// else on the page changed, and reads [`AnchorState::SpanAbsent`] once
359 /// they are gone. Part of the row's identity beside artifact, grain and
360 /// class, so several spans on one document are several rows. `None` on
361 /// every row written before spans existed, which adjudicates exactly as
362 /// before.
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub span: Option<String>,
365 /// The hash over the canonical form of [`Self::span`], computed by the
366 /// engine at write (a caller never supplies it). Present exactly when
367 /// `span` is.
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub span_hash: Option<String>,
370 /// A row whose locator or quoted span could NOT be checked against the
371 /// artifact at write time (consistency-sweep 03/03). The write path
372 /// deliberately reads no source content, so the check is possible only
373 /// where the caller supplied `content`; elsewhere the anchor is accepted
374 /// and this records that its span is unverified, rather than letting a
375 /// later surface report it as adjudicated. Set on a `span`-grain row
376 /// with an unchecked line-range locator, and on any row whose `span`
377 /// was written without `content`; cleared once a recorded observation
378 /// adjudicates the span. Serialized only when true, so an existing
379 /// sidecar is unchanged.
380 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
381 pub span_unvalidated: bool,
382 /// Who established this row's [`Self::hash`] baseline. `None` on every
383 /// row written before the field existed, which is honest: the baseline's
384 /// origin was not recorded then and guessing it would be worse than
385 /// admitting it. Set at write and at backfill from then on, so a reader
386 /// can tell an author-pinned baseline from an engine-inferred one.
387 #[serde(default, skip_serializing_if = "Option::is_none")]
388 pub hash_source: Option<AnchorHashSource>,
389 /// The most recent observation recorded for this row (sidecar version
390 /// 2): when it was made, the prepared-content hash it saw, and the state
391 /// it resolved. Written for grains the engine cannot observe itself —
392 /// a `url` row adjudicated from an observer-supplied observation — so
393 /// the row can age visibly (`unobserved for N days`) instead of resting
394 /// in `unobserved` forever. Path and entity rows are observed live on
395 /// every pass and carry none. Absent on every version-1 row.
396 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub last_observed: Option<AnchorObservation>,
398}
399
400/// One recorded observation of an anchor's artifact (the `last_observed`
401/// record of a sidecar row).
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403pub struct AnchorObservation {
404 /// When the observation was made — second-granularity ISO-8601 UTC
405 /// (`YYYY-MM-DDTHH:MM:SSZ`), as supplied by the observer or stamped by
406 /// the engine at recording time.
407 pub at: String,
408 /// The prepared-content hash the observation saw; `None` when the
409 /// observer reported the artifact absent.
410 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub hash: Option<String>,
412 /// The state the row resolved to against that observation.
413 pub state: AnchorState,
414}
415
416/// Who established an anchor's hash baseline. A baseline that resets with no trace makes drift
417/// unfalsifiable, so the origin is recorded rather than inferred.
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
419#[serde(rename_all = "kebab-case")]
420pub enum AnchorHashSource {
421 /// The writer supplied the hash, or the content the engine hashed.
422 Author,
423 /// A completed verify filled a hash-less row from what it observed.
424 Backfill,
425 /// The engine hashed the target as it stood at write time: an
426 /// `entity`-grain row of a hash-bearing class written without a hash
427 /// while its target was loaded takes the target's prepared hash then,
428 /// so the next verify reads it against the target as it was when the
429 /// claim was made, never against a later state. Sidecar version 3.
430 Pinned,
431}
432
433impl Anchor {
434 /// Whether `other`, as a caller supplied it, restates this stored row:
435 /// equal on every field a caller writes (artifact, grain, class,
436 /// version, stability, derivation, binding, source, span validation)
437 /// and, when the caller named a hash, on the hash too. The engine-set
438 /// fields (`hash_source`, `last_observed`, a backfilled hash the caller
439 /// did not name) do not count: a re-pin that restates the row is a
440 /// no-op, not a fresh baseline.
441 pub fn same_as_supplied(&self, other: &Anchor) -> bool {
442 self.artifact == other.artifact
443 && self.grain == other.grain
444 && self.class == other.class
445 && self.at_version == other.at_version
446 && self.hash_stability == other.hash_stability
447 && self.derived_from == other.derived_from
448 && self.binding == other.binding
449 && self.source == other.source
450 && same_span(self.span.as_deref(), other.span.as_deref())
451 && self.span_unvalidated == other.span_unvalidated
452 && other
453 .hash
454 .as_ref()
455 .is_none_or(|h| Some(h) == self.hash.as_ref())
456 }
457}
458
459/// Whether two optional spans name the same words: both absent, or both
460/// present and equal in the canonical span form. The one span identity
461/// rule, shared by the merge, the no-op check, the duplicate refusal and
462/// the unset selector, so a span re-sent with different line breaks or
463/// quote marks is the same row everywhere.
464pub fn same_span(a: Option<&str>, b: Option<&str>) -> bool {
465 match (a, b) {
466 (None, None) => true,
467 (Some(a), Some(b)) => {
468 crate::preparation::canonical_span_form(a) == crate::preparation::canonical_span_form(b)
469 }
470 _ => false,
471 }
472}
473
474impl AnchorHashSource {
475 pub fn as_wire(self) -> &'static str {
476 match self {
477 AnchorHashSource::Author => "author",
478 AnchorHashSource::Backfill => "backfill",
479 AnchorHashSource::Pinned => "pinned",
480 }
481 }
482}
483
484// ---------------------------------------------------------------------------
485// Span locators
486// ---------------------------------------------------------------------------
487
488/// What a `span` anchor's locator (everything after the first `#`) selects.
489///
490/// Two forms are legal and the distinction is not cosmetic. A LINE RANGE is
491/// checkable against content the write path already holds; a UNIT KEY is a
492/// delivery preparation's own key (`dated-entries` writes
493/// `<path>#<iso-stamp>`), whose validity only that preparation can judge, and
494/// which the existing unit-absent refusal already covers where content is
495/// supplied. Anything the engine can check, it checks; anything it cannot, it
496/// records as unchecked.
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498pub enum SpanLocator<'a> {
499 /// `L<start>` or `L<start>-L<end>`, 1-based and inclusive.
500 Lines { start: usize, end: usize },
501 /// A preparation's delivery-unit key, opaque here.
502 Unit(&'a str),
503}
504
505/// Parse a `span` artifact reference's locator, or say why it cannot be one.
506/// `Ok(None)` means the reference carries no locator at all.
507///
508/// **No locator is not a refusal**, and that is a deliberate line. A
509/// `span`-grain reference naming a bare path addresses its whole file, which
510/// is what a span's hash covers anyway with no preparation declared, and such
511/// anchors are written today. Refusing them would be a new wall across a
512/// working flow, which the no-new-walls rule forbids.
513///
514/// The refusals are the shapes that can never address anything: an EMPTY
515/// locator (`path#`, which announces a span and then names none), and a
516/// locator that announces itself as a line range by its `L` prefix and then
517/// contradicts itself (no digits, a zero line, an end before its start). A
518/// locator that does not look like a line range is a unit key and is accepted
519/// here, because this function cannot know a preparation's key grammar and
520/// refusing what it cannot judge would break every `dated-entries` anchor.
521pub fn parse_span_locator(artifact: &str) -> Result<Option<SpanLocator<'_>>, &'static str> {
522 let locator = match artifact.split_once('#') {
523 None => return Ok(None),
524 Some((_, loc)) if loc.trim().is_empty() => {
525 return Err("the span locator after `#` is empty");
526 }
527 Some((_, loc)) => loc,
528 };
529 // Only an `L`-prefixed locator claims to be a line range. Everything else
530 // is a unit key and is not this function's to judge.
531 let looks_like_lines = locator.starts_with('L')
532 && locator[1..]
533 .chars()
534 .next()
535 .is_some_and(|c| c.is_ascii_digit());
536 if !looks_like_lines {
537 return Ok(Some(SpanLocator::Unit(locator)));
538 }
539 let (start_raw, end_raw) = match locator.split_once('-') {
540 None => (locator, locator),
541 Some((a, b)) => (a, b),
542 };
543 let num = |part: &str| -> Option<usize> {
544 part.strip_prefix('L')
545 .filter(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
546 .and_then(|d| d.parse::<usize>().ok())
547 };
548 let (Some(start), Some(end)) = (num(start_raw), num(end_raw)) else {
549 return Err("a line-range span locator must read `L<start>` or `L<start>-L<end>`");
550 };
551 if start == 0 {
552 return Err("line numbers are 1-based, so `L0` addresses nothing");
553 }
554 if end < start {
555 return Err("a line-range span locator ends before it starts");
556 }
557 Ok(Some(SpanLocator::Lines { start, end }))
558}
559
560// ---------------------------------------------------------------------------
561// Validation
562// ---------------------------------------------------------------------------
563
564/// A permissive wire-shaped anchor element as it arrives on a mutation's
565/// `anchors[]` parameter. All fields are optional / string-typed so an
566/// unknown class or grain surfaces as a typed [`AnchorValidationError`]
567/// with recovery detail rather than an opaque serde failure. Call
568/// [`Self::validate`] to obtain a strict [`Anchor`].
569#[derive(Debug, Clone, Default, Serialize, Deserialize)]
570pub struct AnchorInput {
571 #[serde(default)]
572 pub artifact: Option<String>,
573 #[serde(default)]
574 pub grain: Option<String>,
575 #[serde(default)]
576 pub class: Option<String>,
577 #[serde(default)]
578 pub at_version: Option<AnchorVersion>,
579 #[serde(default)]
580 pub hash: Option<String>,
581 /// The observed artifact CONTENT (UTF-8 text), for the engine to compute
582 /// `hash` from through its preparation registry
583 /// ([`crate::preparation::supplied_content_hash`]) — the write-time
584 /// observation for a grain the engine cannot observe itself: a `url`
585 /// anchor, because the engine never fetches. Accepted for the `span` /
586 /// `file` / `url` grains; mutually exclusive with `hash`; refused on a
587 /// non-hash class and on the `entity` / `tree` grains, whose prepared
588 /// form is never computed from supplied bytes.
589 #[serde(default)]
590 pub content: Option<String>,
591 /// The verbatim words the entity quotes from the artifact. Accepted on
592 /// the `url` / `span` / `file` grains of a hash-bearing class; refused
593 /// beside `hash` (the engine computes the span hash itself), on the
594 /// `entity` / `tree` grains (never prepared from supplied text), and
595 /// when empty. With `content`, the write refuses unless the span occurs
596 /// in it (canonical form); without `content`, the row is recorded with
597 /// the span unverified.
598 #[serde(default)]
599 pub span: Option<String>,
600 #[serde(default)]
601 pub hash_stability: Option<String>,
602 #[serde(default)]
603 pub derived_from: Option<Vec<String>>,
604 #[serde(default)]
605 pub binding: Option<String>,
606 #[serde(default)]
607 pub source: Option<String>,
608}
609
610/// A permissive wire-shaped `anchors_unset[]` element — an explicit
611/// removal selector on the update surface. Each entry names an `artifact`
612/// and may narrow by `grain` and/or `class`; a bare artifact selects every
613/// anchor on it. String-typed like [`AnchorInput`] so an unknown grain or
614/// class refuses typed (`INVALID_ANCHOR`) rather than silently selecting
615/// nothing forever. Call [`Self::validate`] to obtain a strict
616/// [`AnchorUnset`].
617#[derive(Debug, Clone, Default, Serialize, Deserialize)]
618pub struct AnchorUnsetInput {
619 #[serde(default)]
620 pub artifact: Option<String>,
621 #[serde(default)]
622 pub grain: Option<String>,
623 #[serde(default)]
624 pub class: Option<String>,
625 /// Narrow to the one row quoting this span (compared in the canonical
626 /// span form). Absent selects rows with or without a span.
627 #[serde(default)]
628 pub span: Option<String>,
629}
630
631impl AnchorUnsetInput {
632 /// Validate this wire element into a strict [`AnchorUnset`], or refuse
633 /// typed. Rules: artifact present and non-empty; grain / class, when
634 /// supplied, must be known wire strings (absent means "any").
635 pub fn validate(&self) -> Result<AnchorUnset, AnchorValidationError> {
636 let artifact = self
637 .artifact
638 .as_deref()
639 .map(str::trim)
640 .filter(|s| !s.is_empty())
641 .map(str::to_string)
642 .ok_or(AnchorValidationError::MissingArtifact)?;
643 let grain = match self.grain.as_deref() {
644 None => None,
645 Some(s) => Some(AnchorGrain::from_wire(s).ok_or_else(|| {
646 AnchorValidationError::UnknownGrain {
647 got: Some(s.to_string()),
648 allowed: AnchorGrain::WIRE_VALUES,
649 }
650 })?),
651 };
652 let class = match self.class.as_deref() {
653 None => None,
654 Some(s) => Some(AnchorProvenanceClass::from_wire(s).ok_or_else(|| {
655 AnchorValidationError::UnknownClass {
656 got: Some(s.to_string()),
657 allowed: AnchorProvenanceClass::WIRE_VALUES,
658 }
659 })?),
660 };
661 let span = self
662 .span
663 .as_deref()
664 .map(crate::preparation::canonical_span_form)
665 .filter(|s| !s.is_empty());
666 Ok(AnchorUnset {
667 artifact,
668 grain,
669 class,
670 span,
671 })
672 }
673}
674
675/// A validated explicit-removal selector: which of an entity's anchors an
676/// update's `anchors_unset[]` entry removes. Selection is by artifact,
677/// optionally narrowed by grain and/or class; a selector matching nothing
678/// is a no-op (removal is idempotent — its job in recovery flows is "make
679/// sure this is gone").
680#[derive(Debug, Clone, PartialEq, Eq)]
681pub struct AnchorUnset {
682 /// Artifact reference to remove anchors from, exactly as stored.
683 pub artifact: String,
684 /// When present, only anchors of this grain are removed.
685 pub grain: Option<AnchorGrain>,
686 /// When present, only anchors of this class are removed.
687 pub class: Option<AnchorProvenanceClass>,
688 /// When present (canonical span form), only the row quoting this span
689 /// is removed; absent, span rows and span-less rows alike are selected.
690 pub span: Option<String>,
691}
692
693impl AnchorUnset {
694 /// Whether this selector removes `anchor`.
695 pub fn matches(&self, anchor: &Anchor) -> bool {
696 anchor.artifact == self.artifact
697 && self.grain.is_none_or(|g| anchor.grain == g)
698 && self.class.is_none_or(|c| anchor.class == c)
699 && self.span.as_deref().is_none_or(|s| {
700 anchor
701 .span
702 .as_deref()
703 .is_some_and(|have| crate::preparation::canonical_span_form(have) == s)
704 })
705 }
706}
707
708/// A typed `INVALID_ANCHOR` refusal. The whole mutation refuses and the
709/// entity is not written; [`Self::detail`] carries the recovery payload
710/// (offending value + allowed set) the agent fixes from.
711#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
712pub enum AnchorValidationError {
713 /// Provenance class is absent or not one of the allowed wire strings.
714 #[error("unknown anchor provenance class {got:?}; allowed: {}", allowed.join(", "))]
715 UnknownClass {
716 got: Option<String>,
717 allowed: &'static [&'static str],
718 },
719 /// Grain is absent or not one of the allowed wire strings.
720 #[error("unknown anchor grain {got:?}; allowed: {}", allowed.join(", "))]
721 UnknownGrain {
722 got: Option<String>,
723 allowed: &'static [&'static str],
724 },
725 /// Hash stability, when supplied, is not an allowed wire string.
726 #[error("unknown anchor hash stability {got:?}; allowed: {}", allowed.join(", "))]
727 UnknownHashStability {
728 got: String,
729 allowed: &'static [&'static str],
730 },
731 /// The artifact reference is missing or empty.
732 #[error("anchor is missing its artifact reference")]
733 MissingArtifact,
734 /// A content hash (or content to hash) was supplied on a class that
735 /// carries no hash semantics (`authored` / `informed-by`).
736 #[error("anchor class '{class}' carries no hash semantics — a content hash is not permitted")]
737 HashOnNonHashClass { class: &'static str },
738 /// Both `hash` and `content` were supplied — the engine computes the
739 /// hash from content, so a supplied hash beside it is ambiguous.
740 #[error(
741 "anchor supplies both `hash` and `content`; supply one — the engine computes the hash from `content`"
742 )]
743 ContentAndHash,
744 /// `content` was supplied for a grain whose prepared form is never
745 /// computed from supplied bytes: `entity` (computed from the live graph)
746 /// or `tree` (whose prepared form, under a code map, is enumerated by
747 /// the engine).
748 #[error(
749 "anchor grain '{grain}' does not accept `content`: its prepared form is not computed \
750 from supplied bytes (accepted for span / file / url)"
751 )]
752 ContentNotAcceptedForGrain { grain: &'static str },
753 /// `content` was supplied for a `<path>#<key>` unit under a delivery
754 /// preparation, but the content yields no unit with that key.
755 #[error(
756 "anchor artifact {artifact:?} names a delivery unit the supplied `content` does not \
757 yield; supply the whole file's content, or address a unit it contains"
758 )]
759 UnitAbsentFromContent { artifact: String },
760 /// A `span`-grain anchor whose locator is missing, empty, or announces a
761 /// line range and then contradicts itself. Refused at write: such a row
762 /// can never address anything, and accepting it produces an anchor that
763 /// is unadjudicable from birth.
764 #[error("anchor artifact {artifact:?} is not a usable span reference: {reason}")]
765 SpanLocatorUnusable {
766 artifact: String,
767 reason: &'static str,
768 },
769 /// A `span`-grain anchor whose line range lies outside the content the
770 /// caller supplied. Only fires where content is in hand — the write path
771 /// reads no source, and where it cannot check, the row records that
772 /// instead (`span_unvalidated`).
773 #[error(
774 "anchor artifact {artifact:?} names lines the supplied `content` does not have \
775 (it has {lines} line(s)); address a range the artifact contains"
776 )]
777 SpanOutsideContent { artifact: String, lines: usize },
778 /// One payload named the same `(artifact, grain, class, span)` identity
779 /// twice. That identity is the sidecar's merge key, so the later
780 /// occurrence silently replaced the earlier one and the caller was never
781 /// told an anchor it wrote had gone missing. A LATER call replacing the
782 /// stored row is unaffected: the unit of this refusal is one payload.
783 #[error(
784 "the anchors payload names {artifact:?} at grain `{grain}` and class `{class}`{} more \
785 than once; that identity is one row, so the repeats would silently collapse to the \
786 last one: send it once, or vary the grain, class or span",
787 span.as_deref().map(|s| format!(" with span {s:?}")).unwrap_or_default()
788 )]
789 DuplicateAnchorTriple {
790 artifact: String,
791 grain: &'static str,
792 class: &'static str,
793 span: Option<String>,
794 },
795 /// Both `span` and `hash` were supplied. The engine computes a span
796 /// row's hashes itself (the span hash from the span, the document hash
797 /// from `content`), so a supplied hash beside a span is ambiguous.
798 #[error(
799 "anchor supplies both `span` and `hash`; the engine computes a span row's hashes \
800 itself: supply the span with `content`, or a hash without a span"
801 )]
802 SpanAndHash,
803 /// A `span` that is empty after canonicalisation names no words and can
804 /// never be found.
805 #[error(
806 "anchor `span` is empty: a quoted span must carry at least one non-whitespace character"
807 )]
808 SpanEmpty,
809 /// A `span` was supplied on a grain whose prepared form is never computed
810 /// from supplied text (`entity`, `tree`), so the words could never be
811 /// looked for.
812 #[error(
813 "anchor grain '{grain}' does not accept `span`: its prepared form is never computed \
814 from supplied text (accepted for url / span / file)"
815 )]
816 SpanNotAcceptedForGrain { grain: &'static str },
817 /// The canonical form of the supplied `span` does not occur in the
818 /// canonical form of the supplied `content`: the observation the writer
819 /// handed over does not carry the words the entity quotes.
820 #[error(
821 "anchor artifact {artifact:?}: the span {span:?} does not occur in the supplied \
822 `content` (compared in the canonical span form: NFC, whitespace runs to one space, \
823 soft hyphens and line-end hyphens removed, typographic quotes, dashes and ligatures \
824 to ASCII; everything else exact); quote the words as the artifact carries them"
825 )]
826 SpanAbsentFromContent { artifact: String, span: String },
827 /// A `source` was supplied but is empty after trimming — a source
828 /// name, when present, must be one of the producing binding's
829 /// declared names, and an empty string can never be one.
830 #[error("anchor `source`, when present, must be a non-empty source name")]
831 EmptySource,
832 /// The anchor's `source` is not among the sources declared by its
833 /// own (resolvable) producing binding. Carries the declared names
834 /// as the recovery payload. Only fires when the `binding` hash
835 /// still resolves in this workspace — an orphaned or since-edited
836 /// binding accepts any non-empty name, deliberately: a legacy
837 /// anchor whose binding was renamed keeps writing as long as its
838 /// artifact reference is alive under the workspace-relative
839 /// fallback (`mem_commands::source_dialect_anchors_join_fallback_collide_and_refuse`).
840 #[error(
841 "anchor `source` {got:?} is not declared by the anchor's producing binding; \
842 declared sources: {}",
843 declared.join(", ")
844 )]
845 SourceNotDeclared { got: String, declared: Vec<String> },
846 /// A path-grain artifact reference that resolves under NO candidate
847 /// join — neither source-relative (joined onto the declaring source's
848 /// pointer, decision 26) nor workspace-relative. Refused at write time
849 /// so the mutation never stores a silently dead (orphaned-at-birth)
850 /// reference; the payload names every candidate tried so the agent can
851 /// fix the dialect.
852 #[error(
853 "anchor artifact {artifact:?} resolves under no candidate path (tried: {}); artifact \
854 paths are source-relative (joined onto the source's pointer) or workspace-relative — \
855 write the path exactly as the brief lists it",
856 candidates.join(", ")
857 )]
858 ArtifactUnresolvable {
859 artifact: String,
860 candidates: Vec<String>,
861 },
862 /// The grain cannot be expressed in the medium's anchor namespace
863 /// (per the E2 capability matrix), e.g. `span` on a non-path medium.
864 #[error(
865 "anchor grain '{grain}' is unsupported by a '{medium_type}' medium: its \
866 '{anchor_namespace}' namespace does not admit that grain"
867 )]
868 GrainNamespaceUnsupported {
869 grain: &'static str,
870 medium_type: String,
871 anchor_namespace: &'static str,
872 },
873 /// A path-shaped grain (`span` / `file` / `tree`) names a URL. A URL
874 /// never enters a path namespace: the web resource is addressed by the
875 /// `url` grain, and a page coordinate inside it is not a path span.
876 #[error(
877 "anchor grain '{grain}' selects within a path namespace, but its artifact '{artifact}' is a URL — a URL never enters a path namespace; use `grain: url` for the resource"
878 )]
879 PathGrainOnUrlArtifact {
880 grain: &'static str,
881 artifact: String,
882 },
883}
884
885/// Whether an artifact string is URL-shaped (`<scheme>://…`).
886pub fn looks_like_url(artifact: &str) -> bool {
887 let Some((scheme, rest)) = artifact.split_once("://") else {
888 return false;
889 };
890 !rest.is_empty()
891 && scheme
892 .chars()
893 .next()
894 .is_some_and(|c| c.is_ascii_alphabetic())
895 && scheme
896 .chars()
897 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
898}
899
900impl AnchorValidationError {
901 /// The stable typed code — always [`INVALID_ANCHOR_CODE`].
902 pub fn code(&self) -> &'static str {
903 INVALID_ANCHOR_CODE
904 }
905
906 /// Structured recovery detail for the typed envelope: the offending
907 /// field, its bad value, and the allowed set where one applies.
908 pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
909 let mut d = BTreeMap::new();
910 match self {
911 AnchorValidationError::UnknownClass { got, allowed } => {
912 d.insert("field".into(), "class".into());
913 d.insert("got".into(), serde_json::json!(got));
914 d.insert("allowed".into(), serde_json::json!(allowed));
915 }
916 AnchorValidationError::UnknownGrain { got, allowed } => {
917 d.insert("field".into(), "grain".into());
918 d.insert("got".into(), serde_json::json!(got));
919 d.insert("allowed".into(), serde_json::json!(allowed));
920 }
921 AnchorValidationError::UnknownHashStability { got, allowed } => {
922 d.insert("field".into(), "hash_stability".into());
923 d.insert("got".into(), serde_json::json!(got));
924 d.insert("allowed".into(), serde_json::json!(allowed));
925 }
926 AnchorValidationError::MissingArtifact => {
927 d.insert("field".into(), "artifact".into());
928 }
929 AnchorValidationError::EmptySource => {
930 d.insert("field".into(), "source".into());
931 }
932 AnchorValidationError::SourceNotDeclared { got, declared } => {
933 d.insert("field".into(), "source".into());
934 d.insert("got".into(), serde_json::json!(got));
935 d.insert("declared".into(), serde_json::json!(declared));
936 }
937 AnchorValidationError::HashOnNonHashClass { class } => {
938 d.insert("field".into(), "hash".into());
939 d.insert("class".into(), serde_json::json!(class));
940 }
941 AnchorValidationError::ContentAndHash => {
942 d.insert("field".into(), "content".into());
943 d.insert(
944 "expected".into(),
945 serde_json::json!("either `hash` or `content`, never both"),
946 );
947 }
948 AnchorValidationError::ContentNotAcceptedForGrain { grain } => {
949 d.insert("field".into(), "content".into());
950 d.insert("grain".into(), serde_json::json!(grain));
951 d.insert(
952 "accepted_grains".into(),
953 serde_json::json!(["span", "file", "url"]),
954 );
955 }
956 AnchorValidationError::UnitAbsentFromContent { artifact } => {
957 d.insert("field".into(), "content".into());
958 d.insert("got".into(), serde_json::json!(artifact));
959 }
960 AnchorValidationError::SpanLocatorUnusable { artifact, reason } => {
961 d.insert("field".into(), "artifact".into());
962 d.insert("got".into(), serde_json::json!(artifact));
963 d.insert("expected".into(), serde_json::json!(reason));
964 }
965 AnchorValidationError::SpanOutsideContent { artifact, lines } => {
966 d.insert("field".into(), "artifact".into());
967 d.insert("got".into(), serde_json::json!(artifact));
968 d.insert("content_lines".into(), serde_json::json!(lines));
969 }
970 AnchorValidationError::DuplicateAnchorTriple {
971 artifact,
972 grain,
973 class,
974 span,
975 } => {
976 d.insert("field".into(), "anchors".into());
977 d.insert(
978 "got".into(),
979 serde_json::json!({
980 "artifact": artifact, "grain": grain, "class": class, "span": span
981 }),
982 );
983 d.insert(
984 "expected".into(),
985 serde_json::json!(
986 "each (artifact, grain, class, span) identity at most once per payload"
987 ),
988 );
989 }
990 AnchorValidationError::SpanAndHash => {
991 d.insert("field".into(), "span".into());
992 d.insert(
993 "expected".into(),
994 serde_json::json!("either `span` (with `content`) or `hash`, never both"),
995 );
996 }
997 AnchorValidationError::SpanEmpty => {
998 d.insert("field".into(), "span".into());
999 }
1000 AnchorValidationError::SpanNotAcceptedForGrain { grain } => {
1001 d.insert("field".into(), "span".into());
1002 d.insert("grain".into(), serde_json::json!(grain));
1003 d.insert(
1004 "accepted_grains".into(),
1005 serde_json::json!(["url", "span", "file"]),
1006 );
1007 }
1008 AnchorValidationError::SpanAbsentFromContent { artifact, span } => {
1009 d.insert("field".into(), "span".into());
1010 d.insert("artifact".into(), serde_json::json!(artifact));
1011 d.insert("got".into(), serde_json::json!(span));
1012 d.insert(
1013 "expected".into(),
1014 serde_json::json!(
1015 "the span, in the canonical span form, occurring in the canonical form \
1016 of `content`"
1017 ),
1018 );
1019 }
1020 AnchorValidationError::ArtifactUnresolvable {
1021 artifact,
1022 candidates,
1023 } => {
1024 d.insert("field".into(), "artifact".into());
1025 d.insert("got".into(), serde_json::json!(artifact));
1026 d.insert("candidates_tried".into(), serde_json::json!(candidates));
1027 d.insert(
1028 "expected".into(),
1029 serde_json::json!(
1030 "a source-relative path (joined onto the source's pointer) or a \
1031 workspace-relative path that resolves to an existing artifact"
1032 ),
1033 );
1034 }
1035 AnchorValidationError::GrainNamespaceUnsupported {
1036 grain,
1037 medium_type,
1038 anchor_namespace,
1039 } => {
1040 d.insert("field".into(), "grain".into());
1041 d.insert("grain".into(), serde_json::json!(grain));
1042 d.insert("medium_type".into(), serde_json::json!(medium_type));
1043 d.insert(
1044 "anchor_namespace".into(),
1045 serde_json::json!(anchor_namespace),
1046 );
1047 }
1048 AnchorValidationError::PathGrainOnUrlArtifact { grain, artifact } => {
1049 d.insert("field".into(), "grain".into());
1050 d.insert("grain".into(), serde_json::json!(grain));
1051 d.insert("got".into(), serde_json::json!(artifact));
1052 d.insert(
1053 "expected".into(),
1054 serde_json::json!(
1055 "`grain: url` for a web resource — a URL never enters a path namespace"
1056 ),
1057 );
1058 }
1059 }
1060 d
1061 }
1062}
1063
1064impl AnchorInput {
1065 /// Validate this wire element into a strict [`Anchor`], or refuse
1066 /// typed.
1067 ///
1068 /// `medium` — the resolving medium's `(type_name, anchor_namespace)`
1069 /// pair, when the mutation resolved one. When `Some`, the grain is
1070 /// checked against the namespace (the capability-matrix refusal);
1071 /// when `None` (no medium context — a manually-authored anchor), the
1072 /// namespace check is skipped and only the vocabulary + hash-semantics
1073 /// rules apply.
1074 ///
1075 /// Rules enforced (each a typed [`AnchorValidationError`]):
1076 /// - class present and known;
1077 /// - grain present and known;
1078 /// - artifact reference present and non-empty;
1079 /// - a hash (or content to hash) is supplied only on a hash-bearing
1080 /// class; `content` and `hash` are mutually exclusive; `content` is
1081 /// accepted only for the grains whose prepared form the registry
1082 /// computes from supplied bytes (`span` / `file` / `url`), and then
1083 /// `hash` is the registry's prepared hash of it;
1084 /// - hash stability, when supplied, is a known wire string (defaults
1085 /// per grain when absent — `url` unstable, every other grain stable);
1086 /// - grain supported by the medium's namespace (when `medium` given).
1087 pub fn validate(&self, medium: Option<(&str, &str)>) -> Result<Anchor, AnchorValidationError> {
1088 let class = match self
1089 .class
1090 .as_deref()
1091 .and_then(AnchorProvenanceClass::from_wire)
1092 {
1093 Some(c) => c,
1094 None => {
1095 return Err(AnchorValidationError::UnknownClass {
1096 got: self.class.clone(),
1097 allowed: AnchorProvenanceClass::WIRE_VALUES,
1098 });
1099 }
1100 };
1101 let grain = match self.grain.as_deref().and_then(AnchorGrain::from_wire) {
1102 Some(g) => g,
1103 None => {
1104 return Err(AnchorValidationError::UnknownGrain {
1105 got: self.grain.clone(),
1106 allowed: AnchorGrain::WIRE_VALUES,
1107 });
1108 }
1109 };
1110
1111 let artifact = self
1112 .artifact
1113 .as_deref()
1114 .map(str::trim)
1115 .filter(|s| !s.is_empty())
1116 .map(str::to_string)
1117 .ok_or(AnchorValidationError::MissingArtifact)?;
1118
1119 // Hash stability: default per grain when absent (`url` unstable,
1120 // every other grain stable); refuse an unknown supplied value.
1121 let hash_stability = match self.hash_stability.as_deref() {
1122 None => crate::preparation::default_hash_stability(grain),
1123 Some(s) => AnchorHashStability::from_wire(s).ok_or_else(|| {
1124 AnchorValidationError::UnknownHashStability {
1125 got: s.to_string(),
1126 allowed: AnchorHashStability::WIRE_VALUES,
1127 }
1128 })?,
1129 };
1130
1131 // A hash is only meaningful on a hash-bearing class. A quoted span
1132 // is a fidelity claim ("the artifact says these words"), so it is
1133 // one too.
1134 let hash = self
1135 .hash
1136 .as_deref()
1137 .map(str::trim)
1138 .filter(|s| !s.is_empty())
1139 .map(str::to_string);
1140 if (hash.is_some() || self.content.is_some() || self.span.is_some())
1141 && !class.is_hash_bearing()
1142 {
1143 return Err(AnchorValidationError::HashOnNonHashClass {
1144 class: class.as_wire(),
1145 });
1146 }
1147 // The quoted span: the engine computes its hashes, so a supplied
1148 // hash beside it is refused; an empty span names nothing; the
1149 // `entity` and `tree` grains are never prepared from supplied text.
1150 // Checked against `content` where the caller supplied it (the words
1151 // must occur, in the canonical span form); recorded as unverified
1152 // where they did not.
1153 let span = match self.span.as_deref() {
1154 None => None,
1155 Some(_) if hash.is_some() => return Err(AnchorValidationError::SpanAndHash),
1156 Some(raw) => {
1157 if crate::preparation::canonical_span_form(raw).is_empty() {
1158 return Err(AnchorValidationError::SpanEmpty);
1159 }
1160 if matches!(grain, AnchorGrain::Entity | AnchorGrain::Tree) {
1161 return Err(AnchorValidationError::SpanNotAcceptedForGrain {
1162 grain: grain.as_wire(),
1163 });
1164 }
1165 if let Some(content) = self.content.as_deref()
1166 && !crate::preparation::span_occurs(raw, content)
1167 {
1168 return Err(AnchorValidationError::SpanAbsentFromContent {
1169 artifact: artifact.clone(),
1170 span: raw.trim().to_string(),
1171 });
1172 }
1173 Some(raw.trim().to_string())
1174 }
1175 };
1176 let span_hash = span.as_deref().map(crate::preparation::span_hash);
1177 let mut span_unvalidated = span.is_some() && self.content.is_none();
1178 // Supplied content: the engine computes the prepared hash through the
1179 // preparation registry (touchpoint A at write time) — the one way a
1180 // `url` anchor's recorded hash is ever the engine's prepared form.
1181 let hash = match self.content.as_deref() {
1182 None => hash,
1183 Some(_) if hash.is_some() => return Err(AnchorValidationError::ContentAndHash),
1184 Some(content) => {
1185 match crate::preparation::supplied_content_hash(grain, content.as_bytes()) {
1186 Some(h) => Some(h),
1187 None => {
1188 return Err(AnchorValidationError::ContentNotAcceptedForGrain {
1189 grain: grain.as_wire(),
1190 });
1191 }
1192 }
1193 }
1194 };
1195
1196 // The span-grain locator (consistency-sweep 03/03). A locator that
1197 // can never address anything is refused here, context-free, because
1198 // no medium context can rescue it. Where the caller supplied content,
1199 // a line range is checked against it; where they did not, the row
1200 // carries `span_unvalidated` so no later surface reports it as
1201 // adjudicated.
1202 if grain == AnchorGrain::Span {
1203 let locator = parse_span_locator(&artifact).map_err(|reason| {
1204 AnchorValidationError::SpanLocatorUnusable {
1205 artifact: artifact.clone(),
1206 reason,
1207 }
1208 })?;
1209 match (locator, self.content.as_deref()) {
1210 (Some(SpanLocator::Lines { end, .. }), Some(content)) => {
1211 let lines = content.lines().count();
1212 if end > lines {
1213 return Err(AnchorValidationError::SpanOutsideContent {
1214 artifact: artifact.clone(),
1215 lines,
1216 });
1217 }
1218 }
1219 // A unit key with content in hand is the existing
1220 // unit-absent refusal's business, at the seam that knows the
1221 // source's preparation; a check here would have to guess it.
1222 (Some(SpanLocator::Unit(_)), Some(_)) => {}
1223 // No locator addresses the whole artifact, and the existence
1224 // gate already checks that the artifact is there. Nothing is
1225 // left unchecked, so nothing is recorded as unchecked.
1226 (None, _) => {}
1227 (Some(_), None) => span_unvalidated = true,
1228 }
1229 }
1230
1231 // A path-shaped grain never names a URL: the resource is the `url`
1232 // grain's business, whatever medium the mem sits beside.
1233 if grain.is_path_shaped() && looks_like_url(&artifact) {
1234 return Err(AnchorValidationError::PathGrainOnUrlArtifact {
1235 grain: grain.as_wire(),
1236 artifact,
1237 });
1238 }
1239
1240 // Grain must be expressible in the medium's namespace (a `url`
1241 // grain is admitted beside every medium — see
1242 // [`AnchorGrain::supported_by_namespace`]).
1243 if let Some((medium_type, namespace)) = medium
1244 && !grain.supported_by_namespace(namespace)
1245 {
1246 // Resolve the namespace to its `&'static str` so the error
1247 // carries a stable value even though the input came borrowed.
1248 let anchor_namespace = match namespace {
1249 "path" => "path",
1250 "path+commit" => "path+commit",
1251 "entity" => "entity",
1252 "url" => "url",
1253 _ => "path",
1254 };
1255 return Err(AnchorValidationError::GrainNamespaceUnsupported {
1256 grain: grain.as_wire(),
1257 medium_type: medium_type.to_string(),
1258 anchor_namespace,
1259 });
1260 }
1261
1262 // `source`, when present, must be non-empty. (Whether it names a
1263 // source the producing binding actually declares is checked at
1264 // the engine seam, which can resolve the binding hash — this
1265 // context-free validator cannot.)
1266 let source = match self.source.as_deref() {
1267 None => None,
1268 Some(raw) => {
1269 let trimmed = raw.trim();
1270 if trimmed.is_empty() {
1271 return Err(AnchorValidationError::EmptySource);
1272 }
1273 Some(trimmed.to_string())
1274 }
1275 };
1276
1277 Ok(Anchor {
1278 artifact,
1279 grain,
1280 class,
1281 at_version: self.at_version.clone(),
1282 // A hash present at this point came from the writer, directly or
1283 // as content the engine hashed. The backfill stamps its own.
1284 hash_source: hash.is_some().then_some(AnchorHashSource::Author),
1285 hash,
1286 hash_stability,
1287 derived_from: self.derived_from.clone().unwrap_or_default(),
1288 binding: self
1289 .binding
1290 .as_deref()
1291 .map(str::trim)
1292 .filter(|s| !s.is_empty())
1293 .map(str::to_string),
1294 source,
1295 span,
1296 span_hash,
1297 span_unvalidated,
1298 last_observed: None,
1299 })
1300 }
1301}
1302
1303// ---------------------------------------------------------------------------
1304// Prepared-content hash
1305// ---------------------------------------------------------------------------
1306
1307/// Compute the **prepared-content hash** of a path-grain artifact's bytes —
1308/// the value [`Anchor::hash`] records and hash-drift adjudication compares.
1309///
1310/// The prepared form is a deliberate, minimal canonicalization that keeps the
1311/// hash stable across meaningless byte noise while preserving every
1312/// content-bearing byte. For UTF-8 text:
1313///
1314/// - a leading BOM (U+FEFF) is stripped;
1315/// - CRLF / lone-CR line endings normalize to LF;
1316/// - trailing newlines are trimmed (final-newline presence is noise).
1317///
1318/// Interior whitespace is untouched — trailing spaces inside a line can be
1319/// content (markdown hard breaks), so only the two classic cross-tool noise
1320/// sources (encoding marks, line-ending convention) and the final-newline
1321/// question are canonicalized. Non-UTF-8 (binary) bytes hash as-is — no text
1322/// canonicalization applies to them.
1323///
1324/// The hash form reuses the house convention — SHA-256, lowercase hex,
1325/// truncated to 16 characters — shared by entity content hashes
1326/// ([`crate::entity::parser::compute_hash`]) and the change-detection digest
1327/// aggregate, so the engine keeps one hash shape rather than growing a
1328/// second normalization.
1329pub fn prepared_content_hash(bytes: &[u8]) -> String {
1330 use sha2::{Digest as _, Sha256};
1331 let digest = match std::str::from_utf8(bytes) {
1332 Ok(text) => {
1333 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
1334 let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
1335 Sha256::digest(normalized.trim_end_matches('\n').as_bytes())
1336 }
1337 Err(_) => Sha256::digest(bytes),
1338 };
1339 crate::hex_lower(&digest)[..16].to_string()
1340}
1341
1342/// One verify-observed prepared-content hash, addressed to the anchor(s) it
1343/// backfills: the `(entity, artifact)` pair a hash-less hash-bearing anchor
1344/// is keyed by in the sidecar, plus the hash the observation computed. The
1345/// verify pass collects these; the engine's sidecar writer records them.
1346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1347pub struct ObservedArtifactHash {
1348 /// The entity id (`mem--slug`) whose anchor the hash belongs to.
1349 pub entity: String,
1350 /// The anchor's artifact reference, exactly as stored.
1351 pub artifact: String,
1352 /// The prepared-content hash observed for the artifact.
1353 pub hash: String,
1354}
1355
1356// ---------------------------------------------------------------------------
1357// Supplied observations
1358// ---------------------------------------------------------------------------
1359
1360/// Typed code for a malformed supplied observation row.
1361pub const INVALID_OBSERVATION_CODE: &str = "INVALID_OBSERVATION";
1362
1363/// One observer-supplied observation row, as it arrives on the wire
1364/// (`memstead verify-anchors --observations`): permissive and string-typed
1365/// so a malformed row refuses with a typed [`ObservationValidationError`]
1366/// before any state changes. The engine never fetches; for a grain it
1367/// cannot observe itself (`url`) this is how an observation enters the one
1368/// resolution funnel.
1369#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1370pub struct SuppliedObservationInput {
1371 /// The anchor's artifact reference, exactly as stored (a URL for a
1372 /// `url` row).
1373 #[serde(default)]
1374 pub artifact: Option<String>,
1375 /// The prepared-content hash the observer computed. Exactly one of
1376 /// `hash`, `content`, `absent: true`.
1377 #[serde(default)]
1378 pub hash: Option<String>,
1379 /// The observed artifact CONTENT (UTF-8 text); the engine hashes it
1380 /// under the same canonicalization the write path applies to a `url`
1381 /// anchor's `content`.
1382 #[serde(default)]
1383 pub content: Option<String>,
1384 /// The observer could not retrieve the artifact.
1385 #[serde(default)]
1386 pub absent: Option<bool>,
1387 /// When the observation was made (ISO-8601 UTC, `YYYY-MM-DDTHH:MM:SSZ`
1388 /// or a bare `YYYY-MM-DD`). Defaults to the engine's clock at the run.
1389 #[serde(default)]
1390 pub observed_at: Option<String>,
1391}
1392
1393/// What an observer saw for one artifact.
1394#[derive(Debug, Clone, PartialEq, Eq)]
1395pub enum SuppliedOutcome {
1396 /// The artifact was retrieved; `hash` is its prepared-content hash
1397 /// under the default canonicalization, and `content` the retrieved text
1398 /// when the observer supplied it rather than a hash — kept so the
1399 /// resolution site can re-prepare it under the anchor's source
1400 /// preparation (a `quoted-phrase` url anchor is adjudicated on the
1401 /// phrase, not on the whole page), exactly as the write path does for
1402 /// an anchor's `content`.
1403 Present {
1404 hash: String,
1405 content: Option<String>,
1406 },
1407 /// The observer could not retrieve the artifact.
1408 Absent,
1409}
1410
1411/// A validated supplied observation.
1412#[derive(Debug, Clone, PartialEq, Eq)]
1413pub struct SuppliedObservation {
1414 pub artifact: String,
1415 /// ISO-8601 timestamp of the observation.
1416 pub at: String,
1417 pub outcome: SuppliedOutcome,
1418}
1419
1420/// Why a supplied observation row was refused.
1421#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1422pub enum ObservationValidationError {
1423 #[error("observation row {row}: `artifact` is required and must be non-empty")]
1424 MissingArtifact { row: usize },
1425 #[error(
1426 "observation row {row} (`{artifact}`): give exactly one of `hash`, `content`, or \
1427 `absent: true`"
1428 )]
1429 OutcomeAmbiguous { row: usize, artifact: String },
1430 #[error(
1431 "observation row {row} (`{artifact}`): `observed_at` '{got}' is not an ISO-8601 \
1432 timestamp (`YYYY-MM-DDTHH:MM:SSZ`) or date (`YYYY-MM-DD`)"
1433 )]
1434 BadTimestamp {
1435 row: usize,
1436 artifact: String,
1437 got: String,
1438 },
1439 #[error("observation rows name `{artifact}` more than once (rows {first} and {second})")]
1440 DuplicateArtifact {
1441 artifact: String,
1442 first: usize,
1443 second: usize,
1444 },
1445}
1446
1447impl ObservationValidationError {
1448 /// The stable typed code — always [`INVALID_OBSERVATION_CODE`].
1449 pub fn code(&self) -> &'static str {
1450 INVALID_OBSERVATION_CODE
1451 }
1452
1453 /// Structured recovery detail for the typed envelope.
1454 pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
1455 let mut d = BTreeMap::new();
1456 match self {
1457 ObservationValidationError::MissingArtifact { row } => {
1458 d.insert("row".into(), serde_json::json!(row));
1459 d.insert("field".into(), "artifact".into());
1460 }
1461 ObservationValidationError::OutcomeAmbiguous { row, artifact } => {
1462 d.insert("row".into(), serde_json::json!(row));
1463 d.insert("artifact".into(), serde_json::json!(artifact));
1464 d.insert(
1465 "expected".into(),
1466 serde_json::json!("exactly one of `hash`, `content`, `absent: true`"),
1467 );
1468 }
1469 ObservationValidationError::BadTimestamp { row, artifact, got } => {
1470 d.insert("row".into(), serde_json::json!(row));
1471 d.insert("artifact".into(), serde_json::json!(artifact));
1472 d.insert("field".into(), "observed_at".into());
1473 d.insert("got".into(), serde_json::json!(got));
1474 }
1475 ObservationValidationError::DuplicateArtifact {
1476 artifact,
1477 first,
1478 second,
1479 } => {
1480 d.insert("artifact".into(), serde_json::json!(artifact));
1481 d.insert("rows".into(), serde_json::json!([first, second]));
1482 }
1483 }
1484 d
1485 }
1486}
1487
1488/// Accept `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SSZ` (any `T…Z` time part of the
1489/// second-granularity form).
1490fn timestamp_is_wellformed(ts: &str) -> bool {
1491 let b = ts.as_bytes();
1492 let date_ok = b.len() >= 10
1493 && b[..10].iter().enumerate().all(|(i, c)| {
1494 if i == 4 || i == 7 {
1495 *c == b'-'
1496 } else {
1497 c.is_ascii_digit()
1498 }
1499 });
1500 if !date_ok {
1501 return false;
1502 }
1503 if b.len() == 10 {
1504 return true;
1505 }
1506 b.len() == 20
1507 && b[10] == b'T'
1508 && b[19] == b'Z'
1509 && b[11..19].iter().enumerate().all(|(i, c)| {
1510 if i == 2 || i == 5 {
1511 *c == b':'
1512 } else {
1513 c.is_ascii_digit()
1514 }
1515 })
1516}
1517
1518/// Validate a batch of supplied observation rows; all-or-nothing, so a
1519/// malformed row refuses before any state changes. `now` is the timestamp
1520/// stamped on rows that carry no `observed_at`. Returns the observations
1521/// keyed by artifact.
1522pub fn validate_supplied_observations(
1523 rows: &[SuppliedObservationInput],
1524 now: &str,
1525) -> Result<BTreeMap<String, SuppliedObservation>, ObservationValidationError> {
1526 let mut out: BTreeMap<String, SuppliedObservation> = BTreeMap::new();
1527 let mut first_row: BTreeMap<String, usize> = BTreeMap::new();
1528 for (i, row) in rows.iter().enumerate() {
1529 let n = i + 1;
1530 let artifact = row
1531 .artifact
1532 .as_deref()
1533 .map(str::trim)
1534 .filter(|s| !s.is_empty())
1535 .ok_or(ObservationValidationError::MissingArtifact { row: n })?
1536 .to_string();
1537 let absent = row.absent.unwrap_or(false);
1538 let given = usize::from(row.hash.is_some())
1539 + usize::from(row.content.is_some())
1540 + usize::from(absent);
1541 if given != 1 {
1542 return Err(ObservationValidationError::OutcomeAmbiguous { row: n, artifact });
1543 }
1544 let at = match row.observed_at.as_deref().map(str::trim) {
1545 None | Some("") => now.to_string(),
1546 Some(ts) if timestamp_is_wellformed(ts) => ts.to_string(),
1547 Some(ts) => {
1548 return Err(ObservationValidationError::BadTimestamp {
1549 row: n,
1550 artifact,
1551 got: ts.to_string(),
1552 });
1553 }
1554 };
1555 if let Some(first) = first_row.get(&artifact) {
1556 return Err(ObservationValidationError::DuplicateArtifact {
1557 artifact,
1558 first: *first,
1559 second: n,
1560 });
1561 }
1562 let outcome = if absent {
1563 SuppliedOutcome::Absent
1564 } else if let Some(hash) = &row.hash {
1565 SuppliedOutcome::Present {
1566 hash: hash.trim().to_string(),
1567 content: None,
1568 }
1569 } else {
1570 let content = row.content.clone().unwrap_or_default();
1571 SuppliedOutcome::Present {
1572 hash: prepared_content_hash(content.as_bytes()),
1573 content: Some(content),
1574 }
1575 };
1576 first_row.insert(artifact.clone(), n);
1577 out.insert(
1578 artifact.clone(),
1579 SuppliedObservation {
1580 artifact,
1581 at,
1582 outcome,
1583 },
1584 );
1585 }
1586 Ok(out)
1587}
1588
1589/// Days since the Unix epoch of an ISO timestamp's date part, for aging a
1590/// recorded observation (`unobserved for N days`). `None` when the string
1591/// does not start with a well-formed `YYYY-MM-DD`.
1592pub fn iso_days_since_epoch(ts: &str) -> Option<i64> {
1593 if !timestamp_is_wellformed(ts) {
1594 return None;
1595 }
1596 let y: i64 = ts[..4].parse().ok()?;
1597 let m: u32 = ts[5..7].parse().ok()?;
1598 let d: u32 = ts[8..10].parse().ok()?;
1599 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
1600 return None;
1601 }
1602 let y = if m <= 2 { y - 1 } else { y };
1603 let era = if y >= 0 { y } else { y - 399 } / 400;
1604 let yoe = y - era * 400;
1605 let mp = ((m + 9) % 12) as i64;
1606 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
1607 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1608 Some(era * 146097 + doe - 719468)
1609}
1610
1611/// Whole days between a recorded observation and `now` (both ISO), floored
1612/// at zero; `None` when either fails to parse.
1613pub fn days_between(observed_at: &str, now: &str) -> Option<u64> {
1614 let a = iso_days_since_epoch(observed_at)?;
1615 let b = iso_days_since_epoch(now)?;
1616 Some((b - a).max(0) as u64)
1617}
1618
1619// ---------------------------------------------------------------------------
1620// Resolution
1621// ---------------------------------------------------------------------------
1622
1623/// The resolved state of one anchor against the current medium.
1624#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1625#[serde(rename_all = "lowercase")]
1626pub enum AnchorState {
1627 /// The artifact is present and matches (hash equal, or a non-hash
1628 /// class whose artifact still exists).
1629 Resolves,
1630 /// The artifact is present but its prepared-content hash differs and
1631 /// the medium is `stable` — a real content drift.
1632 Drifted,
1633 /// The artifact is present but drift cannot be asserted — the medium
1634 /// is `unstable`, or the hash is unavailable on one side. Flagged for
1635 /// re-examination, never reported as drift.
1636 Recheck,
1637 /// The artifact the anchor references is no longer present in the
1638 /// medium.
1639 Orphaned,
1640 /// The artifact is present but the words the row quotes (its `span`)
1641 /// no longer occur in it. The claim's basis is gone while the document
1642 /// stands: not `drifted` (the row's claim is the span, not the page)
1643 /// and not `orphaned` (the artifact is there). Only a row carrying a
1644 /// span can read this.
1645 #[serde(rename = "span_absent")]
1646 SpanAbsent,
1647}
1648
1649impl AnchorState {
1650 /// Every state, in the order the vocabulary is documented. The one
1651 /// list; a new variant must join it (the match in [`Self::describe`]
1652 /// refuses to compile without it, and [`Self::vocabulary_help`] and the
1653 /// round-trip test read it).
1654 pub const ALL: [AnchorState; 5] = [
1655 AnchorState::Resolves,
1656 AnchorState::Drifted,
1657 AnchorState::Recheck,
1658 AnchorState::Orphaned,
1659 AnchorState::SpanAbsent,
1660 ];
1661
1662 /// Stable wire form.
1663 pub fn as_wire(&self) -> &'static str {
1664 match self {
1665 AnchorState::Resolves => "resolves",
1666 AnchorState::Drifted => "drifted",
1667 AnchorState::Recheck => "recheck",
1668 AnchorState::Orphaned => "orphaned",
1669 AnchorState::SpanAbsent => "span_absent",
1670 }
1671 }
1672
1673 /// The one-line meaning of each state — the documentation every
1674 /// surface that names the vocabulary reads from (the CLI help and the
1675 /// reference rendered from it, [`Self::vocabulary_help`]).
1676 pub fn describe(&self) -> &'static str {
1677 match self {
1678 AnchorState::Resolves => "the artifact is present and matches",
1679 AnchorState::Drifted => {
1680 "present, hash differs, the medium is stable, so a real content drift"
1681 }
1682 AnchorState::Recheck => {
1683 "present, but drift cannot be asserted (unstable medium, or a hash missing on one side)"
1684 }
1685 AnchorState::Orphaned => "the artifact the anchor references is gone from the medium",
1686 AnchorState::SpanAbsent => {
1687 "present, but the words the row quotes (its span) no longer occur in it"
1688 }
1689 }
1690 }
1691
1692 /// The vocabulary as a help paragraph, one line per state, rendered
1693 /// from [`Self::ALL`] and [`Self::describe`] so a surface never carries
1694 /// its own list of states.
1695 pub fn vocabulary_help() -> String {
1696 let mut s = String::from("Anchor states (the artifact end of an anchor):\n");
1697 for state in Self::ALL {
1698 s.push_str(&format!(" {:<11} {}\n", state.as_wire(), state.describe()));
1699 }
1700 s.push_str(
1701 "Not states: `dangling` (a sidecar row whose entity the mem no longer holds) and \
1702 `unobserved` (the pass did not reach the artifact) are conditions of the \
1703 measurement, counted apart.",
1704 );
1705 s
1706 }
1707}
1708
1709/// The positive anchor resolution figure, carried with the population it
1710/// was computed over. A resolution count read on its own is read as
1711/// health, and every W3 finding of the 2026-08 consistency sweep was a bare
1712/// figure that meant less than it looked; this type makes the defect a
1713/// construction error instead of a lint finding. It cannot be built
1714/// without a population statement, it prints only through [`Display`]
1715/// (the count and the statement in one sentence) or [`Self::ratio`], and
1716/// its serde form carries the three fields together, so no renderer, JSON
1717/// or markdown, reaches the raw count.
1718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1719#[serde(try_from = "RawFigure")]
1720pub struct AnchorResolutionFigure {
1721 /// Anchors that resolved clean.
1722 resolves: usize,
1723 /// What the figure was computed over and how much of it the pass could
1724 /// not adjudicate. Never empty.
1725 population: String,
1726 /// Whether the pass adjudicated everything it counted.
1727 fully_adjudicated: bool,
1728}
1729
1730/// The wire shape [`AnchorResolutionFigure`] deserializes through, so a
1731/// figure read back from JSON without a population is refused too.
1732#[derive(Deserialize)]
1733struct RawFigure {
1734 resolves: usize,
1735 population: String,
1736 fully_adjudicated: bool,
1737}
1738
1739/// The one construction refusal: a figure with no population statement.
1740#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1741#[error("an anchor resolution figure cannot exist without the population it was computed over")]
1742pub struct FigureWithoutPopulation;
1743
1744impl TryFrom<RawFigure> for AnchorResolutionFigure {
1745 type Error = FigureWithoutPopulation;
1746 fn try_from(raw: RawFigure) -> Result<Self, Self::Error> {
1747 Self::new(raw.resolves, raw.population, raw.fully_adjudicated)
1748 }
1749}
1750
1751impl AnchorResolutionFigure {
1752 /// The only constructor: refuses an empty population statement.
1753 pub fn new(
1754 resolves: usize,
1755 population: impl Into<String>,
1756 fully_adjudicated: bool,
1757 ) -> Result<Self, FigureWithoutPopulation> {
1758 let population = population.into();
1759 if population.trim().is_empty() {
1760 return Err(FigureWithoutPopulation);
1761 }
1762 Ok(Self {
1763 resolves,
1764 population,
1765 fully_adjudicated,
1766 })
1767 }
1768
1769 /// The figure of a pass that counted nothing because it could not
1770 /// read its rows: zero, with the reason as its population. The reason
1771 /// is the statement, so it is checked like any other.
1772 pub(crate) fn uncounted(why: impl Into<String>) -> Self {
1773 Self::new(0, why, false).expect("an uncounted figure names why it counted nothing")
1774 }
1775
1776 /// What the count was computed over.
1777 pub fn population(&self) -> &str {
1778 &self.population
1779 }
1780
1781 /// Whether the pass adjudicated everything it counted.
1782 pub fn fully_adjudicated(&self) -> bool {
1783 self.fully_adjudicated
1784 }
1785
1786 /// The count as a ratio over `denominator`, followed by the population:
1787 /// `388/422 (91.9%) over 424 counted row(s) …`. The percentage never
1788 /// travels without the statement.
1789 pub fn ratio(&self, denominator: usize) -> String {
1790 if denominator == 0 {
1791 format!("{}/{denominator} (n/a) {}", self.resolves, self.population)
1792 } else {
1793 let pct = (self.resolves as f64) * 100.0 / (denominator as f64);
1794 format!(
1795 "{}/{denominator} ({pct:.1}%) {}",
1796 self.resolves, self.population
1797 )
1798 }
1799 }
1800
1801 /// Read a figure back from a JSON object that carries the three fields
1802 /// (`resolves`, `population`, `fully_adjudicated`) — the shape every
1803 /// surface serializes — so a renderer of JSON prints through the type
1804 /// too. `None` when a field is missing or the population is empty.
1805 pub fn from_json(v: &serde_json::Value) -> Option<Self> {
1806 Self::new(
1807 v.get("resolves")?.as_u64()? as usize,
1808 v.get("population")?.as_str()?,
1809 v.get("fully_adjudicated")?.as_bool()?,
1810 )
1811 .ok()
1812 }
1813
1814 /// The bare count, for a test assertion and nothing else: a renderer
1815 /// prints through [`Display`] or [`Self::ratio`]. Compiled for tests
1816 /// only (this crate's own, or a downstream crate's under the
1817 /// `test-support` feature), so no shipping code can reach it.
1818 #[cfg(any(test, feature = "test-support"))]
1819 pub fn count_for_assertions(&self) -> usize {
1820 self.resolves
1821 }
1822}
1823
1824impl Default for AnchorResolutionFigure {
1825 fn default() -> Self {
1826 Self::uncounted("population unknown: no row was counted")
1827 }
1828}
1829
1830impl std::fmt::Display for AnchorResolutionFigure {
1831 /// The count and its population in one sentence: `388 over 424 counted
1832 /// row(s): 422 adjudicated, 2 not (…)`.
1833 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1834 write!(f, "{} {}", self.resolves, self.population)
1835 }
1836}
1837
1838/// What the engine observed about an anchor's artifact when resolving.
1839#[derive(Debug, Clone, PartialEq, Eq)]
1840pub enum ArtifactObservation {
1841 /// The artifact could not be found in the medium.
1842 Absent,
1843 /// The artifact is present; `current_hash` is its prepared-content
1844 /// hash when the medium could compute one (`None` when the medium has
1845 /// no hash for it this pass — e.g. enumeration without preparation).
1846 Present { current_hash: Option<String> },
1847}
1848
1849/// Resolve one anchor against a current observation, honouring the class's
1850/// hash semantics and the medium's declared stability.
1851///
1852/// - `authored` / `informed-by` are excluded from hash-drift adjudication:
1853/// they [`Resolves`](AnchorState::Resolves) as long as the artifact
1854/// exists, [`Orphaned`](AnchorState::Orphaned) when it does not — a
1855/// content change never produces a drift state for them.
1856/// - `anchored` / `derived` compare the recorded prepared-content hash to
1857/// the current one: equal ⇒ resolves; different ⇒ `drifted` on a stable
1858/// medium, `recheck` on an unstable one; unavailable on either side ⇒
1859/// `recheck` (cannot adjudicate).
1860pub fn resolve_anchor(anchor: &Anchor, observation: &ArtifactObservation) -> AnchorState {
1861 let current_hash = match observation {
1862 ArtifactObservation::Absent => return AnchorState::Orphaned,
1863 ArtifactObservation::Present { current_hash } => current_hash,
1864 };
1865 // A row quoting a span is adjudicated on the span's presence
1866 // ([`resolve_span_anchor`]); a present observation that reaches here
1867 // for such a row carried no text to look in, so nothing can be asserted.
1868 if anchor.span.is_some() {
1869 return AnchorState::Recheck;
1870 }
1871 if !anchor.class.is_hash_bearing() {
1872 return AnchorState::Resolves;
1873 }
1874 match (&anchor.hash, current_hash) {
1875 (Some(recorded), Some(current)) if recorded == current => AnchorState::Resolves,
1876 (Some(_), Some(_)) => match anchor.hash_stability {
1877 AnchorHashStability::Stable => AnchorState::Drifted,
1878 AnchorHashStability::Unstable => AnchorState::Recheck,
1879 },
1880 // Missing hash on either side — cannot adjudicate drift.
1881 _ => AnchorState::Recheck,
1882 }
1883}
1884
1885/// Resolve a row that quotes a `span` against the observed TEXT of its
1886/// artifact: [`Resolves`](AnchorState::Resolves) while the span occurs in
1887/// the text (canonical span form), whatever the document's hash did, and
1888/// [`SpanAbsent`](AnchorState::SpanAbsent) once it does not. The document
1889/// hash is the observation's business (it is kept and shown as the row's
1890/// observed hash); the state answers the row's claim, which is the span.
1891/// A row without a span is not this function's to judge and resolves by
1892/// its hash ([`resolve_anchor`]).
1893pub fn resolve_span_anchor(anchor: &Anchor, text: &str) -> AnchorState {
1894 match anchor.span.as_deref() {
1895 Some(span) if crate::preparation::span_occurs(span, text) => AnchorState::Resolves,
1896 Some(_) => AnchorState::SpanAbsent,
1897 None => AnchorState::Recheck,
1898 }
1899}
1900
1901/// Per-entity provenance-class + grain composition, computed from an
1902/// entity's anchor list. Tree-grain fan-out is surfaced distinctly so a
1903/// single entity anchored to a large tree is never laundered into
1904/// full per-file credit — the count of tree anchors is visible on its own
1905/// axis, and downstream reads the fan-out counts from resolution.
1906#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1907pub struct EntityAnchorComposition {
1908 /// Anchor count keyed by provenance-class wire string.
1909 pub by_class: BTreeMap<String, usize>,
1910 /// Anchor count keyed by grain wire string.
1911 pub by_grain: BTreeMap<String, usize>,
1912 /// The `derived_from` input lists of every `derived` anchor, in
1913 /// anchor order: the derived-input provenance.
1914 pub derived_inputs: Vec<Vec<String>>,
1915 /// Artifact refs of every `tree`-grain anchor — the fan-out axis. A
1916 /// tree anchor is one row here regardless of how many files the tree
1917 /// contains; the file count is an observation resolution supplies, not
1918 /// a credit this composition grants.
1919 pub tree_grain_artifacts: Vec<String>,
1920}
1921
1922/// Compose an entity's anchors into class/grain counts, derived inputs,
1923/// and the tree-grain fan-out axis.
1924pub fn compose_entity_anchors(anchors: &[Anchor]) -> EntityAnchorComposition {
1925 let mut comp = EntityAnchorComposition::default();
1926 for a in anchors {
1927 *comp
1928 .by_class
1929 .entry(a.class.as_wire().to_string())
1930 .or_insert(0) += 1;
1931 *comp
1932 .by_grain
1933 .entry(a.grain.as_wire().to_string())
1934 .or_insert(0) += 1;
1935 if a.class == AnchorProvenanceClass::Derived {
1936 comp.derived_inputs.push(a.derived_from.clone());
1937 }
1938 if a.grain == AnchorGrain::Tree {
1939 comp.tree_grain_artifacts.push(a.artifact.clone());
1940 }
1941 }
1942 comp
1943}
1944
1945// ---------------------------------------------------------------------------
1946// Sidecar document
1947// ---------------------------------------------------------------------------
1948
1949/// The engine-owned anchors sidecar document persisted at
1950/// [`ANCHOR_SIDECAR_PATH`] on the mem branch: entity id → its anchors.
1951///
1952/// Written only through engine commits (the [`crate::backend::MemBackend`]
1953/// sidecar seam). Rename rewrites the key atomically in the same commit as
1954/// the entity move; delete drops the key in the same commit as the entity
1955/// delete.
1956#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1957pub struct AnchorSidecar {
1958 /// Document schema version.
1959 pub version: u32,
1960 /// Entity id (`mem--slug`) → its anchors. An entity with no anchors
1961 /// carries no key (an empty vec is pruned on write).
1962 #[serde(default)]
1963 pub entities: BTreeMap<String, Vec<Anchor>>,
1964}
1965
1966impl Default for AnchorSidecar {
1967 fn default() -> Self {
1968 Self {
1969 version: ANCHOR_SIDECAR_VERSION,
1970 entities: BTreeMap::new(),
1971 }
1972 }
1973}
1974
1975impl AnchorSidecar {
1976 /// Parse sidecar bytes; an absent/empty payload yields an empty
1977 /// document so callers need not special-case a fresh mem.
1978 pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
1979 if bytes.iter().all(u8::is_ascii_whitespace) {
1980 return Ok(Self::default());
1981 }
1982 let sidecar: Self = serde_json::from_slice(bytes)?;
1983 // The version field is a contract, not decoration. Every sibling
1984 // store refuses an unknown one — the binding record with
1985 // `UNKNOWN_BINDING_VERSION`, the workspace stores with
1986 // `WORKSPACE_STORE_FORMAT_MISMATCH` — and this one silently accepted
1987 // it, so a sidecar written by a future engine parsed as whatever
1988 // today's field names happened to match and verified CLEAN. Reading
1989 // an unknown format optimistically is how a measurement ends up
1990 // confidently describing something it does not understand.
1991 if !ANCHOR_SIDECAR_VERSIONS_READ.contains(&sidecar.version) {
1992 return Err(serde::de::Error::custom(format!(
1993 "unsupported anchors sidecar version {} (this engine reads versions {}) — \
1994 the file was written by a different engine; upgrade, or remove the sidecar \
1995 to re-record anchors",
1996 sidecar.version,
1997 ANCHOR_SIDECAR_VERSIONS_READ
1998 .iter()
1999 .map(u32::to_string)
2000 .collect::<Vec<_>>()
2001 .join(", ")
2002 )));
2003 }
2004 // An older readable version is upgraded in memory: the rows are
2005 // unchanged (a version-2 field is simply absent on them) and the
2006 // next write persists the version the rows require: version 2
2007 // unless a row carries a span or a pinned hash source.
2008 let mut sidecar = sidecar;
2009 sidecar.version = sidecar.required_version();
2010 Ok(sidecar)
2011 }
2012
2013 /// The version this document's rows require: [`ANCHOR_SIDECAR_SPAN_VERSION`]
2014 /// once any row carries a quoted `span` or a `pinned` hash source (the
2015 /// two things an engine reading only versions 1 and 2 cannot
2016 /// understand), [`ANCHOR_SIDECAR_VERSION`] otherwise. The version moves
2017 /// only when such a row is written, so a sidecar written before spans
2018 /// existed re-saves with the version it had.
2019 pub fn required_version(&self) -> u32 {
2020 let needs_v3 = self
2021 .entities
2022 .values()
2023 .flatten()
2024 .any(|a| a.span.is_some() || a.hash_source == Some(AnchorHashSource::Pinned));
2025 if needs_v3 {
2026 ANCHOR_SIDECAR_SPAN_VERSION
2027 } else {
2028 ANCHOR_SIDECAR_VERSION
2029 }
2030 }
2031
2032 /// Serialise to canonical pretty JSON with a trailing newline —
2033 /// diff-friendly on the mem branch. The written `version` is
2034 /// [`Self::required_version`], whatever the in-memory field says.
2035 pub fn to_bytes(&self) -> Vec<u8> {
2036 #[derive(Serialize)]
2037 struct Wire<'a> {
2038 version: u32,
2039 entities: &'a BTreeMap<String, Vec<Anchor>>,
2040 }
2041 let wire = Wire {
2042 version: self.required_version(),
2043 entities: &self.entities,
2044 };
2045 let mut s = serde_json::to_string_pretty(&wire).expect("anchor sidecar serialises");
2046 s.push('\n');
2047 s.into_bytes()
2048 }
2049
2050 /// The anchors recorded for `entity_id`, or an empty slice.
2051 pub fn get(&self, entity_id: &str) -> &[Anchor] {
2052 self.entities
2053 .get(entity_id)
2054 .map(Vec::as_slice)
2055 .unwrap_or(&[])
2056 }
2057
2058 /// Replace `entity_id`'s anchors. An empty list prunes the key so the
2059 /// sidecar never accumulates empty rows.
2060 pub fn set(&mut self, entity_id: &str, anchors: Vec<Anchor>) {
2061 if anchors.is_empty() {
2062 self.entities.remove(entity_id);
2063 } else {
2064 self.entities.insert(entity_id.to_string(), anchors);
2065 }
2066 }
2067
2068 /// Merge `incoming` into `entity_id`'s anchor row after applying
2069 /// `unsets` — the write-path set arithmetic.
2070 ///
2071 /// Unset applies **first**: each selector removes its matching anchors
2072 /// (a selector matching nothing is a no-op). Then each incoming anchor
2073 /// **replaces** the surviving anchor with the same
2074 /// `(artifact, grain, class, span)` identity in place, and **appends**
2075 /// otherwise — untouched anchors keep their bytes and their position.
2076 /// The span is part of the identity: two spans on one document are two
2077 /// rows, and a re-pin that omits the span never touches a span row.
2078 /// Writing anchors never removes an anchor the call did not name in
2079 /// `unsets`; an empty `incoming` merges nothing. A row emptied by
2080 /// unsets prunes its key so the sidecar never accumulates empty rows.
2081 pub fn merge(
2082 &mut self,
2083 entity_id: &str,
2084 unsets: &[AnchorUnset],
2085 incoming: Vec<Anchor>,
2086 rebaseline: bool,
2087 ) -> bool {
2088 let mut row = self.entities.remove(entity_id).unwrap_or_default();
2089 let before = row.len();
2090 row.retain(|a| !unsets.iter().any(|u| u.matches(a)));
2091 let mut changed = row.len() != before;
2092 for anchor in incoming {
2093 match row.iter_mut().find(|e| {
2094 e.artifact == anchor.artifact
2095 && e.grain == anchor.grain
2096 && e.class == anchor.class
2097 && same_span(e.span.as_deref(), anchor.span.as_deref())
2098 }) {
2099 Some(existing) => {
2100 // The same triple replaces the row. A row identical to the stored one on every
2101 // caller-supplied field is a no-op: nothing is written
2102 // and the caller hears so. Otherwise the stored row goes,
2103 // baseline included: a re-pin that names no hash is
2104 // written hash-less for the next verify to backfill
2105 // against the artifact as it now is, which is what a
2106 // re-pin after a sync repair means. A caller who
2107 // supplies a hash sets that baseline directly. (The
2108 // 2026-08 consistency sweep carried the stored baseline
2109 // forward instead, which left every one-update repair
2110 // reading `drifted` against the content it had just
2111 // repaired; the re-pin is itself recorded, so nothing is
2112 // lost by re-baselining.)
2113 // `rebaseline` is the update that also rewrote the
2114 // entity's content (a sync repair): its anchors were
2115 // drawn from the artifact as it now is, so a restated
2116 // row still moves the baseline; on an anchors-only
2117 // update a restated row is a no-op.
2118 if !rebaseline && existing.same_as_supplied(&anchor) {
2119 continue;
2120 }
2121 *existing = anchor;
2122 changed = true;
2123 }
2124 None => {
2125 row.push(anchor);
2126 changed = true;
2127 }
2128 }
2129 }
2130 if !row.is_empty() {
2131 self.entities.insert(entity_id.to_string(), row);
2132 }
2133 changed
2134 }
2135
2136 /// Blank every artifact reference — `artifact` and each `derived_from`
2137 /// entry — to [`REDACTED_ARTIFACT_SENTINEL`], keeping everything else:
2138 /// class, grain, `at_version`, hash, hash-stability, binding, source,
2139 /// and the per-entity anchor counts. Redact, not strip: a consumer
2140 /// still reads *how strongly* each entity claims fidelity to a source
2141 /// without learning *which* source. Publish-time only by design — no
2142 /// engine path calls this against workspace state.
2143 pub fn redact_artifact_references(&mut self) {
2144 for anchors in self.entities.values_mut() {
2145 for anchor in anchors {
2146 anchor.artifact = REDACTED_ARTIFACT_SENTINEL.to_string();
2147 for input in &mut anchor.derived_from {
2148 *input = REDACTED_ARTIFACT_SENTINEL.to_string();
2149 }
2150 }
2151 }
2152 }
2153
2154 /// Structural check on artifact references: every `artifact` and every
2155 /// `derived_from` entry must be non-empty. The mutation surface never
2156 /// admits an empty reference (`INVALID_ANCHOR`), so a sidecar carrying
2157 /// one is corruption — including a botched redaction that blanked to
2158 /// nothing instead of the pinned sentinel. Returns the first offence.
2159 pub fn validate_artifact_references(&self) -> Result<(), String> {
2160 for (entity_id, anchors) in &self.entities {
2161 for anchor in anchors {
2162 if anchor.artifact.trim().is_empty() {
2163 return Err(format!(
2164 "entity `{entity_id}` carries an anchor with an empty artifact \
2165 reference"
2166 ));
2167 }
2168 if anchor.derived_from.iter().any(|d| d.trim().is_empty()) {
2169 return Err(format!(
2170 "entity `{entity_id}` carries an anchor with an empty \
2171 `derived_from` entry"
2172 ));
2173 }
2174 }
2175 }
2176 Ok(())
2177 }
2178
2179 /// Drop `entity_id`'s anchors entirely (delete leg). Idempotent.
2180 pub fn remove(&mut self, entity_id: &str) {
2181 self.entities.remove(entity_id);
2182 }
2183
2184 /// Move `from`'s anchors to `to` (rename leg), leaving zero rows under
2185 /// the old id. No-op when `from` has no anchors. When `to` already has
2186 /// anchors they are overwritten — a rename onto a live id is refused
2187 /// upstream, so this is the residual-stub case only.
2188 pub fn rename(&mut self, from: &str, to: &str) {
2189 if let Some(anchors) = self.entities.remove(from) {
2190 self.entities.insert(to.to_string(), anchors);
2191 }
2192 }
2193
2194 /// Whether the document holds no anchors for any entity.
2195 pub fn is_empty(&self) -> bool {
2196 self.entities.is_empty()
2197 }
2198}
2199
2200#[cfg(test)]
2201mod figure_and_vocabulary;
2202#[cfg(test)]
2203mod tests;