Skip to main content

qualia_core_db/poet_host/invoke/
cooperative.rs

1//! Host bindings for `qualia-cooperative-core` and the 6 Core Semantic Instruments (`WP-CP-02B`).
2//!
3//! Exposes:
4//! - `CooperativeDelegation.permits` ([`permits`])
5//! - `CooperativeWork.board_project` ([`board_project`])
6//! - `CooperativeLifecycle.evaluate` ([`evaluate_lifecycle`])
7//! - `CooperativeAssertions.review` ([`review_assertion`])
8//! - `CooperativeInstruments.evaluate` ([`evaluate_instrument_readiness`])
9//! - `CooperativePool.clear_bps` ([`clear_pool_bps`])
10
11mod codec;
12mod permits;
13mod work;
14
15pub use permits::permits;
16pub use work::board_project;
17
18use vibe::{Span, Value};
19
20use super::args;
21use crate::modalities::socioeconomics::clear_pool_obligations_bps;
22use crate::semantic_instruments::{
23    evaluate_contextual_assertions, evaluate_contribution_lifecycle,
24    evaluate_core_semantic_instrument, execute_reference_instrument, ContextualAssertionsReview,
25    ContributionLifecycleCompleteness, CoreInstrumentKind, CoreInstrumentPayload,
26    InstrumentEvaluationReport,
27};
28use codec::{decode_field, encode_json, vibe_to_json};
29
30fn encode_report(
31    report: &InstrumentEvaluationReport,
32    span: Span,
33    what: &str,
34) -> Result<Value, vibe::Diagnostic> {
35    let findings_v = encode_json(&report.findings, span, what)?;
36    Ok(args::record([
37        ("instrument", Value::String(report.instrument.slug().into())),
38        ("outcome", Value::String(report.outcome.as_str().into())),
39        ("satisfied", Value::Bool(report.outcome.is_satisfied())),
40        ("findings", findings_v),
41        ("receipt_subject", Value::U64(report.receipt_quin.subject)),
42        (
43            "receipt_parity_ok",
44            Value::Bool(report.receipt_quin.verify_ecc_parity()),
45        ),
46    ]))
47}
48
49/// `CooperativeLifecycle.evaluate` — evaluate 9-stage contribution lifecycle completeness
50/// (`Activity != Payable Debt` and `Recognition != Settlement`).
51pub fn evaluate_lifecycle(args_v: &Value, span: Span) -> Result<Value, vibe::Diagnostic> {
52    let input: ContributionLifecycleCompleteness = match args::rec(args_v, "lifecycle") {
53        Some(_) => decode_field(args_v, "lifecycle", span, "CooperativeLifecycle.evaluate")?,
54        None => {
55            let json = vibe_to_json(args_v).ok_or_else(|| {
56                args::bad(span, "CooperativeLifecycle.evaluate: invalid argument record")
57            })?;
58            serde_json::from_value(json).map_err(|e| {
59                args::bad(span, format!("CooperativeLifecycle.evaluate: decode failed ({e})"))
60            })?
61        }
62    };
63    let now_unix = args::rec_u64(args_v, "now_unix").unwrap_or(0) as u32;
64    let report = evaluate_contribution_lifecycle(&input, now_unix);
65    encode_report(&report, span, "CooperativeLifecycle.evaluate")
66}
67
68/// `CooperativeAssertions.review` — evaluate contextual assertions review
69/// (`Observation`, `Inference`, `Allegation`, `Attestation`, `AdjudicatedFinding`).
70pub fn review_assertion(args_v: &Value, span: Span) -> Result<Value, vibe::Diagnostic> {
71    let input: ContextualAssertionsReview = match args::rec(args_v, "assertion") {
72        Some(_) => decode_field(args_v, "assertion", span, "CooperativeAssertions.review")?,
73        None => {
74            let json = vibe_to_json(args_v).ok_or_else(|| {
75                args::bad(span, "CooperativeAssertions.review: invalid argument record")
76            })?;
77            serde_json::from_value(json).map_err(|e| {
78                args::bad(span, format!("CooperativeAssertions.review: decode failed ({e})"))
79            })?
80        }
81    };
82    let now_unix = args::rec_u64(args_v, "now_unix").unwrap_or(0) as u32;
83    let report = evaluate_contextual_assertions(&input, now_unix);
84    encode_report(&report, span, "CooperativeAssertions.review")
85}
86
87/// `CooperativeInstruments.evaluate` — evaluate any of the 6 Core Semantic Instruments
88/// by `instrument` slug/IRI + `input` record, or via tagged [`CoreInstrumentPayload`].
89pub fn evaluate_instrument_readiness(args_v: &Value, span: Span) -> Result<Value, vibe::Diagnostic> {
90    let now_unix = args::rec_u64(args_v, "now_unix").unwrap_or(0) as u32;
91    if let Some(slug) = args::rec_str(args_v, "instrument") {
92        if let Some(input_v) = args::rec(args_v, "input") {
93            let kind = CoreInstrumentKind::from_slug_or_id(slug).ok_or_else(|| {
94                args::bad(
95                    span,
96                    format!("CooperativeInstruments.evaluate: unknown instrument `{slug}`"),
97                )
98            })?;
99            let json = vibe_to_json(input_v).ok_or_else(|| {
100                args::bad(span, "CooperativeInstruments.evaluate: invalid `input` value")
101            })?;
102            let bytes = serde_json::to_vec(&json).map_err(|e| {
103                args::bad(span, format!("CooperativeInstruments.evaluate: {e}"))
104            })?;
105            let report = execute_reference_instrument(kind, &bytes, now_unix)
106                .map_err(|e| args::bad(span, format!("CooperativeInstruments.evaluate: {e}")))?;
107            return encode_report(&report, span, "CooperativeInstruments.evaluate");
108        }
109    }
110    let payload: CoreInstrumentPayload = match args::rec(args_v, "payload") {
111        Some(_) => decode_field(args_v, "payload", span, "CooperativeInstruments.evaluate")?,
112        None => {
113            let json = vibe_to_json(args_v).ok_or_else(|| {
114                args::bad(span, "CooperativeInstruments.evaluate: invalid payload record")
115            })?;
116            serde_json::from_value(json).map_err(|e| {
117                args::bad(
118                    span,
119                    format!("CooperativeInstruments.evaluate: decode failed ({e})"),
120                )
121            })?
122        }
123    };
124    let report = evaluate_core_semantic_instrument(&payload, now_unix);
125    encode_report(&report, span, "CooperativeInstruments.evaluate")
126}
127
128/// `CooperativePool.clear_bps` — zero-heap basis-point clearing verifying `Pool Funded != Contributor Paid`.
129pub fn clear_pool_bps(args_v: &Value, span: Span) -> Result<Value, vibe::Diagnostic> {
130    let gross = args::rec_i64(args_v, "gross_receipt_cents").unwrap_or(0);
131    let reserve_bps = args::rec_u64(args_v, "operating_reserve_bps").unwrap_or(0) as u32;
132    let fee_bps = args::rec_u64(args_v, "fiduciary_fee_bps").unwrap_or(0) as u32;
133    let prior_pool = args::rec_i64(args_v, "prior_pool_funded_cents").unwrap_or(0);
134    let target = args::rec_i64(args_v, "target_obligation_cents").unwrap_or(0);
135    let settled = args::rec_i64(args_v, "settled_verified_cents").unwrap_or(0);
136    let waived = args::rec_i64(args_v, "waived_obligation_cents").unwrap_or(0);
137    let res = clear_pool_obligations_bps(
138        gross,
139        reserve_bps,
140        fee_bps,
141        prior_pool,
142        target,
143        settled,
144        waived,
145    )
146    .ok_or_else(|| args::bad(span, "CooperativePool.clear_bps: invalid negative or >10000 bps inputs"))?;
147    Ok(args::record([
148        ("gross_receipt_cents", Value::I64(res.gross_receipt_cents)),
149        ("operating_reserve_cents", Value::I64(res.operating_reserve_cents)),
150        ("fiduciary_fee_cents", Value::I64(res.fiduciary_fee_cents)),
151        (
152            "obligation_pool_allocation_cents",
153            Value::I64(res.obligation_pool_allocation_cents),
154        ),
155        ("pool_funded_cents", Value::I64(res.pool_funded_cents)),
156        ("settled_verified_cents", Value::I64(res.settled_verified_cents)),
157        ("remaining_obligation_cents", Value::I64(res.remaining_obligation_cents)),
158        (
159            "contributor_obligations_discharged",
160            Value::Bool(res.contributor_obligations_discharged),
161        ),
162    ]))
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use std::collections::BTreeMap;
169
170    fn rec(pairs: &[(&str, Value)]) -> Value {
171        let mut m = BTreeMap::new();
172        for (k, v) in pairs {
173            m.insert((*k).into(), v.clone());
174        }
175        Value::Record(m)
176    }
177
178    #[test]
179    fn host_evaluates_lifecycle_and_assertion_and_instrument() {
180        let span = Span { start: 0, end: 0 };
181        let lc_args = rec(&[
182            ("is_commissioned", Value::Bool(false)),
183            ("is_accepted", Value::Bool(false)),
184            ("has_valuation", Value::Bool(false)),
185            ("obligation_cents", Value::I64(10_000)),
186            ("settled_verified_cents", Value::I64(0)),
187            ("is_recognition_badge_only", Value::Bool(true)),
188        ]);
189        let lc_out = evaluate_lifecycle(&lc_args, span).unwrap();
190        let Value::Record(m) = lc_out else { panic!("expected record") };
191        assert_eq!(m.get("outcome"), Some(&Value::String("failed".into())));
192
193        let assert_args = rec(&[
194            ("assertion_kind", Value::String("allegation".into())),
195            ("claimed_target_kind", Value::String("adjudicated_finding".into())),
196            ("distinct_root_sources", Value::U64(1)),
197            ("dependent_inference_count", Value::U64(2)),
198            ("has_human_adjudicator_did", Value::Bool(false)),
199            ("scope_domain", Value::String("project:alpha".into())),
200        ]);
201        let assert_out = review_assertion(&assert_args, span).unwrap();
202        let Value::Record(am) = assert_out else { panic!("expected record") };
203        assert_eq!(am.get("outcome"), Some(&Value::String("failed".into())));
204
205        let ready_args = rec(&[
206            (
207                "instrument",
208                Value::String("licence-transition-readiness".into()),
209            ),
210            (
211                "input",
212                rec(&[
213                    ("project_id", Value::String("proj:1".into())),
214                    ("pool_funded_cents", Value::I64(100_000)),
215                    ("required_obligation_cents", Value::I64(100_000)),
216                    ("settled_verified_cents", Value::I64(40_000)),
217                    ("dependencies_compatible", Value::Bool(true)),
218                    ("unresolved_material_challenges", Value::U64(0)),
219                    (
220                        "authorised_human_steward_did",
221                        Value::String("did:webizen:person:steward".into()),
222                    ),
223                ]),
224            ),
225        ]);
226        let ready_out = evaluate_instrument_readiness(&ready_args, span).unwrap();
227        let Value::Record(rm) = ready_out else { panic!("expected record") };
228        assert_eq!(rm.get("outcome"), Some(&Value::String("held".into())));
229    }
230}