use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use crate::pipeline::{IngestTrigger, MediumType, PatternEntry, Source};
pub const BINDING_VERSION: u32 = 2;
pub const PREPARATION_IMPL_VERSION: u32 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CoverageSemantics {
Exhaustive,
Curated,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BuildMode {
Discovery,
OneShot,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuildOperation {
pub mode: BuildMode,
pub trigger: IngestTrigger,
pub batch_size: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub post_actions: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncOperation {
pub trigger: IngestTrigger,
pub batch_size: u32,
}
pub const DEFAULT_ADJUDICATION_CAP: u32 = 50;
pub const DEFAULT_FULL_RESYNC_EVERY: u32 = 20;
fn default_adjudication_cap() -> u32 {
DEFAULT_ADJUDICATION_CAP
}
fn default_full_resync_every() -> u32 {
DEFAULT_FULL_RESYNC_EVERY
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerifyOperation {
pub trigger: IngestTrigger,
pub batch_size: u32,
#[serde(default = "default_adjudication_cap")]
pub adjudication_cap: u32,
#[serde(default = "default_full_resync_every")]
pub full_resync_every: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PruneConfig {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Operations {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub build: Option<BuildOperation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sync: Option<SyncOperation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub verify: Option<VerifyOperation>,
}
pub const DEFAULT_SCAFFOLD_DENY_PATHS: &[&str] = &[
"**/.DS_Store",
"**/.git/**",
"**/node_modules/**",
"**/Thumbs.db",
];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Binding {
pub version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intent: Option<String>,
#[serde(default)]
pub sources: Vec<Source>,
#[serde(default)]
pub reference_mems: Vec<String>,
pub destination_mem: String,
#[serde(default)]
pub deny_paths: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub coverage_semantics: Option<CoverageSemantics>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rules: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prune: Option<PruneConfig>,
pub operations: Operations,
}
#[derive(Serialize)]
struct HashSource<'a> {
source: &'a str,
patterns: &'a [PatternEntry],
preparation: &'a Option<String>,
preparation_impl_version: u32,
medium_type: MediumType,
pointer: &'a str,
change_detection: &'a Option<String>,
}
#[derive(Serialize)]
struct HashInput<'a> {
version: u32,
intent: &'a Option<String>,
sources: Vec<HashSource<'a>>,
reference_mems: &'a [String],
destination_mem: &'a str,
deny_paths: &'a [String],
coverage_semantics: CoverageSemantics,
rules: &'a Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
build_mode: Option<BuildMode>,
}
fn canonical_json(value: &serde_json::Value) -> String {
fn sorted(v: &serde_json::Value) -> serde_json::Value {
match v {
serde_json::Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let mut out = serde_json::Map::new();
for k in keys {
out.insert(k.clone(), sorted(&map[k]));
}
serde_json::Value::Object(out)
}
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.iter().map(sorted).collect())
}
other => other.clone(),
}
}
serde_json::to_string(&sorted(value)).expect("canonical JSON serializes")
}
pub fn hash_binding(binding: &Binding) -> String {
hash_binding_at_impl_version(binding, PREPARATION_IMPL_VERSION)
}
pub fn hash_binding_at_impl_version(binding: &Binding, preparation_impl_version: u32) -> String {
let sources: Vec<HashSource<'_>> = binding
.sources
.iter()
.map(|s| HashSource {
source: &s.name,
patterns: &s.scope,
preparation: &s.preparation,
preparation_impl_version,
medium_type: s.medium_type,
pointer: &s.pointer,
change_detection: &s.change_detection,
})
.collect();
let input = HashInput {
version: binding.version,
intent: &binding.intent,
sources,
reference_mems: &binding.reference_mems,
destination_mem: &binding.destination_mem,
deny_paths: &binding.deny_paths,
coverage_semantics: effective_coverage_semantics(binding).value,
rules: &binding.rules,
build_mode: binding.operations.build.as_ref().map(|b| b.mode),
};
let value = serde_json::to_value(&input).expect("hash input serializes to a JSON value");
let canonical = canonical_json(&value);
let digest = Sha256::digest(canonical.as_bytes());
crate::hex_lower(&digest)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MediumCapabilities {
pub enumerable: bool,
pub change_signal: bool,
pub base_version_retrievable: bool,
pub anchor_namespace: &'static str,
pub glob_deny_legal: bool,
}
pub fn medium_capabilities(medium_type: MediumType) -> MediumCapabilities {
match medium_type {
MediumType::Codebase => MediumCapabilities {
enumerable: true,
change_signal: true,
base_version_retrievable: true,
anchor_namespace: "path",
glob_deny_legal: true,
},
MediumType::Filesystem => MediumCapabilities {
enumerable: true,
change_signal: true,
base_version_retrievable: true,
anchor_namespace: "path",
glob_deny_legal: true,
},
MediumType::Git => MediumCapabilities {
enumerable: true,
change_signal: true,
base_version_retrievable: true,
anchor_namespace: "path+commit",
glob_deny_legal: true,
},
MediumType::Graph => MediumCapabilities {
enumerable: true,
change_signal: true,
base_version_retrievable: true,
anchor_namespace: "entity",
glob_deny_legal: false,
},
MediumType::Web => MediumCapabilities {
enumerable: false,
change_signal: false,
base_version_retrievable: false,
anchor_namespace: "url",
glob_deny_legal: false,
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EffectiveCoverage {
pub value: CoverageSemantics,
pub declared: bool,
}
pub fn effective_coverage_semantics(binding: &Binding) -> EffectiveCoverage {
if let Some(declared) = binding.coverage_semantics {
return EffectiveCoverage {
value: declared,
declared: true,
};
}
let all_enumerable = binding
.sources
.iter()
.all(|s| medium_capabilities(s.medium_type).enumerable);
EffectiveCoverage {
value: if all_enumerable {
CoverageSemantics::Exhaustive
} else {
CoverageSemantics::Curated
},
declared: false,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation {
Sync,
Verify,
}
impl Operation {
fn name(self) -> &'static str {
match self {
Operation::Sync => "sync",
Operation::Verify => "verify",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CapabilityError {
#[error("a source has an empty name: every source names itself (the name keys its state)")]
EmptySourceName,
#[error(
"source '{source_name}' declares a scope pattern that is not a valid glob: \
'{pattern}' ({reason})"
)]
MalformedScopePattern {
source_name: String,
pattern: String,
reason: String,
},
#[error(
"duplicate source name '{name}': source names are unique within a binding \
(they key per-source sync/verify state)"
)]
DuplicateSourceName {
name: String,
},
#[error(
"operation '{operation}' is out of scope for source '{source_name}' over a '{medium_type}' \
medium: this medium has no change signal"
)]
OperationOutOfScope {
operation: &'static str,
source_name: String,
medium_type: String,
},
#[error(
"scope pattern '{pattern}' on source '{source_name}' is not a legal entity selector: a \
graph medium selects entities, not paths — write '*' for the whole mem, \
'type:<entity_type>', or 'id:<glob>'"
)]
GraphScopeNotEntitySelector {
source_name: String,
pattern: String,
},
#[error(
"scope pattern '{pattern}' on source '{source_name}' cannot be interpreted: a \
'{medium_type}' medium has no scope vocabulary, so the pattern would select \
nothing while looking like selection — remove the scope rule"
)]
ScopeNotInterpretable {
source_name: String,
pattern: String,
medium_type: String,
},
#[error(
"glob deny_paths are illegal for source '{source_name}' over a '{medium_type}' medium: its \
'{anchor_namespace}' namespace is not path-shaped"
)]
GlobDenyIllegal {
source_name: String,
medium_type: String,
anchor_namespace: &'static str,
},
#[error(
"source '{source_name}' declares preparation '{preparation}', which is not in this \
engine's preparation registry (registered: {}; preparation impl version {impl_version})",
crate::preparation::registered_identifiers().join(", ")
)]
PreparationUnsupported {
source_name: String,
preparation: String,
impl_version: u32,
},
#[error(
"source '{source_name}' declares preparation '{preparation}' over a '{medium_type}' \
medium whose '{anchor_namespace}' anchor namespace admits none of the grains it \
prepares"
)]
PreparationGrainMismatch {
source_name: String,
preparation: String,
medium_type: String,
anchor_namespace: &'static str,
},
#[error(
"coverage_semantics 'exhaustive' is unsupported for source '{source_name}' over a \
'{medium_type}' medium: its scope is not enumerable (S(D) is not computable), so \
exhaustive coverage cannot be asserted — declare 'curated', or omit the field to \
resolve per medium"
)]
CoverageExhaustiveUnsupported {
source_name: String,
medium_type: String,
},
}
pub fn validate_binding(binding: &Binding) -> Result<(), Vec<CapabilityError>> {
let mut refusals = Vec::new();
let has_deny = !binding.deny_paths.is_empty();
let sync_declared = binding.operations.sync.is_some();
let verify_declared = binding.operations.verify.is_some();
let mut seen_names: Vec<&str> = Vec::new();
for source in &binding.sources {
if source.name.is_empty() {
refusals.push(CapabilityError::EmptySourceName);
} else if seen_names.contains(&source.name.as_str()) {
refusals.push(CapabilityError::DuplicateSourceName {
name: source.name.clone(),
});
} else {
seen_names.push(&source.name);
}
if !matches!(source.medium_type, MediumType::Graph | MediumType::Web) {
for rule in &source.scope {
if let Err(e) = globset::Glob::new(&rule.path) {
refusals.push(CapabilityError::MalformedScopePattern {
source_name: source.name.clone(),
pattern: rule.path.clone(),
reason: e.to_string(),
});
}
}
}
let caps = medium_capabilities(source.medium_type);
let medium_type = serde_json::to_value(source.medium_type)
.ok()
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default();
if let Some(prep) = &source.preparation {
match crate::preparation::lookup(prep) {
None => refusals.push(CapabilityError::PreparationUnsupported {
source_name: source.name.clone(),
preparation: prep.clone(),
impl_version: PREPARATION_IMPL_VERSION,
}),
Some(registered)
if !crate::preparation::applies_to_namespace(
registered,
caps.anchor_namespace,
) =>
{
refusals.push(CapabilityError::PreparationGrainMismatch {
source_name: source.name.clone(),
preparation: prep.clone(),
medium_type: medium_type.clone(),
anchor_namespace: caps.anchor_namespace,
});
}
Some(_) => {}
}
}
if !caps.change_signal {
for (declared, op) in [
(sync_declared, Operation::Sync),
(verify_declared, Operation::Verify),
] {
if declared {
refusals.push(CapabilityError::OperationOutOfScope {
operation: op.name(),
source_name: source.name.clone(),
medium_type: medium_type.clone(),
});
}
}
}
match source.medium_type {
MediumType::Graph => {
for rule in &source.scope {
if crate::source_scope::parse_entity_selector(&rule.path).is_none() {
refusals.push(CapabilityError::GraphScopeNotEntitySelector {
source_name: source.name.clone(),
pattern: rule.path.clone(),
});
}
}
}
MediumType::Web => {
for rule in &source.scope {
refusals.push(CapabilityError::ScopeNotInterpretable {
source_name: source.name.clone(),
pattern: rule.path.clone(),
medium_type: medium_type.clone(),
});
}
}
MediumType::Codebase | MediumType::Filesystem | MediumType::Git => {}
}
if has_deny && !caps.glob_deny_legal {
refusals.push(CapabilityError::GlobDenyIllegal {
source_name: source.name.clone(),
medium_type: medium_type.clone(),
anchor_namespace: caps.anchor_namespace,
});
}
if binding.coverage_semantics == Some(CoverageSemantics::Exhaustive) && !caps.enumerable {
refusals.push(CapabilityError::CoverageExhaustiveUnsupported {
source_name: source.name.clone(),
medium_type: medium_type.clone(),
});
}
}
if refusals.is_empty() {
Ok(())
} else {
Err(refusals)
}
}
#[derive(Debug, Clone)]
pub struct ScaffoldParams<'a> {
pub destination_mem: &'a str,
pub source_name: &'a str,
pub pointer: &'a str,
pub medium_type: MediumType,
pub intent: Option<String>,
pub additional_deny_paths: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ScaffoldedBinding {
pub binding: Binding,
pub operations: Vec<&'static str>,
pub warnings: Vec<String>,
}
pub fn scaffold_binding(params: ScaffoldParams<'_>) -> ScaffoldedBinding {
let ScaffoldParams {
destination_mem,
source_name,
pointer,
medium_type,
intent,
additional_deny_paths,
} = params;
let source = Source {
name: source_name.to_string(),
medium_type,
pointer: pointer.to_string(),
change_detection: None,
scope: match medium_type {
MediumType::Graph => vec![PatternEntry {
path: "*".to_string(),
mode: crate::pipeline::PatternMode::Allow,
}],
MediumType::Web => Vec::new(),
_ => vec![PatternEntry {
path: "**/*".to_string(),
mode: crate::pipeline::PatternMode::Allow,
}],
},
engagement: None,
preparation: None,
};
let mut deny_paths: Vec<String> =
if matches!(medium_type, MediumType::Codebase | MediumType::Filesystem) {
DEFAULT_SCAFFOLD_DENY_PATHS
.iter()
.map(|s| s.to_string())
.collect()
} else {
Vec::new()
};
for extra in additional_deny_paths {
if !deny_paths.contains(&extra) {
deny_paths.push(extra);
}
}
let mut binding = Binding {
version: BINDING_VERSION,
intent,
sources: vec![source],
reference_mems: Vec::new(),
destination_mem: destination_mem.to_string(),
deny_paths,
coverage_semantics: None,
rules: None,
prune: None,
operations: Operations {
build: Some(BuildOperation {
mode: BuildMode::Discovery,
trigger: IngestTrigger::Loop,
batch_size: 20,
post_actions: None,
}),
sync: Some(SyncOperation {
trigger: IngestTrigger::Manual,
batch_size: 20,
}),
verify: Some(VerifyOperation {
trigger: IngestTrigger::Manual,
batch_size: 20,
adjudication_cap: DEFAULT_ADJUDICATION_CAP,
full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
}),
},
};
let mut warnings: Vec<String> = Vec::new();
if let Err(refusals) = validate_binding(&binding) {
for r in &refusals {
if let CapabilityError::OperationOutOfScope { operation, .. } = r {
match *operation {
"sync" => binding.operations.sync = None,
"verify" => binding.operations.verify = None,
_ => {}
}
}
warnings.push(r.to_string());
}
}
if binding.operations.sync.is_some() {
binding.prune = Some(PruneConfig::default());
}
let mut operations: Vec<&'static str> = vec!["build"];
if binding.operations.sync.is_some() {
operations.push("sync");
}
if binding.operations.verify.is_some() {
operations.push("verify");
}
ScaffoldedBinding {
binding,
operations,
warnings,
}
}
#[cfg(test)]
mod scaffold_tests;
#[cfg(test)]
mod tests;