use serde::{Deserialize, Serialize};
use crate::decay::StalenessPolicy;
use crate::id::UnitId;
use crate::kind::UnitKind;
use crate::time::Timestamp;
pub const SCHEMA_VERSION: &str = "1.0.0";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KnowledgeUnit {
pub id: UnitId,
pub version: String,
pub domain: Vec<String>,
pub insight: Insight,
pub context: UnitContext,
pub evidence: Evidence,
pub provenance: Provenance,
pub lifecycle: Lifecycle,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Insight {
pub summary: String,
pub detail: String,
pub action: String,
}
impl Insight {
pub fn new(
summary: impl Into<String>,
detail: impl Into<String>,
action: impl Into<String>,
) -> Self {
Self {
summary: summary.into().trim().to_string(),
detail: detail.into().trim().to_string(),
action: action.into().trim().to_string(),
}
}
pub fn embedded_len(&self) -> usize {
self.summary.chars().count() + self.detail.chars().count() + self.action.chars().count()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnitContext {
#[serde(default)]
pub language: Vec<String>,
#[serde(default)]
pub frameworks: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub environment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Low,
#[default]
Medium,
High,
Critical,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Evidence {
pub severity: Severity,
pub confidence: f64,
pub confirmations: u32,
pub contributing_orgs: u32,
pub first_observed: Timestamp,
pub last_confirmed: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_queried_at: Option<Timestamp>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
Local,
#[serde(rename = "remote")]
Shared,
#[serde(rename = "global")]
Public,
}
impl Tier {
pub const ALL: [Tier; 3] = [Tier::Local, Tier::Shared, Tier::Public];
pub const fn rank(self) -> u8 {
match self {
Tier::Local => 0,
Tier::Shared => 1,
Tier::Public => 2,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Provenance {
pub proposer_did: String,
#[serde(default)]
pub graduation_history: Vec<Graduation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Graduation {
pub from: Tier,
pub to: Tier,
pub approved_by: String,
pub timestamp: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorising_event: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitStatus {
#[default]
Draft,
Active,
Stale,
Disputed,
Superseded,
Retired,
}
impl UnitStatus {
pub const fn is_servable(self) -> bool {
matches!(
self,
UnitStatus::Draft | UnitStatus::Active | UnitStatus::Stale | UnitStatus::Disputed
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RelationKind {
Extends,
Continues,
Contradicts,
AggregatedInto,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Related {
pub id: UnitId,
#[serde(rename = "type")]
pub kind: RelationKind,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Lifecycle {
pub status: UnitStatus,
pub kind: UnitKind,
pub staleness_policy: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub superseded_by: Option<UnitId>,
#[serde(default)]
pub related: Vec<Related>,
}
impl KnowledgeUnit {
pub fn propose(
proposer_did: impl Into<String>,
kind: UnitKind,
domain: impl IntoIterator<Item = impl Into<String>>,
insight: Insight,
now: Timestamp,
) -> Self {
Self::propose_with_policy(
proposer_did,
kind,
domain,
insight,
now,
&StalenessPolicy::default(),
)
}
pub fn propose_with_policy(
proposer_did: impl Into<String>,
kind: UnitKind,
domain: impl IntoIterator<Item = impl Into<String>>,
insight: Insight,
now: Timestamp,
policy: &StalenessPolicy,
) -> Self {
let proposer_did = proposer_did.into();
let mut domain: Vec<String> = domain.into_iter().map(Into::into).collect();
domain.sort();
domain.dedup();
let id = UnitId::mint(
&proposer_did,
&domain,
&insight.summary,
&insight.detail,
&insight.action,
);
Self {
id,
version: SCHEMA_VERSION.to_string(),
domain,
insight,
context: UnitContext::default(),
evidence: Evidence {
severity: Severity::default(),
confidence: 0.0,
confirmations: 0,
contributing_orgs: 0,
first_observed: now,
last_confirmed: now,
last_queried_at: None,
},
provenance: Provenance {
proposer_did,
graduation_history: Vec::new(),
},
lifecycle: Lifecycle {
status: UnitStatus::Draft,
kind,
staleness_policy: policy.token_for(kind),
superseded_by: None,
related: Vec::new(),
},
}
}
pub fn with_context(mut self, context: UnitContext) -> Self {
self.context = context;
self
}
pub fn with_severity(mut self, severity: Severity) -> Self {
self.evidence.severity = severity;
self
}
pub fn tier(&self) -> Tier {
self.provenance
.graduation_history
.last()
.map_or(Tier::Local, |g| g.to)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn now() -> Timestamp {
Timestamp::parse_rfc3339("2026-01-01T00:00:00Z").unwrap()
}
fn sample() -> KnowledgeUnit {
KnowledgeUnit::propose(
"did:nostr:abc",
UnitKind::Workaround,
["payments", "api", "payments"],
Insight::new(" summary ", "detail", "action"),
now(),
)
}
#[test]
fn proposing_does_not_confirm() {
let u = sample();
assert_eq!(u.lifecycle.status, UnitStatus::Draft);
assert_eq!(u.evidence.confirmations, 0);
assert_eq!(u.evidence.contributing_orgs, 0);
assert_eq!(u.evidence.confidence, 0.0);
}
#[test]
fn domain_is_normalised_and_insight_trimmed() {
let u = sample();
assert_eq!(u.domain, vec!["api", "payments"]);
assert_eq!(u.insight.summary, "summary");
}
#[test]
fn a_fresh_unit_is_local() {
assert_eq!(sample().tier(), Tier::Local);
}
#[test]
fn tier_wire_tokens_are_cqs() {
assert_eq!(serde_json::to_string(&Tier::Local).unwrap(), "\"local\"");
assert_eq!(serde_json::to_string(&Tier::Shared).unwrap(), "\"remote\"");
assert_eq!(serde_json::to_string(&Tier::Public).unwrap(), "\"global\"");
assert_eq!(
serde_json::from_str::<Tier>("\"global\"").unwrap(),
Tier::Public
);
}
#[test]
fn disputed_and_stale_units_are_still_served() {
assert!(UnitStatus::Disputed.is_servable());
assert!(UnitStatus::Stale.is_servable());
assert!(!UnitStatus::Retired.is_servable());
assert!(!UnitStatus::Superseded.is_servable());
}
#[test]
fn the_authorising_event_is_omitted_when_absent() {
let g = Graduation {
from: Tier::Local,
to: Tier::Shared,
approved_by: "human:alice@acme.dev".into(),
timestamp: now(),
authorising_event: None,
};
let j = serde_json::to_string(&g).unwrap();
assert!(!j.contains("authorising_event"), "must stay cq-shaped: {j}");
}
#[test]
fn round_trips_through_json() {
let u = sample();
let j = serde_json::to_string(&u).unwrap();
assert_eq!(serde_json::from_str::<KnowledgeUnit>(&j).unwrap(), u);
}
}