use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub const ANCHOR_SIDECAR_PATH: &str = ".memstead/anchors.json";
pub const ANCHOR_SIDECAR_VERSION: u32 = 2;
pub const ANCHOR_SIDECAR_SPAN_VERSION: u32 = 3;
pub const ANCHOR_SIDECAR_VERSIONS_READ: &[u32] = &[1, 2, 3];
pub const INVALID_ANCHOR_CODE: &str = "INVALID_ANCHOR";
pub const REDACTED_ARTIFACT_SENTINEL: &str = "[redacted]";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AnchorProvenanceClass {
Anchored,
Derived,
Authored,
InformedBy,
}
impl AnchorProvenanceClass {
pub const WIRE_VALUES: &'static [&'static str] =
&["anchored", "derived", "authored", "informed-by"];
pub fn as_wire(&self) -> &'static str {
match self {
AnchorProvenanceClass::Anchored => "anchored",
AnchorProvenanceClass::Derived => "derived",
AnchorProvenanceClass::Authored => "authored",
AnchorProvenanceClass::InformedBy => "informed-by",
}
}
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"anchored" => Some(AnchorProvenanceClass::Anchored),
"derived" => Some(AnchorProvenanceClass::Derived),
"authored" => Some(AnchorProvenanceClass::Authored),
"informed-by" => Some(AnchorProvenanceClass::InformedBy),
_ => None,
}
}
pub fn is_hash_bearing(&self) -> bool {
matches!(
self,
AnchorProvenanceClass::Anchored | AnchorProvenanceClass::Derived
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorGrain {
Span,
File,
Tree,
Url,
Entity,
}
impl AnchorGrain {
pub const WIRE_VALUES: &'static [&'static str] = &["span", "file", "tree", "url", "entity"];
pub fn as_wire(&self) -> &'static str {
match self {
AnchorGrain::Span => "span",
AnchorGrain::File => "file",
AnchorGrain::Tree => "tree",
AnchorGrain::Url => "url",
AnchorGrain::Entity => "entity",
}
}
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"span" => Some(AnchorGrain::Span),
"file" => Some(AnchorGrain::File),
"tree" => Some(AnchorGrain::Tree),
"url" => Some(AnchorGrain::Url),
"entity" => Some(AnchorGrain::Entity),
_ => None,
}
}
pub fn supported_by_namespace(&self, anchor_namespace: &str) -> bool {
let path_shaped = matches!(anchor_namespace, "path" | "path+commit");
match self {
AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => path_shaped,
AnchorGrain::Url => true,
AnchorGrain::Entity => anchor_namespace == "entity",
}
}
pub fn is_path_shaped(&self) -> bool {
matches!(
self,
AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorHashStability {
Stable,
Unstable,
}
impl AnchorHashStability {
pub const WIRE_VALUES: &'static [&'static str] = &["stable", "unstable"];
pub fn as_wire(&self) -> &'static str {
match self {
AnchorHashStability::Stable => "stable",
AnchorHashStability::Unstable => "unstable",
}
}
pub fn from_wire(s: &str) -> Option<Self> {
match s {
"stable" => Some(AnchorHashStability::Stable),
"unstable" => Some(AnchorHashStability::Unstable),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
pub enum AnchorVersion {
Commit(String),
Snapshot(String),
Etag(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Anchor {
pub artifact: String,
pub grain: AnchorGrain,
pub class: AnchorProvenanceClass,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at_version: Option<AnchorVersion>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
pub hash_stability: AnchorHashStability,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub derived_from: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub binding: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub span: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub span_hash: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub span_unvalidated: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash_source: Option<AnchorHashSource>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_observed: Option<AnchorObservation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnchorObservation {
pub at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
pub state: AnchorState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AnchorHashSource {
Author,
Backfill,
Pinned,
}
impl Anchor {
pub fn same_as_supplied(&self, other: &Anchor) -> bool {
self.artifact == other.artifact
&& self.grain == other.grain
&& self.class == other.class
&& self.at_version == other.at_version
&& self.hash_stability == other.hash_stability
&& self.derived_from == other.derived_from
&& self.binding == other.binding
&& self.source == other.source
&& same_span(self.span.as_deref(), other.span.as_deref())
&& self.span_unvalidated == other.span_unvalidated
&& other
.hash
.as_ref()
.is_none_or(|h| Some(h) == self.hash.as_ref())
}
}
pub fn same_span(a: Option<&str>, b: Option<&str>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => {
crate::preparation::canonical_span_form(a) == crate::preparation::canonical_span_form(b)
}
_ => false,
}
}
impl AnchorHashSource {
pub fn as_wire(self) -> &'static str {
match self {
AnchorHashSource::Author => "author",
AnchorHashSource::Backfill => "backfill",
AnchorHashSource::Pinned => "pinned",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanLocator<'a> {
Lines { start: usize, end: usize },
Unit(&'a str),
}
pub fn parse_span_locator(artifact: &str) -> Result<Option<SpanLocator<'_>>, &'static str> {
let locator = match artifact.split_once('#') {
None => return Ok(None),
Some((_, loc)) if loc.trim().is_empty() => {
return Err("the span locator after `#` is empty");
}
Some((_, loc)) => loc,
};
let looks_like_lines = locator.starts_with('L')
&& locator[1..]
.chars()
.next()
.is_some_and(|c| c.is_ascii_digit());
if !looks_like_lines {
return Ok(Some(SpanLocator::Unit(locator)));
}
let (start_raw, end_raw) = match locator.split_once('-') {
None => (locator, locator),
Some((a, b)) => (a, b),
};
let num = |part: &str| -> Option<usize> {
part.strip_prefix('L')
.filter(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
.and_then(|d| d.parse::<usize>().ok())
};
let (Some(start), Some(end)) = (num(start_raw), num(end_raw)) else {
return Err("a line-range span locator must read `L<start>` or `L<start>-L<end>`");
};
if start == 0 {
return Err("line numbers are 1-based, so `L0` addresses nothing");
}
if end < start {
return Err("a line-range span locator ends before it starts");
}
Ok(Some(SpanLocator::Lines { start, end }))
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnchorInput {
#[serde(default)]
pub artifact: Option<String>,
#[serde(default)]
pub grain: Option<String>,
#[serde(default)]
pub class: Option<String>,
#[serde(default)]
pub at_version: Option<AnchorVersion>,
#[serde(default)]
pub hash: Option<String>,
#[serde(default)]
pub content: Option<String>,
#[serde(default)]
pub span: Option<String>,
#[serde(default)]
pub hash_stability: Option<String>,
#[serde(default)]
pub derived_from: Option<Vec<String>>,
#[serde(default)]
pub binding: Option<String>,
#[serde(default)]
pub source: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnchorUnsetInput {
#[serde(default)]
pub artifact: Option<String>,
#[serde(default)]
pub grain: Option<String>,
#[serde(default)]
pub class: Option<String>,
#[serde(default)]
pub span: Option<String>,
}
impl AnchorUnsetInput {
pub fn validate(&self) -> Result<AnchorUnset, AnchorValidationError> {
let artifact = self
.artifact
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.ok_or(AnchorValidationError::MissingArtifact)?;
let grain = match self.grain.as_deref() {
None => None,
Some(s) => Some(AnchorGrain::from_wire(s).ok_or_else(|| {
AnchorValidationError::UnknownGrain {
got: Some(s.to_string()),
allowed: AnchorGrain::WIRE_VALUES,
}
})?),
};
let class = match self.class.as_deref() {
None => None,
Some(s) => Some(AnchorProvenanceClass::from_wire(s).ok_or_else(|| {
AnchorValidationError::UnknownClass {
got: Some(s.to_string()),
allowed: AnchorProvenanceClass::WIRE_VALUES,
}
})?),
};
let span = self
.span
.as_deref()
.map(crate::preparation::canonical_span_form)
.filter(|s| !s.is_empty());
Ok(AnchorUnset {
artifact,
grain,
class,
span,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnchorUnset {
pub artifact: String,
pub grain: Option<AnchorGrain>,
pub class: Option<AnchorProvenanceClass>,
pub span: Option<String>,
}
impl AnchorUnset {
pub fn matches(&self, anchor: &Anchor) -> bool {
anchor.artifact == self.artifact
&& self.grain.is_none_or(|g| anchor.grain == g)
&& self.class.is_none_or(|c| anchor.class == c)
&& self.span.as_deref().is_none_or(|s| {
anchor
.span
.as_deref()
.is_some_and(|have| crate::preparation::canonical_span_form(have) == s)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AnchorValidationError {
#[error("unknown anchor provenance class {got:?}; allowed: {}", allowed.join(", "))]
UnknownClass {
got: Option<String>,
allowed: &'static [&'static str],
},
#[error("unknown anchor grain {got:?}; allowed: {}", allowed.join(", "))]
UnknownGrain {
got: Option<String>,
allowed: &'static [&'static str],
},
#[error("unknown anchor hash stability {got:?}; allowed: {}", allowed.join(", "))]
UnknownHashStability {
got: String,
allowed: &'static [&'static str],
},
#[error("anchor is missing its artifact reference")]
MissingArtifact,
#[error("anchor class '{class}' carries no hash semantics — a content hash is not permitted")]
HashOnNonHashClass { class: &'static str },
#[error(
"anchor supplies both `hash` and `content`; supply one — the engine computes the hash from `content`"
)]
ContentAndHash,
#[error(
"anchor grain '{grain}' does not accept `content`: its prepared form is not computed \
from supplied bytes (accepted for span / file / url)"
)]
ContentNotAcceptedForGrain { grain: &'static str },
#[error(
"anchor artifact {artifact:?} names a delivery unit the supplied `content` does not \
yield; supply the whole file's content, or address a unit it contains"
)]
UnitAbsentFromContent { artifact: String },
#[error("anchor artifact {artifact:?} is not a usable span reference: {reason}")]
SpanLocatorUnusable {
artifact: String,
reason: &'static str,
},
#[error(
"anchor artifact {artifact:?} names lines the supplied `content` does not have \
(it has {lines} line(s)); address a range the artifact contains"
)]
SpanOutsideContent { artifact: String, lines: usize },
#[error(
"the anchors payload names {artifact:?} at grain `{grain}` and class `{class}`{} more \
than once; that identity is one row, so the repeats would silently collapse to the \
last one: send it once, or vary the grain, class or span",
span.as_deref().map(|s| format!(" with span {s:?}")).unwrap_or_default()
)]
DuplicateAnchorTriple {
artifact: String,
grain: &'static str,
class: &'static str,
span: Option<String>,
},
#[error(
"anchor supplies both `span` and `hash`; the engine computes a span row's hashes \
itself: supply the span with `content`, or a hash without a span"
)]
SpanAndHash,
#[error(
"anchor `span` is empty: a quoted span must carry at least one non-whitespace character"
)]
SpanEmpty,
#[error(
"anchor grain '{grain}' does not accept `span`: its prepared form is never computed \
from supplied text (accepted for url / span / file)"
)]
SpanNotAcceptedForGrain { grain: &'static str },
#[error(
"anchor artifact {artifact:?}: the span {span:?} does not occur in the supplied \
`content` (compared in the canonical span form: NFC, whitespace runs to one space, \
soft hyphens and line-end hyphens removed, typographic quotes, dashes and ligatures \
to ASCII; everything else exact); quote the words as the artifact carries them"
)]
SpanAbsentFromContent { artifact: String, span: String },
#[error("anchor `source`, when present, must be a non-empty source name")]
EmptySource,
#[error(
"anchor `source` {got:?} is not declared by the anchor's producing binding; \
declared sources: {}",
declared.join(", ")
)]
SourceNotDeclared { got: String, declared: Vec<String> },
#[error(
"anchor artifact {artifact:?} resolves under no candidate path (tried: {}); artifact \
paths are source-relative (joined onto the source's pointer) or workspace-relative — \
write the path exactly as the brief lists it",
candidates.join(", ")
)]
ArtifactUnresolvable {
artifact: String,
candidates: Vec<String>,
},
#[error(
"anchor grain '{grain}' is unsupported by a '{medium_type}' medium: its \
'{anchor_namespace}' namespace does not admit that grain"
)]
GrainNamespaceUnsupported {
grain: &'static str,
medium_type: String,
anchor_namespace: &'static str,
},
#[error(
"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"
)]
PathGrainOnUrlArtifact {
grain: &'static str,
artifact: String,
},
}
pub fn looks_like_url(artifact: &str) -> bool {
let Some((scheme, rest)) = artifact.split_once("://") else {
return false;
};
!rest.is_empty()
&& scheme
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}
impl AnchorValidationError {
pub fn code(&self) -> &'static str {
INVALID_ANCHOR_CODE
}
pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
let mut d = BTreeMap::new();
match self {
AnchorValidationError::UnknownClass { got, allowed } => {
d.insert("field".into(), "class".into());
d.insert("got".into(), serde_json::json!(got));
d.insert("allowed".into(), serde_json::json!(allowed));
}
AnchorValidationError::UnknownGrain { got, allowed } => {
d.insert("field".into(), "grain".into());
d.insert("got".into(), serde_json::json!(got));
d.insert("allowed".into(), serde_json::json!(allowed));
}
AnchorValidationError::UnknownHashStability { got, allowed } => {
d.insert("field".into(), "hash_stability".into());
d.insert("got".into(), serde_json::json!(got));
d.insert("allowed".into(), serde_json::json!(allowed));
}
AnchorValidationError::MissingArtifact => {
d.insert("field".into(), "artifact".into());
}
AnchorValidationError::EmptySource => {
d.insert("field".into(), "source".into());
}
AnchorValidationError::SourceNotDeclared { got, declared } => {
d.insert("field".into(), "source".into());
d.insert("got".into(), serde_json::json!(got));
d.insert("declared".into(), serde_json::json!(declared));
}
AnchorValidationError::HashOnNonHashClass { class } => {
d.insert("field".into(), "hash".into());
d.insert("class".into(), serde_json::json!(class));
}
AnchorValidationError::ContentAndHash => {
d.insert("field".into(), "content".into());
d.insert(
"expected".into(),
serde_json::json!("either `hash` or `content`, never both"),
);
}
AnchorValidationError::ContentNotAcceptedForGrain { grain } => {
d.insert("field".into(), "content".into());
d.insert("grain".into(), serde_json::json!(grain));
d.insert(
"accepted_grains".into(),
serde_json::json!(["span", "file", "url"]),
);
}
AnchorValidationError::UnitAbsentFromContent { artifact } => {
d.insert("field".into(), "content".into());
d.insert("got".into(), serde_json::json!(artifact));
}
AnchorValidationError::SpanLocatorUnusable { artifact, reason } => {
d.insert("field".into(), "artifact".into());
d.insert("got".into(), serde_json::json!(artifact));
d.insert("expected".into(), serde_json::json!(reason));
}
AnchorValidationError::SpanOutsideContent { artifact, lines } => {
d.insert("field".into(), "artifact".into());
d.insert("got".into(), serde_json::json!(artifact));
d.insert("content_lines".into(), serde_json::json!(lines));
}
AnchorValidationError::DuplicateAnchorTriple {
artifact,
grain,
class,
span,
} => {
d.insert("field".into(), "anchors".into());
d.insert(
"got".into(),
serde_json::json!({
"artifact": artifact, "grain": grain, "class": class, "span": span
}),
);
d.insert(
"expected".into(),
serde_json::json!(
"each (artifact, grain, class, span) identity at most once per payload"
),
);
}
AnchorValidationError::SpanAndHash => {
d.insert("field".into(), "span".into());
d.insert(
"expected".into(),
serde_json::json!("either `span` (with `content`) or `hash`, never both"),
);
}
AnchorValidationError::SpanEmpty => {
d.insert("field".into(), "span".into());
}
AnchorValidationError::SpanNotAcceptedForGrain { grain } => {
d.insert("field".into(), "span".into());
d.insert("grain".into(), serde_json::json!(grain));
d.insert(
"accepted_grains".into(),
serde_json::json!(["url", "span", "file"]),
);
}
AnchorValidationError::SpanAbsentFromContent { artifact, span } => {
d.insert("field".into(), "span".into());
d.insert("artifact".into(), serde_json::json!(artifact));
d.insert("got".into(), serde_json::json!(span));
d.insert(
"expected".into(),
serde_json::json!(
"the span, in the canonical span form, occurring in the canonical form \
of `content`"
),
);
}
AnchorValidationError::ArtifactUnresolvable {
artifact,
candidates,
} => {
d.insert("field".into(), "artifact".into());
d.insert("got".into(), serde_json::json!(artifact));
d.insert("candidates_tried".into(), serde_json::json!(candidates));
d.insert(
"expected".into(),
serde_json::json!(
"a source-relative path (joined onto the source's pointer) or a \
workspace-relative path that resolves to an existing artifact"
),
);
}
AnchorValidationError::GrainNamespaceUnsupported {
grain,
medium_type,
anchor_namespace,
} => {
d.insert("field".into(), "grain".into());
d.insert("grain".into(), serde_json::json!(grain));
d.insert("medium_type".into(), serde_json::json!(medium_type));
d.insert(
"anchor_namespace".into(),
serde_json::json!(anchor_namespace),
);
}
AnchorValidationError::PathGrainOnUrlArtifact { grain, artifact } => {
d.insert("field".into(), "grain".into());
d.insert("grain".into(), serde_json::json!(grain));
d.insert("got".into(), serde_json::json!(artifact));
d.insert(
"expected".into(),
serde_json::json!(
"`grain: url` for a web resource — a URL never enters a path namespace"
),
);
}
}
d
}
}
impl AnchorInput {
pub fn validate(&self, medium: Option<(&str, &str)>) -> Result<Anchor, AnchorValidationError> {
let class = match self
.class
.as_deref()
.and_then(AnchorProvenanceClass::from_wire)
{
Some(c) => c,
None => {
return Err(AnchorValidationError::UnknownClass {
got: self.class.clone(),
allowed: AnchorProvenanceClass::WIRE_VALUES,
});
}
};
let grain = match self.grain.as_deref().and_then(AnchorGrain::from_wire) {
Some(g) => g,
None => {
return Err(AnchorValidationError::UnknownGrain {
got: self.grain.clone(),
allowed: AnchorGrain::WIRE_VALUES,
});
}
};
let artifact = self
.artifact
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.ok_or(AnchorValidationError::MissingArtifact)?;
let hash_stability = match self.hash_stability.as_deref() {
None => crate::preparation::default_hash_stability(grain),
Some(s) => AnchorHashStability::from_wire(s).ok_or_else(|| {
AnchorValidationError::UnknownHashStability {
got: s.to_string(),
allowed: AnchorHashStability::WIRE_VALUES,
}
})?,
};
let hash = self
.hash
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string);
if (hash.is_some() || self.content.is_some() || self.span.is_some())
&& !class.is_hash_bearing()
{
return Err(AnchorValidationError::HashOnNonHashClass {
class: class.as_wire(),
});
}
let span = match self.span.as_deref() {
None => None,
Some(_) if hash.is_some() => return Err(AnchorValidationError::SpanAndHash),
Some(raw) => {
if crate::preparation::canonical_span_form(raw).is_empty() {
return Err(AnchorValidationError::SpanEmpty);
}
if matches!(grain, AnchorGrain::Entity | AnchorGrain::Tree) {
return Err(AnchorValidationError::SpanNotAcceptedForGrain {
grain: grain.as_wire(),
});
}
if let Some(content) = self.content.as_deref()
&& !crate::preparation::span_occurs(raw, content)
{
return Err(AnchorValidationError::SpanAbsentFromContent {
artifact: artifact.clone(),
span: raw.trim().to_string(),
});
}
Some(raw.trim().to_string())
}
};
let span_hash = span.as_deref().map(crate::preparation::span_hash);
let mut span_unvalidated = span.is_some() && self.content.is_none();
let hash = match self.content.as_deref() {
None => hash,
Some(_) if hash.is_some() => return Err(AnchorValidationError::ContentAndHash),
Some(content) => {
match crate::preparation::supplied_content_hash(grain, content.as_bytes()) {
Some(h) => Some(h),
None => {
return Err(AnchorValidationError::ContentNotAcceptedForGrain {
grain: grain.as_wire(),
});
}
}
}
};
if grain == AnchorGrain::Span {
let locator = parse_span_locator(&artifact).map_err(|reason| {
AnchorValidationError::SpanLocatorUnusable {
artifact: artifact.clone(),
reason,
}
})?;
match (locator, self.content.as_deref()) {
(Some(SpanLocator::Lines { end, .. }), Some(content)) => {
let lines = content.lines().count();
if end > lines {
return Err(AnchorValidationError::SpanOutsideContent {
artifact: artifact.clone(),
lines,
});
}
}
(Some(SpanLocator::Unit(_)), Some(_)) => {}
(None, _) => {}
(Some(_), None) => span_unvalidated = true,
}
}
if grain.is_path_shaped() && looks_like_url(&artifact) {
return Err(AnchorValidationError::PathGrainOnUrlArtifact {
grain: grain.as_wire(),
artifact,
});
}
if let Some((medium_type, namespace)) = medium
&& !grain.supported_by_namespace(namespace)
{
let anchor_namespace = match namespace {
"path" => "path",
"path+commit" => "path+commit",
"entity" => "entity",
"url" => "url",
_ => "path",
};
return Err(AnchorValidationError::GrainNamespaceUnsupported {
grain: grain.as_wire(),
medium_type: medium_type.to_string(),
anchor_namespace,
});
}
let source = match self.source.as_deref() {
None => None,
Some(raw) => {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(AnchorValidationError::EmptySource);
}
Some(trimmed.to_string())
}
};
Ok(Anchor {
artifact,
grain,
class,
at_version: self.at_version.clone(),
hash_source: hash.is_some().then_some(AnchorHashSource::Author),
hash,
hash_stability,
derived_from: self.derived_from.clone().unwrap_or_default(),
binding: self
.binding
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string),
source,
span,
span_hash,
span_unvalidated,
last_observed: None,
})
}
}
pub fn prepared_content_hash(bytes: &[u8]) -> String {
use sha2::{Digest as _, Sha256};
let digest = match std::str::from_utf8(bytes) {
Ok(text) => {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
Sha256::digest(normalized.trim_end_matches('\n').as_bytes())
}
Err(_) => Sha256::digest(bytes),
};
crate::hex_lower(&digest)[..16].to_string()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObservedArtifactHash {
pub entity: String,
pub artifact: String,
pub hash: String,
}
pub const INVALID_OBSERVATION_CODE: &str = "INVALID_OBSERVATION";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppliedObservationInput {
#[serde(default)]
pub artifact: Option<String>,
#[serde(default)]
pub hash: Option<String>,
#[serde(default)]
pub content: Option<String>,
#[serde(default)]
pub absent: Option<bool>,
#[serde(default)]
pub observed_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuppliedOutcome {
Present {
hash: String,
content: Option<String>,
},
Absent,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SuppliedObservation {
pub artifact: String,
pub at: String,
pub outcome: SuppliedOutcome,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ObservationValidationError {
#[error("observation row {row}: `artifact` is required and must be non-empty")]
MissingArtifact { row: usize },
#[error(
"observation row {row} (`{artifact}`): give exactly one of `hash`, `content`, or \
`absent: true`"
)]
OutcomeAmbiguous { row: usize, artifact: String },
#[error(
"observation row {row} (`{artifact}`): `observed_at` '{got}' is not an ISO-8601 \
timestamp (`YYYY-MM-DDTHH:MM:SSZ`) or date (`YYYY-MM-DD`)"
)]
BadTimestamp {
row: usize,
artifact: String,
got: String,
},
#[error("observation rows name `{artifact}` more than once (rows {first} and {second})")]
DuplicateArtifact {
artifact: String,
first: usize,
second: usize,
},
}
impl ObservationValidationError {
pub fn code(&self) -> &'static str {
INVALID_OBSERVATION_CODE
}
pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
let mut d = BTreeMap::new();
match self {
ObservationValidationError::MissingArtifact { row } => {
d.insert("row".into(), serde_json::json!(row));
d.insert("field".into(), "artifact".into());
}
ObservationValidationError::OutcomeAmbiguous { row, artifact } => {
d.insert("row".into(), serde_json::json!(row));
d.insert("artifact".into(), serde_json::json!(artifact));
d.insert(
"expected".into(),
serde_json::json!("exactly one of `hash`, `content`, `absent: true`"),
);
}
ObservationValidationError::BadTimestamp { row, artifact, got } => {
d.insert("row".into(), serde_json::json!(row));
d.insert("artifact".into(), serde_json::json!(artifact));
d.insert("field".into(), "observed_at".into());
d.insert("got".into(), serde_json::json!(got));
}
ObservationValidationError::DuplicateArtifact {
artifact,
first,
second,
} => {
d.insert("artifact".into(), serde_json::json!(artifact));
d.insert("rows".into(), serde_json::json!([first, second]));
}
}
d
}
}
fn timestamp_is_wellformed(ts: &str) -> bool {
let b = ts.as_bytes();
let date_ok = b.len() >= 10
&& b[..10].iter().enumerate().all(|(i, c)| {
if i == 4 || i == 7 {
*c == b'-'
} else {
c.is_ascii_digit()
}
});
if !date_ok {
return false;
}
if b.len() == 10 {
return true;
}
b.len() == 20
&& b[10] == b'T'
&& b[19] == b'Z'
&& b[11..19].iter().enumerate().all(|(i, c)| {
if i == 2 || i == 5 {
*c == b':'
} else {
c.is_ascii_digit()
}
})
}
pub fn validate_supplied_observations(
rows: &[SuppliedObservationInput],
now: &str,
) -> Result<BTreeMap<String, SuppliedObservation>, ObservationValidationError> {
let mut out: BTreeMap<String, SuppliedObservation> = BTreeMap::new();
let mut first_row: BTreeMap<String, usize> = BTreeMap::new();
for (i, row) in rows.iter().enumerate() {
let n = i + 1;
let artifact = row
.artifact
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or(ObservationValidationError::MissingArtifact { row: n })?
.to_string();
let absent = row.absent.unwrap_or(false);
let given = usize::from(row.hash.is_some())
+ usize::from(row.content.is_some())
+ usize::from(absent);
if given != 1 {
return Err(ObservationValidationError::OutcomeAmbiguous { row: n, artifact });
}
let at = match row.observed_at.as_deref().map(str::trim) {
None | Some("") => now.to_string(),
Some(ts) if timestamp_is_wellformed(ts) => ts.to_string(),
Some(ts) => {
return Err(ObservationValidationError::BadTimestamp {
row: n,
artifact,
got: ts.to_string(),
});
}
};
if let Some(first) = first_row.get(&artifact) {
return Err(ObservationValidationError::DuplicateArtifact {
artifact,
first: *first,
second: n,
});
}
let outcome = if absent {
SuppliedOutcome::Absent
} else if let Some(hash) = &row.hash {
SuppliedOutcome::Present {
hash: hash.trim().to_string(),
content: None,
}
} else {
let content = row.content.clone().unwrap_or_default();
SuppliedOutcome::Present {
hash: prepared_content_hash(content.as_bytes()),
content: Some(content),
}
};
first_row.insert(artifact.clone(), n);
out.insert(
artifact.clone(),
SuppliedObservation {
artifact,
at,
outcome,
},
);
}
Ok(out)
}
pub fn iso_days_since_epoch(ts: &str) -> Option<i64> {
if !timestamp_is_wellformed(ts) {
return None;
}
let y: i64 = ts[..4].parse().ok()?;
let m: u32 = ts[5..7].parse().ok()?;
let d: u32 = ts[8..10].parse().ok()?;
if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = ((m + 9) % 12) as i64;
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some(era * 146097 + doe - 719468)
}
pub fn days_between(observed_at: &str, now: &str) -> Option<u64> {
let a = iso_days_since_epoch(observed_at)?;
let b = iso_days_since_epoch(now)?;
Some((b - a).max(0) as u64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorState {
Resolves,
Drifted,
Recheck,
Orphaned,
#[serde(rename = "span_absent")]
SpanAbsent,
}
impl AnchorState {
pub const ALL: [AnchorState; 5] = [
AnchorState::Resolves,
AnchorState::Drifted,
AnchorState::Recheck,
AnchorState::Orphaned,
AnchorState::SpanAbsent,
];
pub fn as_wire(&self) -> &'static str {
match self {
AnchorState::Resolves => "resolves",
AnchorState::Drifted => "drifted",
AnchorState::Recheck => "recheck",
AnchorState::Orphaned => "orphaned",
AnchorState::SpanAbsent => "span_absent",
}
}
pub fn describe(&self) -> &'static str {
match self {
AnchorState::Resolves => "the artifact is present and matches",
AnchorState::Drifted => {
"present, hash differs, the medium is stable, so a real content drift"
}
AnchorState::Recheck => {
"present, but drift cannot be asserted (unstable medium, or a hash missing on one side)"
}
AnchorState::Orphaned => "the artifact the anchor references is gone from the medium",
AnchorState::SpanAbsent => {
"present, but the words the row quotes (its span) no longer occur in it"
}
}
}
pub fn vocabulary_help() -> String {
let mut s = String::from("Anchor states (the artifact end of an anchor):\n");
for state in Self::ALL {
s.push_str(&format!(" {:<11} {}\n", state.as_wire(), state.describe()));
}
s.push_str(
"Not states: `dangling` (a sidecar row whose entity the mem no longer holds) and \
`unobserved` (the pass did not reach the artifact) are conditions of the \
measurement, counted apart.",
);
s
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RawFigure")]
pub struct AnchorResolutionFigure {
resolves: usize,
population: String,
fully_adjudicated: bool,
}
#[derive(Deserialize)]
struct RawFigure {
resolves: usize,
population: String,
fully_adjudicated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("an anchor resolution figure cannot exist without the population it was computed over")]
pub struct FigureWithoutPopulation;
impl TryFrom<RawFigure> for AnchorResolutionFigure {
type Error = FigureWithoutPopulation;
fn try_from(raw: RawFigure) -> Result<Self, Self::Error> {
Self::new(raw.resolves, raw.population, raw.fully_adjudicated)
}
}
impl AnchorResolutionFigure {
pub fn new(
resolves: usize,
population: impl Into<String>,
fully_adjudicated: bool,
) -> Result<Self, FigureWithoutPopulation> {
let population = population.into();
if population.trim().is_empty() {
return Err(FigureWithoutPopulation);
}
Ok(Self {
resolves,
population,
fully_adjudicated,
})
}
pub(crate) fn uncounted(why: impl Into<String>) -> Self {
Self::new(0, why, false).expect("an uncounted figure names why it counted nothing")
}
pub fn population(&self) -> &str {
&self.population
}
pub fn fully_adjudicated(&self) -> bool {
self.fully_adjudicated
}
pub fn ratio(&self, denominator: usize) -> String {
if denominator == 0 {
format!("{}/{denominator} (n/a) {}", self.resolves, self.population)
} else {
let pct = (self.resolves as f64) * 100.0 / (denominator as f64);
format!(
"{}/{denominator} ({pct:.1}%) {}",
self.resolves, self.population
)
}
}
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
Self::new(
v.get("resolves")?.as_u64()? as usize,
v.get("population")?.as_str()?,
v.get("fully_adjudicated")?.as_bool()?,
)
.ok()
}
#[cfg(any(test, feature = "test-support"))]
pub fn count_for_assertions(&self) -> usize {
self.resolves
}
}
impl Default for AnchorResolutionFigure {
fn default() -> Self {
Self::uncounted("population unknown: no row was counted")
}
}
impl std::fmt::Display for AnchorResolutionFigure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.resolves, self.population)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactObservation {
Absent,
Present { current_hash: Option<String> },
}
pub fn resolve_anchor(anchor: &Anchor, observation: &ArtifactObservation) -> AnchorState {
let current_hash = match observation {
ArtifactObservation::Absent => return AnchorState::Orphaned,
ArtifactObservation::Present { current_hash } => current_hash,
};
if anchor.span.is_some() {
return AnchorState::Recheck;
}
if !anchor.class.is_hash_bearing() {
return AnchorState::Resolves;
}
match (&anchor.hash, current_hash) {
(Some(recorded), Some(current)) if recorded == current => AnchorState::Resolves,
(Some(_), Some(_)) => match anchor.hash_stability {
AnchorHashStability::Stable => AnchorState::Drifted,
AnchorHashStability::Unstable => AnchorState::Recheck,
},
_ => AnchorState::Recheck,
}
}
pub fn resolve_span_anchor(anchor: &Anchor, text: &str) -> AnchorState {
match anchor.span.as_deref() {
Some(span) if crate::preparation::span_occurs(span, text) => AnchorState::Resolves,
Some(_) => AnchorState::SpanAbsent,
None => AnchorState::Recheck,
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityAnchorComposition {
pub by_class: BTreeMap<String, usize>,
pub by_grain: BTreeMap<String, usize>,
pub derived_inputs: Vec<Vec<String>>,
pub tree_grain_artifacts: Vec<String>,
}
pub fn compose_entity_anchors(anchors: &[Anchor]) -> EntityAnchorComposition {
let mut comp = EntityAnchorComposition::default();
for a in anchors {
*comp
.by_class
.entry(a.class.as_wire().to_string())
.or_insert(0) += 1;
*comp
.by_grain
.entry(a.grain.as_wire().to_string())
.or_insert(0) += 1;
if a.class == AnchorProvenanceClass::Derived {
comp.derived_inputs.push(a.derived_from.clone());
}
if a.grain == AnchorGrain::Tree {
comp.tree_grain_artifacts.push(a.artifact.clone());
}
}
comp
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnchorSidecar {
pub version: u32,
#[serde(default)]
pub entities: BTreeMap<String, Vec<Anchor>>,
}
impl Default for AnchorSidecar {
fn default() -> Self {
Self {
version: ANCHOR_SIDECAR_VERSION,
entities: BTreeMap::new(),
}
}
}
impl AnchorSidecar {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
if bytes.iter().all(u8::is_ascii_whitespace) {
return Ok(Self::default());
}
let sidecar: Self = serde_json::from_slice(bytes)?;
if !ANCHOR_SIDECAR_VERSIONS_READ.contains(&sidecar.version) {
return Err(serde::de::Error::custom(format!(
"unsupported anchors sidecar version {} (this engine reads versions {}) — \
the file was written by a different engine; upgrade, or remove the sidecar \
to re-record anchors",
sidecar.version,
ANCHOR_SIDECAR_VERSIONS_READ
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(", ")
)));
}
let mut sidecar = sidecar;
sidecar.version = sidecar.required_version();
Ok(sidecar)
}
pub fn required_version(&self) -> u32 {
let needs_v3 = self
.entities
.values()
.flatten()
.any(|a| a.span.is_some() || a.hash_source == Some(AnchorHashSource::Pinned));
if needs_v3 {
ANCHOR_SIDECAR_SPAN_VERSION
} else {
ANCHOR_SIDECAR_VERSION
}
}
pub fn to_bytes(&self) -> Vec<u8> {
#[derive(Serialize)]
struct Wire<'a> {
version: u32,
entities: &'a BTreeMap<String, Vec<Anchor>>,
}
let wire = Wire {
version: self.required_version(),
entities: &self.entities,
};
let mut s = serde_json::to_string_pretty(&wire).expect("anchor sidecar serialises");
s.push('\n');
s.into_bytes()
}
pub fn get(&self, entity_id: &str) -> &[Anchor] {
self.entities
.get(entity_id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn set(&mut self, entity_id: &str, anchors: Vec<Anchor>) {
if anchors.is_empty() {
self.entities.remove(entity_id);
} else {
self.entities.insert(entity_id.to_string(), anchors);
}
}
pub fn merge(
&mut self,
entity_id: &str,
unsets: &[AnchorUnset],
incoming: Vec<Anchor>,
rebaseline: bool,
) -> bool {
let mut row = self.entities.remove(entity_id).unwrap_or_default();
let before = row.len();
row.retain(|a| !unsets.iter().any(|u| u.matches(a)));
let mut changed = row.len() != before;
for anchor in incoming {
match row.iter_mut().find(|e| {
e.artifact == anchor.artifact
&& e.grain == anchor.grain
&& e.class == anchor.class
&& same_span(e.span.as_deref(), anchor.span.as_deref())
}) {
Some(existing) => {
if !rebaseline && existing.same_as_supplied(&anchor) {
continue;
}
*existing = anchor;
changed = true;
}
None => {
row.push(anchor);
changed = true;
}
}
}
if !row.is_empty() {
self.entities.insert(entity_id.to_string(), row);
}
changed
}
pub fn redact_artifact_references(&mut self) {
for anchors in self.entities.values_mut() {
for anchor in anchors {
anchor.artifact = REDACTED_ARTIFACT_SENTINEL.to_string();
for input in &mut anchor.derived_from {
*input = REDACTED_ARTIFACT_SENTINEL.to_string();
}
}
}
}
pub fn validate_artifact_references(&self) -> Result<(), String> {
for (entity_id, anchors) in &self.entities {
for anchor in anchors {
if anchor.artifact.trim().is_empty() {
return Err(format!(
"entity `{entity_id}` carries an anchor with an empty artifact \
reference"
));
}
if anchor.derived_from.iter().any(|d| d.trim().is_empty()) {
return Err(format!(
"entity `{entity_id}` carries an anchor with an empty \
`derived_from` entry"
));
}
}
}
Ok(())
}
pub fn remove(&mut self, entity_id: &str) {
self.entities.remove(entity_id);
}
pub fn rename(&mut self, from: &str, to: &str) {
if let Some(anchors) = self.entities.remove(from) {
self.entities.insert(to.to_string(), anchors);
}
}
pub fn is_empty(&self) -> bool {
self.entities.is_empty()
}
}
#[cfg(test)]
mod figure_and_vocabulary;
#[cfg(test)]
mod tests;