Skip to main content

qualia_cooperative_core/
projects.rs

1//! Cooperative projects (audit COP-01..19) — Restricted records for shared work,
2//! membership, contributions, and the obligations **derived** from them.
3//!
4//! Money/effort safety mirrors `finance.rs`: contributions merge **add-wins by stable
5//! entry id** and never by raw sum, and obligations are a **pure derivation over the
6//! unique-id set** keyed by `(project_id, contributor_did)`. This makes duplicate,
7//! reordered, or replayed sync frames safe — you can never double-count effort.
8//!
9//! `Contribution` records form an author chain via `predecessor_id`, so a project's
10//! effort history is a verifiable append-only sequence per contributor.
11
12use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15use crate::record::{
16    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
17};
18
19/// Role a member holds within a cooperative project.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum ProjectRole {
23    /// Coordinates the project and can admit/settle on behalf of members.
24    Steward,
25    /// Does the work and accrues effort obligations.
26    Contributor,
27    /// Read-only participant; accrues no effort.
28    Observer,
29}
30
31impl Default for ProjectRole {
32    fn default() -> Self {
33        Self::Contributor
34    }
35}
36
37/// A cooperative project — a named unit of shared work.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Project {
40    pub id: String,
41    pub name: String,
42    pub description: String,
43    /// Semantic URIs defining the licensing constraints (e.g. human rights values, trade rules).
44    #[serde(default)]
45    pub licensing_ontologies: Vec<String>,
46    pub created_at_unix: u32,
47    /// High-resolution instant (T71 bridge). Preferred over `created_at_unix`
48    /// when present; the u32 field is kept for backward-compatible deserialization.
49    #[serde(skip_serializing_if = "Option::is_none", default)]
50    pub created_at_instant: Option<InstantBridge>,
51}
52
53impl Project {
54    /// Creates a new instance.
55    pub fn new(
56        name: impl Into<String>,
57        description: impl Into<String>,
58        licensing_ontologies: Vec<String>,
59        created_at_unix: u32,
60    ) -> Self {
61        Self {
62            id: Uuid::new_v4().to_string(),
63            name: name.into(),
64            description: description.into(),
65            licensing_ontologies,
66            created_at_unix,
67            created_at_instant: Some(InstantBridge::from_coarse(created_at_unix)),
68        }
69    }
70
71    /// Resolve the created-at instant, preferring the high-resolution
72    /// `InstantBridge` field when present (T71 bridge).
73    pub fn created_at(&self) -> InstantBridge {
74        self.created_at_instant
75            .unwrap_or_else(|| InstantBridge::from_coarse(self.created_at_unix))
76    }
77}
78
79/// Membership of a DID in a project, with an agreed role.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ProjectMembership {
82    pub id: String,
83    pub project_id: String,
84    pub member_did: String,
85    #[serde(default)]
86    pub role: ProjectRole,
87    pub agreed_at_unix: u32,
88    /// High-resolution instant (T71 bridge). Preferred over `agreed_at_unix`
89    /// when present; the u32 field is kept for backward-compatible deserialization.
90    #[serde(skip_serializing_if = "Option::is_none", default)]
91    pub agreed_at_instant: Option<InstantBridge>,
92}
93
94impl ProjectMembership {
95    /// Creates a new instance.
96    pub fn new(
97        project_id: impl Into<String>,
98        member_did: impl Into<String>,
99        role: ProjectRole,
100        agreed_at_unix: u32,
101    ) -> Self {
102        Self {
103            id: Uuid::new_v4().to_string(),
104            project_id: project_id.into(),
105            member_did: member_did.into(),
106            role,
107            agreed_at_unix,
108            agreed_at_instant: Some(InstantBridge::from_coarse(agreed_at_unix)),
109        }
110    }
111
112    /// Resolve the agreed-at instant, preferring the high-resolution
113    /// `InstantBridge` field when present (T71 bridge).
114    pub fn agreed_at(&self) -> InstantBridge {
115        self.agreed_at_instant
116            .unwrap_or_else(|| InstantBridge::from_coarse(self.agreed_at_unix))
117    }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub enum ContributionPrivacy {
122    Public,
123    Permissive,
124    Private,
125}
126
127impl Default for ContributionPrivacy {
128    fn default() -> Self {
129        Self::Public
130    }
131}
132
133/// A single immutable unit of contributed effort. Never mutated; a correction is a
134/// new entry linked via `predecessor_id`, so `id` is a stable content anchor for dedup
135/// and the entries form an append-only author chain.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct Contribution {
138    pub id: String,
139    pub project_id: String,
140    pub contributor_did: String,
141    pub description: String,
142    /// Effort in whole minutes. Non-negative by construction.
143    pub effort_minutes: u32,
144    /// Capital injected into the project in cents (e.g. $10.00 = 1000).
145    #[serde(default)]
146    pub capital_cents: u64,
147    /// ROI Multiplier to apply to the obligation ledger (e.g. 1.0, 1.5, 2.0).
148    #[serde(default = "default_roi")]
149    pub roi_multiplier: f32,
150    /// Privacy scope of this contributor's identity.
151    #[serde(default)]
152    pub privacy_level: ContributionPrivacy,
153    pub occurred_at_unix: u32,
154    /// High-resolution instant (T71 bridge). Preferred over `occurred_at_unix`
155    /// when present; the u32 field is kept for backward-compatible deserialization.
156    #[serde(skip_serializing_if = "Option::is_none", default)]
157    pub occurred_at_instant: Option<InstantBridge>,
158    /// Prior contribution in this contributor's chain, if any.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub predecessor_id: Option<String>,
161}
162
163fn default_roi() -> f32 {
164    1.0
165}
166
167impl Contribution {
168    /// Creates a new instance.
169    #[allow(clippy::too_many_arguments)]
170    pub fn new(
171        project_id: impl Into<String>,
172        contributor_did: impl Into<String>,
173        description: impl Into<String>,
174        effort_minutes: u32,
175        capital_cents: u64,
176        roi_multiplier: f32,
177        privacy_level: ContributionPrivacy,
178        occurred_at_unix: u32,
179    ) -> Self {
180        Self {
181            id: Uuid::new_v4().to_string(),
182            project_id: project_id.into(),
183            contributor_did: contributor_did.into(),
184            description: description.into(),
185            effort_minutes,
186            capital_cents,
187            roi_multiplier,
188            privacy_level,
189            occurred_at_unix,
190            occurred_at_instant: Some(InstantBridge::from_coarse(occurred_at_unix)),
191            predecessor_id: None,
192        }
193    }
194
195    /// Resolve the occurred-at instant, preferring the high-resolution
196    /// `InstantBridge` field when present (T71 bridge).
197    pub fn occurred_at(&self) -> InstantBridge {
198        self.occurred_at_instant
199            .unwrap_or_else(|| InstantBridge::from_coarse(self.occurred_at_unix))
200    }
201
202    /// Link this contribution as the successor of `predecessor`, forming the author chain.
203    pub fn following(mut self, predecessor: &Contribution) -> Self {
204        self.predecessor_id = Some(predecessor.id.clone());
205        self
206    }
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
210pub struct Obligation {
211    pub project_id: String,
212    pub contributor_did: String,
213    /// Total effort minutes across the unique contributions for this pair.
214    pub total_effort_minutes: u64,
215    /// Total capital invested.
216    #[serde(default)]
217    pub total_capital_cents: u64,
218    /// The mathematically resolved ROI obligation value.
219    #[serde(default)]
220    pub resolved_obligation_score: f64,
221    /// Number of unique contributions aggregated.
222    pub contribution_count: usize,
223}
224
225// ---------------------------------------------------------------------------
226// Record-id helpers
227// ---------------------------------------------------------------------------
228
229/// `project-record` ID.
230pub fn project_record_id(uuid: &str) -> String {
231    format!("urn:wellfair:project:{uuid}")
232}
233
234/// `project-membership-record` ID.
235pub fn project_membership_record_id(uuid: &str) -> String {
236    format!("urn:wellfair:project_membership:{uuid}")
237}
238
239/// `contribution-record` ID.
240pub fn contribution_record_id(uuid: &str) -> String {
241    format!("urn:wellfair:contribution:{uuid}")
242}
243
244// ---------------------------------------------------------------------------
245// Merge + derivation (money/effort safety — mirror finance.rs discipline)
246// ---------------------------------------------------------------------------
247
248/// Merge two contribution sets **add-wins by stable id** (never sum-merge), returning a
249/// deterministically ordered union. Idempotent and order-independent.
250pub fn merge_contributions(
251    existing: &[Contribution],
252    incoming: &[Contribution],
253) -> Vec<Contribution> {
254    let mut merged: Vec<Contribution> = Vec::with_capacity(existing.len() + incoming.len());
255    for entry in existing.iter().chain(incoming.iter()) {
256        if !merged.iter().any(|e| e.id == entry.id) {
257            merged.push(entry.clone());
258        }
259    }
260    merged.sort_by(|a, b| {
261        a.occurred_at_unix
262            .cmp(&b.occurred_at_unix)
263            .then_with(|| a.id.cmp(&b.id))
264    });
265    merged
266}
267
268/// Derive per-(project, contributor) effort obligations purely from the unique-id set.
269pub fn derive_obligations(contributions: &[Contribution]) -> Vec<Obligation> {
270    let unique = merge_contributions(contributions, &[]);
271    let mut obligations: Vec<Obligation> = Vec::new();
272    for c in &unique {
273        let score = (c.effort_minutes as f64 + c.capital_cents as f64) * c.roi_multiplier as f64;
274        match obligations
275            .iter_mut()
276            .find(|o| o.project_id == c.project_id && o.contributor_did == c.contributor_did)
277        {
278            Some(ob) => {
279                ob.total_effort_minutes += u64::from(c.effort_minutes);
280                ob.total_capital_cents += c.capital_cents;
281                ob.resolved_obligation_score += score;
282                ob.contribution_count += 1;
283            }
284            None => obligations.push(Obligation {
285                project_id: c.project_id.clone(),
286                contributor_did: c.contributor_did.clone(),
287                total_effort_minutes: u64::from(c.effort_minutes),
288                total_capital_cents: c.capital_cents,
289                resolved_obligation_score: score,
290                contribution_count: 1,
291            }),
292        }
293    }
294    obligations.sort_by(|a, b| {
295        a.project_id
296            .cmp(&b.project_id)
297            .then_with(|| a.contributor_did.cmp(&b.contributor_did))
298    });
299    obligations
300}
301
302// ---------------------------------------------------------------------------
303// Envelope builders
304// ---------------------------------------------------------------------------
305
306fn project_envelope(
307    id: &str,
308    owner_did: &str,
309    author_did: &str,
310    asserted_unix: u32,
311    valid_start_unix: u32,
312    valid_start_instant: Option<InstantBridge>,
313    predecessor_id: Option<String>,
314    blob_hash: Option<String>,
315) -> RecordEnvelope {
316    RecordEnvelope {
317        id: id.to_string(),
318        owner_did: owner_did.to_string(),
319        author_did: author_did.to_string(),
320        proxy_did: None,
321        epistemic_status: EpistemicStatus::Asserted,
322        evidence_type: EvidenceType::SelfReported,
323        sensitivity: SensitivityClass::Restricted,
324        asserted_time_unix: asserted_unix,
325        asserted_instant: None,
326        valid_time_start_unix: Some(valid_start_unix),
327        valid_time_start_instant: valid_start_instant,
328        valid_time_end_unix: None,
329        valid_time_end_instant: None,
330        predecessor_id,
331        blob_hash,
332        tombstone: false,
333    }
334}
335
336/// Builds project-envelope.
337pub fn build_project_envelope(
338    project: &Project,
339    owner_did: &str,
340    author_did: &str,
341    asserted_unix: u32,
342    blob_hash: Option<String>,
343) -> RecordEnvelope {
344    let id = project_record_id(&project.id);
345    project_envelope(&id, owner_did, author_did, asserted_unix, project.created_at_unix, project.created_at_instant, None, blob_hash)
346}
347
348/// Builds membership-envelope.
349pub fn build_membership_envelope(
350    membership: &ProjectMembership,
351    owner_did: &str,
352    author_did: &str,
353    asserted_unix: u32,
354    blob_hash: Option<String>,
355) -> RecordEnvelope {
356    let id = project_membership_record_id(&membership.id);
357    project_envelope(&id, owner_did, author_did, asserted_unix, membership.agreed_at_unix, membership.agreed_at_instant, None, blob_hash)
358}
359
360/// Builds contribution-envelope.
361pub fn build_contribution_envelope(
362    contribution: &Contribution,
363    owner_did: &str,
364    author_did: &str,
365    asserted_unix: u32,
366    blob_hash: Option<String>,
367) -> RecordEnvelope {
368    let id = contribution_record_id(&contribution.id);
369    let predecessor_id = contribution.predecessor_id.as_ref().map(|p| contribution_record_id(p));
370    project_envelope(&id, owner_did, author_did, asserted_unix, contribution.occurred_at_unix, contribution.occurred_at_instant, predecessor_id, blob_hash)
371}
372
373// ---------------------------------------------------------------------------
374// Summaries (lossless serde_json object strings, as stored on the journal row)
375// ---------------------------------------------------------------------------
376
377/// Project summary.
378pub fn project_summary(project: &Project) -> String {
379    serde_json::json!({
380        "id": project.id,
381        "name": project.name,
382        "description": project.description,
383        "licensing_ontologies": project.licensing_ontologies,
384        "created_at_unix": project.created_at_unix,
385        "created_at_instant": project.created_at_instant,
386    })
387    .to_string()
388}
389
390/// Membership summary.
391pub fn membership_summary(membership: &ProjectMembership) -> String {
392    serde_json::json!({
393        "id": membership.id,
394        "project_id": membership.project_id,
395        "member_did": membership.member_did,
396        "role": membership.role,
397        "agreed_at_unix": membership.agreed_at_unix,
398        "agreed_at_instant": membership.agreed_at_instant,
399    })
400    .to_string()
401}
402
403/// Lossless contribution summary including `capital_cents`, `roi_multiplier`,
404/// `privacy_level`, `occurred_at_instant`, and `predecessor_id`.
405pub fn contribution_summary(contribution: &Contribution) -> String {
406    serde_json::json!({
407        "id": contribution.id,
408        "project_id": contribution.project_id,
409        "contributor_did": contribution.contributor_did,
410        "description": contribution.description,
411        "effort_minutes": contribution.effort_minutes,
412        "capital_cents": contribution.capital_cents,
413        "roi_multiplier": contribution.roi_multiplier,
414        "privacy_level": contribution.privacy_level,
415        "occurred_at_unix": contribution.occurred_at_unix,
416        "occurred_at_instant": contribution.occurred_at_instant,
417        "predecessor_id": contribution.predecessor_id,
418    })
419    .to_string()
420}
421
422/// Reconstruct a `Contribution` losslessly from a stored/transmitted summary JSON.
423pub fn parse_contribution_summary(
424    id: impl Into<String>,
425    summary: &str,
426    fallback_occurred_at_unix: u32,
427) -> Option<Contribution> {
428    let v: serde_json::Value = serde_json::from_str(summary).ok()?;
429    if !v.is_object() {
430        return None;
431    }
432    let id_str = id.into();
433    let resolved_id = if id_str.is_empty() {
434        v.get("id").and_then(|x| x.as_str()).unwrap_or_default().to_string()
435    } else {
436        id_str
437    };
438    let privacy_level = v.get("privacy_level").and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default();
439    let occurred_at_unix = v.get("occurred_at_unix").and_then(|x| x.as_u64()).map(|t| t as u32).unwrap_or(fallback_occurred_at_unix);
440    let occurred_at_instant = v.get("occurred_at_instant").and_then(|x| serde_json::from_value(x.clone()).ok());
441    Some(Contribution {
442        id: resolved_id,
443        project_id: v.get("project_id").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
444        contributor_did: v.get("contributor_did").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
445        description: v.get("description").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
446        effort_minutes: v.get("effort_minutes").and_then(|x| x.as_u64()).unwrap_or(0) as u32,
447        capital_cents: v.get("capital_cents").and_then(|x| x.as_u64()).unwrap_or(0),
448        roi_multiplier: v.get("roi_multiplier").and_then(|x| x.as_f64()).map(|f| f as f32).unwrap_or(1.0),
449        privacy_level,
450        occurred_at_unix,
451        occurred_at_instant,
452        predecessor_id: v.get("predecessor_id").and_then(|x| x.as_str()).map(|s| s.to_string()),
453    })
454}
455
456#[cfg(test)]
457#[path = "projects_tests.rs"]
458mod tests;