1use std::collections::HashSet;
20
21use serde::{Deserialize, Serialize};
22
23use crate::record::{q_hash_str, NQuin, SensitivityClass};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum StatementType {
29 Observation,
30 Inference,
31 Allegation,
32 Attestation,
33 AdjudicatedFinding,
34}
35
36impl StatementType {
37 pub const fn as_str(&self) -> &'static str {
39 match self {
40 Self::Observation => "observation",
41 Self::Inference => "inference",
42 Self::Allegation => "allegation",
43 Self::Attestation => "attestation",
44 Self::AdjudicatedFinding => "adjudicated_finding",
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum AssertionStatus {
53 Active,
54 Challenged,
55 Restricted,
56 Expired,
57 Withdrawn,
58 Superseded,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum VerificationStatus {
65 Proposed,
66 Attested,
67 Verified,
68 Disputed,
69 Adjudicated,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct ContextualAssertion {
75 pub id: String,
76 pub subject_uri: String,
77 pub statement_type: StatementType,
78 pub assertion_status: AssertionStatus,
79 pub verification_status: VerificationStatus,
80 pub claim_summary: String,
81 pub author_did: String,
82 pub root_source_id: String,
85 #[serde(default)]
87 pub derived_from_assertion_ids: Vec<String>,
88 pub scope_domain: String,
89 pub sensitivity: SensitivityClass,
90 pub asserted_at_unix: u32,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub expires_at_unix: Option<u32>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub superseded_by_id: Option<String>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub adjudicated_by_human_did: Option<String>,
97}
98
99impl ContextualAssertion {
100 pub fn compile_to_quins(&self, out: &mut [NQuin]) -> usize {
102 let mut written = 0;
103 let s = q_hash_str(&self.id);
104 let ctx = q_hash_str(&self.scope_domain);
105 let meta = self.sensitivity.to_metadata_mask() | (self.asserted_at_unix as u64);
106 let triples = [
107 (
108 q_hash_str("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
109 q_hash_str(self.statement_type.as_str()),
110 ),
111 (
112 q_hash_str("https://vocab.Burst.net.au/hro#subjectUri"),
113 q_hash_str(&self.subject_uri),
114 ),
115 (
116 q_hash_str("https://vocab.Burst.net.au/hro#rootSourceId"),
117 q_hash_str(&self.root_source_id),
118 ),
119 (
120 q_hash_str("https://vocab.Burst.net.au/hro#assertionStatus"),
121 self.assertion_status as u64,
122 ),
123 (
124 q_hash_str("https://vocab.Burst.net.au/hro#verificationStatus"),
125 self.verification_status as u64,
126 ),
127 ];
128 for (p, o) in triples {
129 if written >= out.len() {
130 break;
131 }
132 out[written] = NQuin::new(s, p, o, ctx, meta);
133 written += 1;
134 }
135 written
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ChallengeRecord {
142 pub id: String,
143 pub target_assertion_id: String,
144 pub challenger_did: String,
145 pub grounds: String,
146 pub counter_evidence_ids: Vec<String>,
147 pub challenged_at_unix: u32,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct DownstreamDecisionRef {
153 pub decision_id: String,
154 pub depends_on_assertion_ids: Vec<String>,
155 pub requires_review: bool,
156 pub review_reason: Option<String>,
157}
158
159pub fn count_independent_corroborations(assertions: &[ContextualAssertion]) -> usize {
163 let mut distinct_roots: HashSet<&str> = HashSet::new();
164 for a in assertions {
165 if matches!(
166 a.assertion_status,
167 AssertionStatus::Withdrawn | AssertionStatus::Expired
168 ) {
169 continue;
170 }
171 let root = a.root_source_id.trim();
172 if !root.is_empty() {
173 distinct_roots.insert(root);
174 }
175 }
176 distinct_roots.len()
177}
178
179pub fn validate_assertion_promotion(
188 current: &ContextualAssertion,
189 target_type: StatementType,
190 target_verification: VerificationStatus,
191 human_adjudicator_did: Option<&str>,
192 corroborating: &[ContextualAssertion],
193) -> Result<ContextualAssertion, String> {
194 if target_type == StatementType::Observation
195 && current.statement_type != StatementType::Observation
196 {
197 return Err(format!(
198 "cannot promote {:?} into Observation: observations must originate directly from primary capture",
199 current.statement_type
200 ));
201 }
202
203 let independent_sources = count_independent_corroborations(corroborating);
204
205 if matches!(
206 current.statement_type,
207 StatementType::Inference | StatementType::Allegation
208 ) && target_verification == VerificationStatus::Verified
209 && independent_sources < 2
210 {
211 return Err(
212 "dependent inferences or repeated statements from a single root_source_id cannot verify an Inference or Allegation"
213 .to_string(),
214 );
215 }
216
217 if target_type == StatementType::AdjudicatedFinding
218 || target_verification == VerificationStatus::Adjudicated
219 {
220 let Some(adjudicator) = human_adjudicator_did.map(str::trim).filter(|s| !s.is_empty())
221 else {
222 return Err(
223 "promotion to AdjudicatedFinding requires an explicit human adjudicator DID; repetition never auto-promotes"
224 .to_string(),
225 );
226 };
227 let mut promoted = current.clone();
228 promoted.statement_type = target_type;
229 promoted.verification_status = target_verification;
230 promoted.adjudicated_by_human_did = Some(adjudicator.to_string());
231 if current.statement_type == StatementType::Allegation {
232 promoted.sensitivity = SensitivityClass::Restricted;
233 }
234 return Ok(promoted);
235 }
236
237 let mut updated = current.clone();
238 updated.statement_type = target_type;
239 updated.verification_status = target_verification;
240 Ok(updated)
241}
242
243pub fn apply_assertion_challenge(
250 assertions: &[ContextualAssertion],
251 challenge: ChallengeRecord,
252 downstream_decisions: &[DownstreamDecisionRef],
253) -> (
254 Vec<ContextualAssertion>,
255 ChallengeRecord,
256 Vec<DownstreamDecisionRef>,
257) {
258 let target_id = challenge.target_assertion_id.as_str();
259 let mut affected_assertion_ids: HashSet<String> = HashSet::new();
260 affected_assertion_ids.insert(target_id.to_string());
261
262 let mut updated_assertions: Vec<ContextualAssertion> = Vec::with_capacity(assertions.len());
263 for a in assertions {
264 let mut copy = a.clone();
265 if copy.id == target_id
266 || copy
267 .derived_from_assertion_ids
268 .iter()
269 .any(|dep| affected_assertion_ids.contains(dep))
270 {
271 copy.assertion_status = AssertionStatus::Challenged;
272 copy.verification_status = VerificationStatus::Disputed;
273 if copy.statement_type == StatementType::Allegation {
274 copy.sensitivity = SensitivityClass::Restricted;
275 }
276 affected_assertion_ids.insert(copy.id.clone());
277 }
278 updated_assertions.push(copy);
279 }
280
281 let updated_decisions: Vec<DownstreamDecisionRef> = downstream_decisions
282 .iter()
283 .map(|d| {
284 let mut copy = d.clone();
285 if copy
286 .depends_on_assertion_ids
287 .iter()
288 .any(|id| affected_assertion_ids.contains(id))
289 {
290 copy.requires_review = true;
291 copy.review_reason = Some(format!(
292 "upstream assertion {} challenged by {}: {}",
293 challenge.target_assertion_id, challenge.challenger_did, challenge.grounds
294 ));
295 }
296 copy
297 })
298 .collect();
299
300 (updated_assertions, challenge, updated_decisions)
301}
302
303pub fn validate_contextual_evaluation_scope(
306 scope_domain: &str,
307 collapses_person_to_universal_scalar: bool,
308) -> Result<(), String> {
309 if collapses_person_to_universal_scalar {
310 return Err(
311 "deriving a universal human reputation score or scalar person ranking is forbidden"
312 .to_string(),
313 );
314 }
315 let normalized = scope_domain.trim().to_ascii_lowercase();
316 if normalized.is_empty()
317 || normalized == "universal"
318 || normalized == "global_reputation"
319 || normalized == "social_credit"
320 {
321 return Err(format!(
322 "invalid evaluation scope '{scope_domain}': assertions must be bounded to a specific domain/context"
323 ));
324 }
325 Ok(())
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 fn sample_assertion(
333 id: &str,
334 st: StatementType,
335 root_source: &str,
336 ) -> ContextualAssertion {
337 ContextualAssertion {
338 id: id.into(),
339 subject_uri: "did:wf:contributor-1".into(),
340 statement_type: st,
341 assertion_status: AssertionStatus::Active,
342 verification_status: VerificationStatus::Proposed,
343 claim_summary: format!("claim-{id}"),
344 author_did: "did:wf:reviewer-1".into(),
345 root_source_id: root_source.into(),
346 derived_from_assertion_ids: Vec::new(),
347 scope_domain: "coop:project:solar:code-review".into(),
348 sensitivity: SensitivityClass::Restricted,
349 asserted_at_unix: 1_700_000_000,
350 expires_at_unix: None,
351 superseded_by_id: None,
352 adjudicated_by_human_did: None,
353 }
354 }
355
356 #[test]
357 fn dependent_inferences_from_one_root_source_do_not_corroborate_or_auto_promote() {
358 let base_allegation = sample_assertion("a1", StatementType::Allegation, "src-log-1");
359 let inf_1 = sample_assertion("inf-1", StatementType::Inference, "src-log-1");
360 let inf_2 = sample_assertion("inf-2", StatementType::Inference, "src-log-1");
361 let inf_3 = sample_assertion("inf-3", StatementType::Inference, "src-log-1");
362
363 let group = vec![base_allegation.clone(), inf_1, inf_2, inf_3];
364 assert_eq!(
365 count_independent_corroborations(&group),
366 1,
367 "four statements sharing root_source_id must count as 1 source, not 4"
368 );
369
370 assert!(validate_assertion_promotion(
372 &base_allegation,
373 StatementType::Allegation,
374 VerificationStatus::Verified,
375 None,
376 &group
377 )
378 .is_err());
379
380 assert!(validate_assertion_promotion(
382 &base_allegation,
383 StatementType::Observation,
384 VerificationStatus::Verified,
385 Some("did:wf:steward"),
386 &group
387 )
388 .is_err());
389
390 assert!(validate_assertion_promotion(
392 &base_allegation,
393 StatementType::AdjudicatedFinding,
394 VerificationStatus::Adjudicated,
395 None,
396 &group
397 )
398 .is_err());
399
400 let adj = validate_assertion_promotion(
402 &base_allegation,
403 StatementType::AdjudicatedFinding,
404 VerificationStatus::Adjudicated,
405 Some("did:wf:human-ombuds"),
406 &group,
407 )
408 .expect("human adjudicator promotes finding");
409 assert_eq!(adj.statement_type, StatementType::AdjudicatedFinding);
410 assert_eq!(
411 adj.adjudicated_by_human_did.as_deref(),
412 Some("did:wf:human-ombuds")
413 );
414 }
415
416 #[test]
417 fn challenging_assertion_preserves_both_and_marks_downstream_decisions_for_review() {
418 let a1 = sample_assertion("a1", StatementType::Allegation, "src-1");
419 let mut derived = sample_assertion("a2", StatementType::Inference, "src-1");
420 derived.derived_from_assertion_ids = vec!["a1".into()];
421
422 let decisions = vec![
423 DownstreamDecisionRef {
424 decision_id: "dec-payout-hold".into(),
425 depends_on_assertion_ids: vec!["a2".into()],
426 requires_review: false,
427 review_reason: None,
428 },
429 DownstreamDecisionRef {
430 decision_id: "dec-unrelated".into(),
431 depends_on_assertion_ids: vec!["other-assertion".into()],
432 requires_review: false,
433 review_reason: None,
434 },
435 ];
436
437 let challenge = ChallengeRecord {
438 id: "chal-1".into(),
439 target_assertion_id: "a1".into(),
440 challenger_did: "did:wf:contributor-1".into(),
441 grounds: "Timestamped commit log proves authorship".into(),
442 counter_evidence_ids: vec!["urn:git:commit:999".into()],
443 challenged_at_unix: 1_700_000_500,
444 };
445
446 let (updated_assertions, preserved_challenge, updated_decisions) =
447 apply_assertion_challenge(&[a1, derived], challenge, &decisions);
448
449 assert_eq!(updated_assertions.len(), 2);
450 assert_eq!(updated_assertions[0].assertion_status, AssertionStatus::Challenged);
451 assert_eq!(updated_assertions[0].verification_status, VerificationStatus::Disputed);
452 assert_eq!(updated_assertions[1].assertion_status, AssertionStatus::Challenged);
453 assert_eq!(preserved_challenge.id, "chal-1");
454 assert!(updated_decisions[0].requires_review);
455 assert!(!updated_decisions[1].requires_review);
456 }
457
458 #[test]
459 fn universal_human_reputation_score_is_rejected() {
460 assert!(validate_contextual_evaluation_scope("coop:project:1", true).is_err());
461 assert!(validate_contextual_evaluation_scope("universal", false).is_err());
462 assert!(validate_contextual_evaluation_scope("global_reputation", false).is_err());
463 assert!(validate_contextual_evaluation_scope("coop:project:1", false).is_ok());
464 }
465}