qualia_cooperative_core/provenance.rs
1//! Declared reliance & judgement provenance as a **DAG** — the evidentiary substrate that keeps a
2//! natural person's authorship and responsibility intact while making their toolchain auditable.
3//!
4//! (Timothy, 2026-07-03; see `docs/plans/adr-authority-attestation-guardianship-model.md` §8/§9/§10.)
5//! When a natural agent forms a judgement *for another person*, they must declare which other agents
6//! informed it. A `Reliance` records who/what contributed and how; because a consulted agent carries
7//! *their own* [`JudgementProvenance`] (nested via [`Reliance::sub_provenance`]), `informed_by` is not a
8//! flat list — it is a **directed acyclic graph** of contributions.
9//!
10//! Load-bearing distinctions:
11//! - **Selfhood ≠ personhood, authorship stays with the natural person.** A [`AgentType::SoftwareAgent`]
12//! is *tooling & provenance* — it never bears liability, but its use MUST be disclosed and scoped. The
13//! natural person `responsible_agent` bears authorship + responsibility.
14//! - **Dual-timed veracity.** Each contribution carries its veracity *as reasonably assessed at the time*
15//! ([`Reliance::veracity_at_time`], against the [`JudgementProvenance::epistemic_horizon`]) and *as later
16//! determined* by forensic review ([`Reliance::veracity_determined`]). The gap between the two is exactly
17//! where the malice / negligence / honest-error distinction lives (§10).
18//! - **Epistemic horizon** is a content-addressed reference (Merkle root / checkpoint hash) to the
19//! information-state available to the agent at decision time — the hindsight-resistance mechanism.
20//! - **Standing declaration.** A [`RelianceDeclaration`] lets an agent declare, up front, which tools they
21//! MAY use, so a principal can consent to the toolchain before relying on the agent. An
22//! *undeclared* software agent discovered later is a serious integrity breach — see [`has_undeclared_ai`].
23//! - **Disclosure** is two independent axes (subject vs other agents) over a proof modality; the process
24//! subject's right-to-know is the first-class default (§9).
25
26use serde::{Deserialize, Serialize};
27
28/// The kind of agent that contributed to a judgement. Weight and liability differ per kind (§8.1):
29/// a natural person bears authorship + responsibility; a software agent is tooling whose use must be
30/// disclosed and scoped but which never bears liability; an instrument has calibration/validation state;
31/// a dataset/source is provenance for input data. Modelled as an enum here (a closed, well-known set);
32/// finer agent-kind facets live in the extensible `taxonomy`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
34#[serde(rename_all = "snake_case")]
35pub enum AgentType {
36 /// Bears authorship + responsibility for the judgement.
37 #[default]
38 NaturalPerson,
39 /// AI / automated tooling. Its use MUST be disclosed and scoped; it never bears liability.
40 SoftwareAgent,
41 /// A body (company, clinic, professional network) that stands behind a contribution.
42 Organization,
43 /// A measuring/analysis device — carries calibration/validation state (§10).
44 Instrument,
45 /// A dataset or data source relied upon as input.
46 Dataset,
47}
48
49/// A reference to a contributing agent. `capacity` is a role/credential term id (e.g. a professional
50/// registration URI); `version` pins a software agent or instrument to a specific version/configuration
51/// so result variation is attributable (§10).
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct AgentRef {
54 /// Stable identifier for the agent (a DID / URI / registration id). Matched by [`has_undeclared_ai`].
55 pub id: String,
56 pub agent_type: AgentType,
57 /// A role/credential term id evidencing the capacity in which the agent acted, if any.
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub capacity: Option<String>,
60 /// Version / configuration for a software agent or instrument (result-affecting, §10).
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub version: Option<String>,
63}
64
65impl AgentRef {
66 /// A natural-person agent (bears authorship + responsibility).
67 pub fn natural_person(id: impl Into<String>) -> Self {
68 Self {
69 id: id.into(),
70 agent_type: AgentType::NaturalPerson,
71 capacity: None,
72 version: None,
73 }
74 }
75
76 /// A software agent / AI tool (must be disclosed; never bears liability).
77 pub fn software_agent(id: impl Into<String>) -> Self {
78 Self {
79 id: id.into(),
80 agent_type: AgentType::SoftwareAgent,
81 capacity: None,
82 version: None,
83 }
84 }
85
86 /// Generic constructor for any agent type.
87 pub fn new(id: impl Into<String>, agent_type: AgentType) -> Self {
88 Self {
89 id: id.into(),
90 agent_type,
91 capacity: None,
92 version: None,
93 }
94 }
95
96 /// Set the capacity/credential term id (fluent).
97 pub fn with_capacity(mut self, capacity: impl Into<String>) -> Self {
98 self.capacity = Some(capacity.into());
99 self
100 }
101
102 /// Set the version/configuration (fluent).
103 pub fn with_version(mut self, version: impl Into<String>) -> Self {
104 self.version = Some(version.into());
105 self
106 }
107}
108
109/// Veracity of a contributed input, over the extended epistemic vocabulary (§10). Used dual-timed:
110/// once for the assessment *at the time* (against the epistemic horizon) and again for the later,
111/// forensic determination. The default is [`InputVeracity::Uncertain`] — nothing is assumed accurate.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
113#[serde(rename_all = "snake_case")]
114pub enum InputVeracity {
115 /// Assessed as correct.
116 Accurate,
117 /// Not yet determined — the honest default before evidence resolves it.
118 #[default]
119 Uncertain,
120 /// Contested; conflicting characterisations held paraconsistently, not collapsed.
121 Disputed,
122 /// Shown to be false (typically on hindsight / forensic review).
123 Refuted,
124 /// Deliberately false. If undetectable at the horizon, root cause attaches to the source, not the
125 /// relying agent (§10).
126 Malicious,
127}
128
129/// One contribution to a judgement — an edge in the provenance DAG. Records the contributing agent, the
130/// **nature** of reliance (`"diagnostic-support"`, `"drafting"`, `"data-source"`, `"consult"`, …), whether
131/// the agent/tool was used **within its validated/insured scope**, dual-timed veracity, and — when the
132/// contributor is itself an agent that formed a judgement — that contributor's own nested provenance
133/// (`sub_provenance`), which is what makes `informed_by` a DAG rather than a flat list.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135pub struct Reliance {
136 pub agent: AgentRef,
137 /// How the agent was relied upon (diagnostic-support | drafting | data-source | consult | …).
138 pub nature: String,
139 /// Was the tool/agent used inside its validated/insured competence? Use outside declared scope for a
140 /// consequential judgement is a red flag (§8.3).
141 pub within_validated_scope: bool,
142 /// Veracity as reasonably assessed *at the time* of reliance (against the epistemic horizon).
143 #[serde(default)]
144 pub veracity_at_time: InputVeracity,
145 /// Veracity as *later determined* by forensic/hindsight review, if a re-assessment has occurred.
146 /// `None` until reviewed. The gap vs `veracity_at_time` distinguishes malice/negligence from honest error.
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub veracity_determined: Option<InputVeracity>,
149 /// The consulted agent's *own* provenance (their toolchain), nested under this edge → the DAG.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub sub_provenance: Option<Box<JudgementProvenance>>,
152}
153
154impl Reliance {
155 /// A new reliance edge. Veracity defaults to `Uncertain`; there is no later determination yet.
156 pub fn new(agent: AgentRef, nature: impl Into<String>, within_validated_scope: bool) -> Self {
157 Self {
158 agent,
159 nature: nature.into(),
160 within_validated_scope,
161 veracity_at_time: InputVeracity::default(),
162 veracity_determined: None,
163 sub_provenance: None,
164 }
165 }
166
167 /// Set the veracity assessed at the time of reliance (fluent).
168 pub fn assessed_at_time(mut self, veracity: InputVeracity) -> Self {
169 self.veracity_at_time = veracity;
170 self
171 }
172
173 /// Record a later, forensic determination of veracity (fluent).
174 pub fn later_determined(mut self, veracity: InputVeracity) -> Self {
175 self.veracity_determined = Some(veracity);
176 self
177 }
178
179 /// Nest the contributor's own judgement provenance under this edge (fluent) — extends the DAG.
180 pub fn with_sub_provenance(mut self, jp: JudgementProvenance) -> Self {
181 self.sub_provenance = Some(Box::new(jp));
182 self
183 }
184}
185
186/// The provenance of a single judgement: the natural (or other) agent responsible for it, the ordered
187/// set of contributions that informed it, an optional epistemic horizon, and free-form procedure notes.
188/// Because each [`Reliance`] may carry a nested `sub_provenance`, this type is recursively a DAG node.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190pub struct JudgementProvenance {
191 /// The agent who bears authorship + responsibility for the judgement (`prov:wasAssociatedWith`).
192 pub responsible_agent: AgentRef,
193 /// The contributions that informed the judgement (`prov:used` / `prov:wasInformedBy`).
194 #[serde(default)]
195 pub informed_by: Vec<Reliance>,
196 /// Content-addressed reference (Merkle root / checkpoint hash) to the information-state available at
197 /// decision time — the hindsight-resistance mechanism (§9). `None` until captured.
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub epistemic_horizon: Option<String>,
200 /// Free-form notes on the procedure/method followed.
201 #[serde(default)]
202 pub procedure_notes: String,
203}
204
205impl JudgementProvenance {
206 /// A judgement attributed to `responsible_agent`, with no contributions declared yet.
207 pub fn new(responsible_agent: AgentRef) -> Self {
208 Self {
209 responsible_agent,
210 informed_by: Vec::new(),
211 epistemic_horizon: None,
212 procedure_notes: String::new(),
213 }
214 }
215
216 /// Declare one contribution that informed the judgement (fluent, chainable).
217 pub fn informed_by(mut self, reliance: Reliance) -> Self {
218 self.informed_by.push(reliance);
219 self
220 }
221
222 /// Pin the epistemic horizon (content-addressed info-state hash) at decision time (fluent).
223 pub fn with_horizon(mut self, hash: impl Into<String>) -> Self {
224 self.epistemic_horizon = Some(hash.into());
225 self
226 }
227
228 /// Set the procedure notes (fluent).
229 pub fn with_procedure_notes(mut self, notes: impl Into<String>) -> Self {
230 self.procedure_notes = notes.into();
231 self
232 }
233}
234
235/// A **standing** declaration (capacity-level) of the agents/tools an agent MAY use, so a principal can
236/// evaluate and consent to the toolchain *before* relying on the agent (§8.2). This is not the per-judgement
237/// record; it is the up-front permission surface against which [`has_undeclared_ai`] checks actual reliance.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239pub struct RelianceDeclaration {
240 /// The agent making the declaration (typically a natural person in a professional capacity).
241 pub declaring_agent: AgentRef,
242 /// The role/capacity term id this declaration is scoped to, if any.
243 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub capacity: Option<String>,
245 /// The agents/tools the declaring agent is permitted to rely upon (matched by `AgentRef.id`).
246 #[serde(default)]
247 pub permitted: Vec<AgentRef>,
248 /// When the declaration takes effect (unix seconds). `u32` is intentional (a coarse effective-date,
249 /// not a high-precision timestamp).
250 pub effective_from_unix: u32,
251}
252
253impl RelianceDeclaration {
254 /// A new declaration effective from `effective_from_unix`, permitting nothing until tools are added.
255 pub fn new(declaring_agent: AgentRef, effective_from_unix: u32) -> Self {
256 Self {
257 declaring_agent,
258 capacity: None,
259 permitted: Vec::new(),
260 effective_from_unix,
261 }
262 }
263
264 /// Scope the declaration to a capacity/credential term id (fluent).
265 pub fn with_capacity(mut self, capacity: impl Into<String>) -> Self {
266 self.capacity = Some(capacity.into());
267 self
268 }
269
270 /// Permit reliance on an agent/tool (fluent, chainable).
271 pub fn permit(mut self, agent: AgentRef) -> Self {
272 self.permitted.push(agent);
273 self
274 }
275
276 /// True if an agent id is covered by this declaration's permitted set.
277 pub fn permits_id(&self, id: &str) -> bool {
278 self.permitted.iter().any(|a| a.id == id)
279 }
280}
281
282/// The proof modality by which a provenance node (or the DAG) is disclosed (§9).
283#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
284#[serde(rename_all = "snake_case")]
285pub enum DisclosureModality {
286 /// Full reveal of the provenance.
287 #[default]
288 Full,
289 /// Reveal a subset of the DAG's fields/nodes (selective field disclosure).
290 SelectiveField,
291 /// Prove a property of the provenance *without* revealing the underlying identities/tools — e.g.
292 /// "≥2 licensed physicians", "tool within validated scope", "no undeclared AI".
293 ///
294 /// Where a real zero-knowledge circuit exists for the predicate, this is genuine ZK: real Groth16 over
295 /// BLS12-381 lives in `crypto/zk_proofs.rs` (a separate crate). Where **no** circuit exists for the
296 /// predicate yet, this modality falls back to a **signed commitment + selective field disclosure** and
297 /// MUST be labelled as such — it is NOT to be called ZK until a circuit backs it.
298 PropertyProof,
299}
300
301/// Per-node disclosure policy over two independent axes (§9): what the **process subject** (the natural
302/// person the decision is about) may see, versus what **other agents / institutions** may see. The
303/// subject's right-to-know is the first-class default; others get proportionate disclosure.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
305pub struct DisclosurePolicy {
306 /// What the process subject may see. Defaults to [`DisclosureModality::Full`].
307 pub subject: DisclosureModality,
308 /// What other agents/institutions may see. Defaults to [`DisclosureModality::SelectiveField`].
309 pub other_agents: DisclosureModality,
310}
311
312impl Default for DisclosurePolicy {
313 fn default() -> Self {
314 // The subject's right-to-know is first-class; others get proportionate/selective disclosure.
315 Self {
316 subject: DisclosureModality::Full,
317 other_agents: DisclosureModality::SelectiveField,
318 }
319 }
320}
321
322/// The integrity-breach detector (§8.3): returns `true` if any [`AgentType::SoftwareAgent`] appearing in
323/// `jp.informed_by` (recursively, through nested `sub_provenance`) is **not** covered by `declaration`'s
324/// permitted set (matched by `AgentRef.id`). An undeclared AI reliance discovered after the fact is a
325/// serious integrity breach — the omission is itself evidence.
326///
327/// Only software agents are checked; other agent types are not subject to the standing-declaration gate.
328pub fn has_undeclared_ai(jp: &JudgementProvenance, declaration: &RelianceDeclaration) -> bool {
329 for reliance in &jp.informed_by {
330 if reliance.agent.agent_type == AgentType::SoftwareAgent
331 && !declaration.permits_id(&reliance.agent.id)
332 {
333 return true;
334 }
335 if let Some(sub) = &reliance.sub_provenance {
336 if has_undeclared_ai(sub, declaration) {
337 return true;
338 }
339 }
340 }
341 false
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 /// Build a 2-level DAG: agent A's judgement is informed by B (a consult), and B's contribution
349 /// carries B's *own* provenance, which is in turn informed by a software agent tool.
350 fn two_level_dag(tool: AgentRef) -> JudgementProvenance {
351 // Level 2: agent B's own provenance, using an AI tool for drafting.
352 let b_provenance = JudgementProvenance::new(AgentRef::natural_person("did:example:b"))
353 .with_horizon("merkle:b-info-state")
354 .with_procedure_notes("B drafted using the tool, within scope.")
355 .informed_by(
356 Reliance::new(tool, "drafting", true).assessed_at_time(InputVeracity::Accurate),
357 );
358
359 // Level 1: agent A's judgement, informed by a consult with B (B's provenance nested).
360 JudgementProvenance::new(AgentRef::natural_person("did:example:a"))
361 .with_horizon("merkle:a-info-state")
362 .with_procedure_notes("A consulted B before forming the judgement.")
363 .informed_by(
364 Reliance::new(
365 AgentRef::natural_person("did:example:b").with_capacity("urn:cap:psychologist"),
366 "consult",
367 true,
368 )
369 .with_sub_provenance(b_provenance),
370 )
371 }
372
373 #[test]
374 fn builds_two_level_dag() {
375 let jp = two_level_dag(AgentRef::software_agent("did:tool:llm-x"));
376 assert_eq!(jp.responsible_agent.id, "did:example:a");
377 assert_eq!(jp.informed_by.len(), 1);
378
379 // A is informed by B (a consult).
380 let consult = &jp.informed_by[0];
381 assert_eq!(consult.nature, "consult");
382 assert_eq!(consult.agent.id, "did:example:b");
383
384 // B carries its own nested provenance (the DAG's second level).
385 let b_prov = consult
386 .sub_provenance
387 .as_ref()
388 .expect("B's sub-provenance should be present");
389 assert_eq!(b_prov.responsible_agent.id, "did:example:b");
390 assert_eq!(b_prov.informed_by.len(), 1);
391 assert_eq!(
392 b_prov.informed_by[0].agent.agent_type,
393 AgentType::SoftwareAgent
394 );
395 assert_eq!(
396 b_prov.epistemic_horizon.as_deref(),
397 Some("merkle:b-info-state")
398 );
399 }
400
401 #[test]
402 fn default_disclosure_gives_subject_full_others_selective() {
403 let policy = DisclosurePolicy::default();
404 assert_eq!(policy.subject, DisclosureModality::Full);
405 assert_eq!(policy.other_agents, DisclosureModality::SelectiveField);
406 }
407
408 #[test]
409 fn input_veracity_defaults_to_uncertain() {
410 assert_eq!(InputVeracity::default(), InputVeracity::Uncertain);
411 // A fresh reliance inherits the uncertain default and has no later determination yet.
412 let r = Reliance::new(AgentRef::natural_person("did:x"), "data-source", true);
413 assert_eq!(r.veracity_at_time, InputVeracity::Uncertain);
414 assert_eq!(r.veracity_determined, None);
415 }
416
417 #[test]
418 fn agent_type_default_is_natural_person() {
419 assert_eq!(AgentType::default(), AgentType::NaturalPerson);
420 // A generically-constructed reference to a person bears authorship.
421 assert_eq!(
422 AgentRef::natural_person("did:p").agent_type,
423 AgentType::NaturalPerson
424 );
425 }
426
427 #[test]
428 fn detects_undeclared_ai_deep_in_the_dag() {
429 // The AI tool used two levels down is NOT covered by the declaration → integrity breach.
430 let jp = two_level_dag(AgentRef::software_agent("did:tool:secret-llm"));
431 let declaration =
432 RelianceDeclaration::new(AgentRef::natural_person("did:example:a"), 1_700_000_000)
433 .with_capacity("urn:cap:psychologist")
434 .permit(AgentRef::software_agent("did:tool:approved-llm"));
435
436 assert!(
437 has_undeclared_ai(&jp, &declaration),
438 "an undeclared AI nested in the DAG must be detected"
439 );
440 }
441
442 #[test]
443 fn returns_false_when_ai_is_declared() {
444 // Same DAG, but now the tool used deep in the DAG IS permitted → no breach.
445 let jp = two_level_dag(AgentRef::software_agent("did:tool:llm-x"));
446 let declaration =
447 RelianceDeclaration::new(AgentRef::natural_person("did:example:a"), 1_700_000_000)
448 .permit(AgentRef::software_agent("did:tool:llm-x"));
449
450 assert!(
451 !has_undeclared_ai(&jp, &declaration),
452 "a declared AI must not be flagged as undeclared"
453 );
454 assert!(declaration.permits_id("did:tool:llm-x"));
455 }
456
457 #[test]
458 fn non_software_agents_are_not_gated_by_declaration() {
459 // A dataset/instrument contribution is not a SoftwareAgent, so an empty declaration is fine.
460 let jp = JudgementProvenance::new(AgentRef::natural_person("did:example:a"))
461 .informed_by(Reliance::new(
462 AgentRef::new("did:dataset:registry", AgentType::Dataset),
463 "data-source",
464 true,
465 ))
466 .informed_by(Reliance::new(
467 AgentRef::new("did:instr:analyzer", AgentType::Instrument).with_version("v2.1"),
468 "measurement",
469 true,
470 ));
471 let declaration =
472 RelianceDeclaration::new(AgentRef::natural_person("did:example:a"), 1_700_000_000);
473 assert!(!has_undeclared_ai(&jp, &declaration));
474 }
475
476 #[test]
477 fn dual_timed_veracity_round_trips_through_serde() {
478 // A reliance judged accurate at the time but later refuted (the malice/negligence-detecting gap).
479 let reliance = Reliance::new(
480 AgentRef::software_agent("did:tool:llm-x").with_version("2026.01"),
481 "diagnostic-support",
482 true,
483 )
484 .assessed_at_time(InputVeracity::Accurate)
485 .later_determined(InputVeracity::Refuted);
486
487 let json = serde_json::to_string(&reliance).expect("serialize");
488 // snake_case serde on the enum.
489 assert!(json.contains("\"veracity_at_time\":\"accurate\""));
490 assert!(json.contains("\"veracity_determined\":\"refuted\""));
491
492 let back: Reliance = serde_json::from_str(&json).expect("deserialize");
493 assert_eq!(back, reliance);
494 assert_eq!(back.veracity_at_time, InputVeracity::Accurate);
495 assert_eq!(back.veracity_determined, Some(InputVeracity::Refuted));
496 }
497
498 #[test]
499 fn whole_provenance_round_trips_through_serde() {
500 let jp = two_level_dag(AgentRef::software_agent("did:tool:llm-x"));
501 let json = serde_json::to_string(&jp).expect("serialize");
502 let back: JudgementProvenance = serde_json::from_str(&json).expect("deserialize");
503 assert_eq!(back, jp);
504 }
505
506 #[test]
507 fn out_of_scope_reliance_is_recorded() {
508 // Using a tool outside its validated scope is a red flag the record must preserve faithfully.
509 let r = Reliance::new(
510 AgentRef::software_agent("did:tool:llm-x"),
511 "diagnostic-support",
512 false,
513 );
514 assert!(!r.within_validated_scope);
515 }
516
517 #[test]
518 fn property_proof_modality_is_available() {
519 // The disclosure modality enum offers the property-proof option (labelled honestly in docs).
520 let policy = DisclosurePolicy {
521 subject: DisclosureModality::Full,
522 other_agents: DisclosureModality::PropertyProof,
523 };
524 assert_eq!(policy.other_agents, DisclosureModality::PropertyProof);
525 }
526}