Skip to main content

qualia_core_db/services/
poet_record_api.rs

1//! Bounded persistent COP/project record store for standalone POET surfaces.
2//!
3//! The loopback daemon owns a family-keyed JSON ledger under the configured
4//! storage path. Agreement, rights, and later project views share this contract
5//! instead of each inventing a transport.
6
7use std::collections::BTreeMap;
8use std::fs;
9use std::path::{Path, PathBuf};
10use std::sync::Mutex;
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use axum::{
14    body::Bytes,
15    http::StatusCode,
16    response::{IntoResponse, Response},
17    Json,
18};
19use serde::{Deserialize, Serialize};
20
21pub const RECORD_REQUEST_LIMIT_BYTES: usize = 64 * 1024;
22const MAX_RECORDS_PER_FAMILY: usize = 256;
23const MAX_TITLE_BYTES: usize = 256;
24const MAX_FIELD_KEYS: usize = 32;
25const MAX_FIELD_KEY_BYTES: usize = 64;
26const MAX_FIELD_VALUE_BYTES: usize = 1024;
27const MAX_FILE_BYTES: usize = 2 * 1024 * 1024;
28
29pub const FAMILIES: &[&str] = &[
30    "agreement",
31    "contribution",
32    "license",
33    "obligation",
34    "compensation",
35    "rights_agreement",
36    "rights_deontic",
37    "rights_jural",
38    "rights_breach",
39    "rights_consent",
40    "project",
41    "project_task",
42    "project_issue",
43    "project_wiki",
44    "project_document",
45    "project_deliverable",
46    "project_milestone",
47    "project_risk",
48    "project_budget",
49    "project_actual",
50    "project_funding",
51    "project_royalty",
52    "project_tax",
53    "project_cost",
54    "project_event",
55    "project_asset",
56    "project_discussion",
57    "project_governance",
58    "project_vote",
59    "project_award",
60    "project_bounty",
61    "project_credential",
62    "project_integration",
63    "project_connector_run",
64    "project_datasource",
65    "project_automation",
66    "project_token",
67    "project_time",
68    "project_news",
69    "project_onboarding",
70    "project_review",
71    "project_retrospective",
72    "project_ip",
73    "project_commons",
74    "project_import",
75    "project_agent",
76    "project_agent_run",
77    "project_member",
78    "project_knowledge",
79    "dataset",
80    "dataset_annotation",
81    "dataset_lineage",
82    "dataset_view",
83    "dataset_presentation",
84    "dataset_media",
85    "dataset_cad",
86    "dataset_import",
87    "ontology",
88    "ontology_shape",
89    "ontology_shex",
90    "ontology_relation",
91    "ontology_mapping",
92    "ontology_compare",
93    "ontology_binding",
94    "ontology_term",
95    "studio_scene",
96    "studio_audio",
97    "studio_animation",
98    "studio_asset",
99    "health_condition",
100    "health_medication",
101    "health_lab",
102    "health_vital",
103    "health_report",
104    "health_note",
105    "health_document",
106    "health_share",
107    "health_safeguard",
108    "health_attestation",
109    "health_activity",
110    "gov_meeting",
111    "gov_dispute",
112    "gov_complaint",
113    "gov_coi",
114    "gov_correction",
115    "device",
116    "wallet_entry",
117    "social_message",
118    "social_moderation",
119    "social_notification",
120    "social_request",
121    "social_reputation",
122    "presence",
123    "channel",
124    "finance_account",
125    "vision_job",
126    "listen_session",
127    "triad_session",
128    "portal_nav",
129    "webview_session",
130    "aura_validation",
131    "webrtc_session",
132    "settings_pref",
133    "capability_grant",
134    "policy_rule",
135    "pulse_event",
136    "poet_subject",
137    "manifold_participant",
138    "context_markup",
139    "provenance_entry",
140    "constituency",
141    "constituency_consent",
142];
143
144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
145pub struct CopRecord {
146    pub id: String,
147    pub family: String,
148    pub title: String,
149    #[serde(default)]
150    pub fields: BTreeMap<String, serde_json::Value>,
151    pub created_at: i64,
152    pub updated_at: i64,
153}
154
155#[derive(Debug, Clone, Default, Serialize, Deserialize)]
156struct RecordLedger {
157    #[serde(default)]
158    records: Vec<CopRecord>,
159}
160
161#[derive(Debug, Deserialize)]
162pub struct RecordQueryRequest {
163    pub family: String,
164    #[serde(default)]
165    pub query: String,
166    /// Optional `fields.kind` filter. Empty means every kind in the family.
167    #[serde(default)]
168    pub kind: String,
169}
170
171#[derive(Debug, Deserialize)]
172pub struct RecordUpsertRequest {
173    pub family: String,
174    pub title: String,
175    #[serde(default)]
176    pub id: Option<String>,
177    #[serde(default)]
178    pub fields: BTreeMap<String, serde_json::Value>,
179}
180
181#[derive(Debug, Deserialize)]
182pub struct RecordDeleteRequest {
183    pub family: String,
184    pub id: String,
185}
186
187struct RecordStore {
188    path: PathBuf,
189    ledger: RecordLedger,
190}
191
192static STORE: Mutex<Option<RecordStore>> = Mutex::new(None);
193
194/// Point the record store at `path`; called once at server spawn.
195/// Until configured, handlers return store-unavailable.
196pub fn configure(path: PathBuf) {
197    let ledger = load_ledger(&path);
198    *STORE.lock().expect("COP record store lock") = Some(RecordStore { path, ledger });
199}
200
201/// Best-effort COP upsert used by native invoke seams (Pulse, etc.).
202///
203/// Returns `Err` when the store is unconfigured or the record is rejected.
204/// Invoke handlers must treat this as optional persistence, not a hard fail.
205pub fn try_upsert(
206    family: &str,
207    title: &str,
208    fields: BTreeMap<String, serde_json::Value>,
209) -> Result<serde_json::Value, String> {
210    let mut guard = STORE
211        .lock()
212        .map_err(|_| "COP record store lock failed".to_string())?;
213    let store = guard
214        .as_mut()
215        .ok_or_else(|| "COP record store is not configured on this daemon".to_string())?;
216    store.upsert(RecordUpsertRequest {
217        family: family.to_string(),
218        title: title.to_string(),
219        id: None,
220        fields,
221    })
222}
223
224/// Enforce an optional persisted agent profile at the daemon boundary.
225/// Unprofiled agents remain local-inference-only; once a profile exists its
226/// owner, model, grounding scope and token ceiling become mandatory.
227pub fn authorize_agent_run(
228    agent_did: &str,
229    principal_did: &str,
230    model_path: &str,
231    library_projects: &[String],
232    uses_library_context: bool,
233    max_tokens: u32,
234) -> Result<(), String> {
235    let guard = STORE
236        .lock()
237        .map_err(|_| "COP record store lock failed".to_string())?;
238    let Some(store) = guard.as_ref() else {
239        return Ok(());
240    };
241    let mut profiles = store.ledger.records.iter().filter(|record| {
242        record.family == "project_agent"
243            && record
244                .fields
245                .get("kind")
246                .and_then(serde_json::Value::as_str)
247                == Some("profile")
248            && record
249                .fields
250                .get("agent_did")
251                .and_then(serde_json::Value::as_str)
252                == Some(agent_did)
253    });
254    let Some(profile) = profiles.next() else {
255        return Ok(());
256    };
257    if profiles.next().is_some() {
258        return Err("agent authority is ambiguous because multiple profiles use this DID".into());
259    }
260    let field = |key: &str| {
261        profile
262            .fields
263            .get(key)
264            .and_then(serde_json::Value::as_str)
265            .unwrap_or("")
266    };
267    if principal_did.is_empty() || field("owner_did") != principal_did {
268        return Err("the requesting principal does not control this agent profile".into());
269    }
270    let configured_model = field("model_path");
271    if !configured_model.is_empty() && configured_model != model_path {
272        return Err("the selected model is outside this agent profile".into());
273    }
274    let ceiling = field("max_tokens").parse::<u32>().unwrap_or(256);
275    if max_tokens > ceiling {
276        return Err(format!(
277            "the requested token budget exceeds this agent profile's {ceiling}-token ceiling"
278        ));
279    }
280    let capabilities = field("capabilities")
281        .split(',')
282        .map(str::trim)
283        .collect::<Vec<_>>();
284    if !capabilities.contains(&"local-inference") {
285        return Err("this agent profile does not permit local inference".into());
286    }
287    if uses_library_context {
288        if !capabilities.contains(&"semantic-library-read") {
289            return Err("this agent profile does not permit Semantic Library grounding".into());
290        }
291        match field("scope") {
292            "all" => {}
293            "none" => {
294                return Err("this agent profile does not permit Semantic Library grounding".into())
295            }
296            scope if scope.starts_with("project:") => {
297                let project = &scope["project:".len()..];
298                if library_projects.len() != 1 || library_projects[0] != project {
299                    return Err(format!(
300                        "this agent profile is restricted to Semantic Library project `{project}`"
301                    ));
302                }
303            }
304            _ => return Err("this agent profile has an invalid Library scope".into()),
305        }
306    }
307    Ok(())
308}
309
310/// JSON error envelope `{code, message}` with `status`.
311fn diagnostic(status: StatusCode, code: &'static str, message: impl Into<String>) -> Response {
312    (
313        status,
314        Json(serde_json::json!({
315            "ok": false,
316            "honesty": "unavailable",
317            "code": code,
318            "diagnostic": message.into()
319        })),
320    )
321        .into_response()
322}
323
324/// 200 JSON response wrapping `data`.
325fn ok(data: serde_json::Value) -> Response {
326    Json(serde_json::json!({
327        "ok": true,
328        "honesty": "live",
329        "data": data
330    }))
331    .into_response()
332}
333
334/// Deserialize the request body; 400 diagnostic on malformed JSON.
335fn decode<T: serde::de::DeserializeOwned>(body: &Bytes) -> Result<T, Response> {
336    if body.len() > RECORD_REQUEST_LIMIT_BYTES {
337        return Err(diagnostic(
338            StatusCode::PAYLOAD_TOO_LARGE,
339            "payload_too_large",
340            "COP record requests are limited to 64 KiB",
341        ));
342    }
343    serde_json::from_slice(body)
344        .map_err(|error| diagnostic(StatusCode::BAD_REQUEST, "invalid_json", error.to_string()))
345}
346
347/// Run `op` under the global store lock; maps store errors to
348/// diagnostics.
349fn with_store<T>(op: impl FnOnce(&mut RecordStore) -> Result<T, String>) -> Result<T, Response> {
350    let mut guard = STORE.lock().map_err(|_| {
351        diagnostic(
352            StatusCode::INTERNAL_SERVER_ERROR,
353            "store_lock",
354            "COP record store lock failed",
355        )
356    })?;
357    let store = guard.as_mut().ok_or_else(|| {
358        diagnostic(
359            StatusCode::SERVICE_UNAVAILABLE,
360            "store_unconfigured",
361            "COP record store is not configured on this daemon",
362        )
363    })?;
364    op(store).map_err(|error| diagnostic(StatusCode::BAD_REQUEST, "record_rejected", error))
365}
366
367/// `POST /records/query` — filter records by family/kind/fields.
368pub async fn query_handler(body: Bytes) -> Response {
369    let request: RecordQueryRequest = match decode(&body) {
370        Ok(request) => request,
371        Err(response) => return response,
372    };
373    match with_store(|store| store.query(&request)) {
374        Ok(data) => ok(data),
375        Err(response) => response,
376    }
377}
378
379/// `POST /records/upsert` — insert or replace a record after
380/// family-scoped validation.
381pub async fn upsert_handler(body: Bytes) -> Response {
382    let request: RecordUpsertRequest = match decode(&body) {
383        Ok(request) => request,
384        Err(response) => return response,
385    };
386    match with_store(|store| store.upsert(request)) {
387        Ok(data) => ok(data),
388        Err(response) => response,
389    }
390}
391
392/// `POST /records/delete` — remove a record by id.
393pub async fn delete_handler(body: Bytes) -> Response {
394    let request: RecordDeleteRequest = match decode(&body) {
395        Ok(request) => request,
396        Err(response) => return response,
397    };
398    match with_store(|store| store.delete(&request)) {
399        Ok(data) => ok(data),
400        Err(response) => response,
401    }
402}
403
404impl RecordStore {
405    /// Filter records matching the query's family/kind/field
406    /// constraints.
407    fn query(&self, request: &RecordQueryRequest) -> Result<serde_json::Value, String> {
408        let family = validate_family(&request.family)?;
409        let needle = request.query.trim().to_ascii_lowercase();
410        if needle.len() > 256 {
411            return Err("query cannot exceed 256 bytes".into());
412        }
413        let kind = request.kind.trim();
414        if kind.len() > 64 {
415            return Err("kind cannot exceed 64 bytes".into());
416        }
417        let records: Vec<&CopRecord> = self
418            .ledger
419            .records
420            .iter()
421            .filter(|record| {
422                record.family == family
423                    && (needle.is_empty()
424                        || record.title.to_ascii_lowercase().contains(&needle)
425                        || record.id.to_ascii_lowercase().contains(&needle))
426                    && (kind.is_empty()
427                        || record
428                            .fields
429                            .get("kind")
430                            .and_then(serde_json::Value::as_str)
431                            == Some(kind))
432            })
433            .collect();
434        Ok(serde_json::json!({
435            "family": family,
436            "kind": kind,
437            "count": records.len(),
438            "records": records
439        }))
440    }
441
442    /// Validate the record against its family's schema, then
443    /// insert/replace and persist the ledger.
444    fn upsert(&mut self, mut request: RecordUpsertRequest) -> Result<serde_json::Value, String> {
445        let family = validate_family(&request.family)?;
446        request.title = request.title.trim().to_string();
447        if request.title.is_empty() || request.title.len() > MAX_TITLE_BYTES {
448            return Err("title must be 1..=256 bytes".into());
449        }
450        validate_fields(&request.fields)?;
451        validate_economic_fields(family, &request.fields)?;
452        validate_connector_fields(family, &request.fields)?;
453        validate_social_fields(family, &request.fields)?;
454        validate_agent_fields(family, &request.fields)?;
455        validate_social_context(
456            family,
457            &request.fields,
458            &self.ledger.records,
459            request.id.as_deref(),
460        )?;
461        let now = unix_now();
462        if let Some(id) = request.id.as_ref().filter(|id| !id.trim().is_empty()) {
463            let record = self
464                .ledger
465                .records
466                .iter_mut()
467                .find(|record| record.family == family && record.id == *id)
468                .ok_or_else(|| format!("record `{id}` was not found"))?;
469            record.title = request.title;
470            record.fields = request.fields;
471            record.updated_at = now;
472            let snapshot = record.clone();
473            persist(&self.path, &self.ledger)?;
474            return Ok(serde_json::to_value(snapshot).unwrap_or(serde_json::Value::Null));
475        }
476        let family_count = self
477            .ledger
478            .records
479            .iter()
480            .filter(|record| record.family == family)
481            .count();
482        if family_count >= MAX_RECORDS_PER_FAMILY {
483            return Err(format!(
484                "family `{family}` already holds {MAX_RECORDS_PER_FAMILY} records"
485            ));
486        }
487        let id = format!(
488            "{family}-{:016x}",
489            crate::q_hash(&format!("{}|{}|{now}", family, request.title))
490        );
491        let record = CopRecord {
492            id,
493            family: family.to_string(),
494            title: request.title,
495            fields: request.fields,
496            created_at: now,
497            updated_at: now,
498        };
499        self.ledger.records.push(record.clone());
500        persist(&self.path, &self.ledger)?;
501        Ok(serde_json::to_value(record).unwrap_or(serde_json::Value::Null))
502    }
503
504    /// Remove the record with `request.id`; error when absent.
505    fn delete(&mut self, request: &RecordDeleteRequest) -> Result<serde_json::Value, String> {
506        let family = validate_family(&request.family)?;
507        let before = self.ledger.records.len();
508        self.ledger
509            .records
510            .retain(|record| !(record.family == family && record.id == request.id));
511        if self.ledger.records.len() == before {
512            return Err(format!("record `{}` was not found", request.id));
513        }
514        persist(&self.path, &self.ledger)?;
515        Ok(serde_json::json!({ "deleted": request.id, "family": family }))
516    }
517}
518
519/// Resolve `family` to a known family name; reject unknown
520/// families.
521fn validate_family(family: &str) -> Result<&'static str, String> {
522    FAMILIES
523        .iter()
524        .copied()
525        .find(|allowed| *allowed == family)
526        .ok_or_else(|| format!("unsupported COP record family `{family}`"))
527}
528
529/// Base field validation — size caps, depth limits, no nested
530/// record payloads.
531fn validate_fields(fields: &BTreeMap<String, serde_json::Value>) -> Result<(), String> {
532    if fields.len() > MAX_FIELD_KEYS {
533        return Err("a record may carry at most 32 fields".into());
534    }
535    for (key, value) in fields {
536        if key.is_empty() || key.len() > MAX_FIELD_KEY_BYTES {
537            return Err("field keys must be 1..=64 bytes".into());
538        }
539        match value {
540            serde_json::Value::Null | serde_json::Value::Bool(_) => {}
541            serde_json::Value::Number(number) if number.as_f64().is_some_and(f64::is_finite) => {}
542            serde_json::Value::String(text) if text.len() <= MAX_FIELD_VALUE_BYTES => {}
543            _ => {
544                return Err(format!(
545                    "field `{key}` must be a finite number, boolean, or string up to 1024 bytes"
546                ));
547            }
548        }
549    }
550    Ok(())
551}
552
553/// Economic-family validation — requires auditable units and a
554/// lifecycle state per the commons ledger contract.
555fn validate_economic_fields(
556    family: &str,
557    fields: &BTreeMap<String, serde_json::Value>,
558) -> Result<(), String> {
559    let lifecycles: &[&str] = match family {
560        "project_budget" => &["draft", "approved", "committed", "cancelled"],
561        "project_actual" => &["observed", "verified", "settled"],
562        "project_funding" => &["pledged", "received", "restricted", "returned"],
563        "project_royalty" => &["calculated", "approved", "settled"],
564        "project_tax" => &["estimated", "filed", "settled"],
565        _ => return Ok(()),
566    };
567
568    let amount = scalar_text(fields, "amount")?
569        .parse::<f64>()
570        .map_err(|_| "economic field `amount` must be a finite non-negative number".to_string())?;
571    if !amount.is_finite() || amount < 0.0 {
572        return Err("economic field `amount` must be a finite non-negative number".into());
573    }
574
575    let currency = scalar_text(fields, "currency")?;
576    if currency.len() < 3
577        || currency.len() > 12
578        || !currency
579            .bytes()
580            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
581    {
582        return Err(
583            "economic field `currency` must be a 3..=12 character currency or unit code".into(),
584        );
585    }
586
587    let lifecycle = scalar_text(fields, "lifecycle")?.to_ascii_lowercase();
588    if !lifecycles.contains(&lifecycle.as_str()) {
589        return Err(format!(
590            "economic field `lifecycle` for `{family}` must be one of {}",
591            lifecycles.join(", ")
592        ));
593    }
594
595    for required in ["effective_date", "actor", "provenance"] {
596        scalar_text(fields, required)?;
597    }
598    let sensitivity = scalar_text(fields, "sensitivity")?.to_ascii_lowercase();
599    if !matches!(sensitivity.as_str(), "public" | "restricted" | "classified") {
600        return Err(
601            "economic field `sensitivity` must be public, restricted, or classified".into(),
602        );
603    }
604    Ok(())
605}
606
607/// Extract a scalar string field; error when missing or
608/// non-scalar.
609fn scalar_text<'a>(
610    fields: &'a BTreeMap<String, serde_json::Value>,
611    key: &str,
612) -> Result<&'a str, String> {
613    fields
614        .get(key)
615        .and_then(serde_json::Value::as_str)
616        .map(str::trim)
617        .filter(|value| !value.is_empty())
618        .ok_or_else(|| format!("economic field `{key}` is required and must be a string"))
619}
620
621/// Connector-family validation — endpoint, protocol, and
622/// auth-scope requirements.
623fn validate_connector_fields(
624    family: &str,
625    fields: &BTreeMap<String, serde_json::Value>,
626) -> Result<(), String> {
627    if family == "project_connector_run" {
628        scalar_text(fields, "connector_id")?;
629        scalar_text(fields, "capability_id")?;
630        let status = scalar_text(fields, "status")?;
631        if !matches!(status, "succeeded" | "failed" | "cancelled") {
632            return Err("connector run `status` must be succeeded, failed, or cancelled".into());
633        }
634        let attempt = scalar_text(fields, "attempt")?
635            .parse::<u8>()
636            .map_err(|_| "connector run `attempt` must be 1, 2, or 3".to_string())?;
637        if !(1..=3).contains(&attempt) {
638            return Err("connector run `attempt` must be 1, 2, or 3".into());
639        }
640        scalar_text(fields, "started_at")?;
641        scalar_text(fields, "finished_at")?;
642        scalar_text(fields, "effect_class")?;
643        if let Some(raw) = fields.get("probe_args").and_then(serde_json::Value::as_str) {
644            if !serde_json::from_str::<serde_json::Value>(raw).is_ok_and(|value| value.is_object())
645            {
646                return Err("connector run `probe_args` must be a JSON object".into());
647            }
648        }
649        return Ok(());
650    }
651    if family != "project_integration" {
652        return Ok(());
653    }
654    scalar_text(fields, "connector_id")?;
655    for key in ["interface_iri", "input_class_iri", "output_class_iri"] {
656        let iri = scalar_text(fields, key)?;
657        if !iri.contains(':') || iri.bytes().any(|byte| byte.is_ascii_whitespace()) {
658            return Err(format!(
659                "connector field `{key}` must be an absolute semantic IRI"
660            ));
661        }
662    }
663    let transport = scalar_text(fields, "transport")?.to_ascii_lowercase();
664    if !matches!(
665        transport.as_str(),
666        "local-invoke" | "http" | "websocket" | "mcp" | "pulse" | "file"
667    ) {
668        return Err(
669            "connector field `transport` must be local-invoke, http, websocket, mcp, pulse, or file"
670                .into(),
671        );
672    }
673    let capability = fields
674        .get("capability_id")
675        .and_then(serde_json::Value::as_str)
676        .map(str::trim)
677        .unwrap_or_default();
678    let endpoint = fields
679        .get("endpoint")
680        .and_then(serde_json::Value::as_str)
681        .map(str::trim)
682        .unwrap_or_default();
683    if capability.is_empty() && endpoint.is_empty() {
684        return Err("connector requires either `capability_id` or `endpoint`".into());
685    }
686    if transport == "local-invoke" && capability.is_empty() {
687        return Err("a local-invoke connector requires `capability_id`".into());
688    }
689    if transport != "local-invoke" && endpoint.is_empty() {
690        return Err(format!("a {transport} connector requires `endpoint`"));
691    }
692    let auth_mode = scalar_text(fields, "auth_mode")?.to_ascii_lowercase();
693    if !matches!(
694        auth_mode.as_str(),
695        "none" | "capability" | "oauth" | "did-signature"
696    ) {
697        return Err(
698            "connector field `auth_mode` must be none, capability, oauth, or did-signature".into(),
699        );
700    }
701    let status = scalar_text(fields, "status")?.to_ascii_lowercase();
702    if !matches!(
703        status.as_str(),
704        "draft" | "configured" | "enabled" | "disabled"
705    ) {
706        return Err(
707            "connector field `status` must be draft, configured, enabled, or disabled".into(),
708        );
709    }
710    let sensitivity = scalar_text(fields, "sensitivity")?.to_ascii_lowercase();
711    if !matches!(sensitivity.as_str(), "public" | "restricted" | "classified") {
712        return Err(
713            "connector field `sensitivity` must be public, restricted, or classified".into(),
714        );
715    }
716    if status == "enabled" && transport != "local-invoke" {
717        return Err(
718            "external transports remain configured until a host adapter authenticates and probes them"
719                .into(),
720        );
721    }
722    if let Some(raw) = fields
723        .get("probe_args")
724        .and_then(serde_json::Value::as_str)
725        .map(str::trim)
726        .filter(|value| !value.is_empty())
727    {
728        let value: serde_json::Value = serde_json::from_str(raw)
729            .map_err(|_| "connector `probe_args` must be a JSON object".to_string())?;
730        if !value.is_object() {
731            return Err("connector `probe_args` must be a JSON object".into());
732        }
733    }
734    if let Some(effect) = fields
735        .get("effect_class")
736        .and_then(serde_json::Value::as_str)
737    {
738        if !matches!(
739            effect.to_ascii_lowercase().as_str(),
740            "pure" | "cold" | "unknown"
741        ) {
742            return Err("connector `effect_class` must be Pure, Cold, or unknown".into());
743        }
744    }
745    Ok(())
746}
747
748/// Social-family validation — channel membership, reply
749/// targets, and content bounds.
750fn validate_social_fields(
751    family: &str,
752    fields: &BTreeMap<String, serde_json::Value>,
753) -> Result<(), String> {
754    match family {
755        "social_message" => {
756            require_did(fields, "from")?;
757            scalar_text(fields, "body")?;
758            if let Some(thread) = fields.get("thread").and_then(serde_json::Value::as_str) {
759                if thread.trim().is_empty() || thread.len() > 128 {
760                    return Err("social field `thread` must be 1..=128 bytes".into());
761                }
762            }
763            if let Some(mentions) = fields.get("mentions").and_then(serde_json::Value::as_str) {
764                let mentions = mentions
765                    .split(',')
766                    .map(str::trim)
767                    .filter(|value| !value.is_empty())
768                    .collect::<Vec<_>>();
769                if mentions.len() > 16 {
770                    return Err("a social message may mention at most 16 DIDs".into());
771                }
772                if mentions.iter().any(|did| {
773                    !did.starts_with("did:") || did.bytes().any(|byte| byte.is_ascii_whitespace())
774                }) {
775                    return Err("social message mentions must be comma-separated DIDs".into());
776                }
777            }
778        }
779        "social_notification" => {
780            require_did(fields, "recipient")?;
781            require_did(fields, "from")?;
782            scalar_text(fields, "source_message_id")?;
783            scalar_text(fields, "thread")?;
784            let status = scalar_text(fields, "status")?;
785            if !matches!(status, "unread" | "read") {
786                return Err("social notification `status` must be unread or read".into());
787            }
788            if status == "read" {
789                let actor = require_did(fields, "acted_by")?;
790                if actor != require_did(fields, "recipient")? {
791                    return Err("only the notification recipient may mark it read".into());
792                }
793                scalar_text(fields, "acted_at")?;
794            }
795        }
796        "social_moderation" => {
797            require_did(fields, "actor_did")?;
798            scalar_text(fields, "message_id")?;
799            scalar_text(fields, "thread")?;
800            scalar_text(fields, "reason")?;
801            scalar_text(fields, "acted_at")?;
802            if scalar_text(fields, "action")? != "hide" {
803                return Err(
804                    "social moderation currently supports only non-destructive `hide`".into(),
805                );
806            }
807        }
808        "social_request" => {
809            let from = require_did(fields, "from")?;
810            let to = require_did(fields, "to")?;
811            if from == to {
812                return Err("a social request cannot target the requesting DID".into());
813            }
814            let status = scalar_text(fields, "status")?.to_ascii_lowercase();
815            if !matches!(
816                status.as_str(),
817                "pending" | "accepted" | "denied" | "blocked"
818            ) {
819                return Err(
820                    "social request `status` must be pending, accepted, denied, or blocked".into(),
821                );
822            }
823            if status != "pending" {
824                let actor = require_did(fields, "acted_by")?;
825                if actor != to {
826                    return Err(
827                        "only the receiving DID may accept, deny, or block a request".into(),
828                    );
829                }
830                scalar_text(fields, "acted_at")?;
831            }
832        }
833        "presence" => {
834            require_did(fields, "did")?;
835            let status = scalar_text(fields, "status")?.to_ascii_lowercase();
836            if !matches!(status.as_str(), "here" | "away" | "unavailable") {
837                return Err("presence `status` must be here, away, or unavailable".into());
838            }
839            scalar_text(fields, "scope")?;
840            let expires = scalar_text(fields, "expires_at")?
841                .parse::<i64>()
842                .map_err(|_| "presence `expires_at` must be a Unix timestamp".to_string())?;
843            let now = unix_now();
844            if expires <= now || expires > now + 30 * 24 * 60 * 60 {
845                return Err("presence `expires_at` must be within the next 30 days".into());
846            }
847        }
848        "channel" => {
849            let channel_id = scalar_text(fields, "channel_id")?;
850            if channel_id.len() > 128
851                || !channel_id.bytes().all(|byte| {
852                    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'/')
853                })
854            {
855                return Err(
856                    "channel `channel_id` must use 1..=128 letters, numbers, -, _, . or /".into(),
857                );
858            }
859            require_did(fields, "creator_did")?;
860            let visibility = scalar_text(fields, "visibility")?.to_ascii_lowercase();
861            if !matches!(visibility.as_str(), "public" | "private" | "restricted") {
862                return Err("channel `visibility` must be public, private, or restricted".into());
863            }
864            let membership = scalar_text(fields, "membership")?.to_ascii_lowercase();
865            if !matches!(membership.as_str(), "open" | "request" | "invite") {
866                return Err("channel `membership` must be open, request, or invite".into());
867            }
868            let topic = scalar_text(fields, "semantic_topic_iri")?;
869            if !topic.contains(':') || topic.bytes().any(|byte| byte.is_ascii_whitespace()) {
870                return Err("channel `semantic_topic_iri` must be an absolute IRI".into());
871            }
872        }
873        "manifold_participant" => {
874            let manifold = scalar_text(fields, "manifold")?;
875            if !manifold.starts_with("channel:") {
876                return Ok(());
877            }
878            require_did(fields, "participant")?;
879            let role = scalar_text(fields, "role")?.to_ascii_lowercase();
880            if !matches!(role.as_str(), "owner" | "moderator" | "member" | "guest") {
881                return Err(
882                    "channel participant `role` must be owner, moderator, member, or guest".into(),
883                );
884            }
885            let status = scalar_text(fields, "status")?.to_ascii_lowercase();
886            if !matches!(status.as_str(), "pending" | "active" | "removed") {
887                return Err(
888                    "channel participant `status` must be pending, active, or removed".into(),
889                );
890            }
891        }
892        _ => {}
893    }
894    Ok(())
895}
896
897/// Agent-family validation — DID presence, capability scope,
898/// model binding.
899fn validate_agent_fields(
900    family: &str,
901    fields: &BTreeMap<String, serde_json::Value>,
902) -> Result<(), String> {
903    if family == "project_agent_run" {
904        require_did(fields, "agent_did")?;
905        let model_path = scalar_text(fields, "model_path")?.to_ascii_lowercase();
906        if !model_path.ends_with(".gguf")
907            && !model_path.ends_with(".p64")
908            && !model_path.ends_with(".safetensors")
909        {
910            return Err(
911                "agent run `model_path` must identify a GGUF, P64, or Safetensors model".into(),
912            );
913        }
914        let status = scalar_text(fields, "status")?;
915        if !matches!(status, "completed" | "cancelled" | "failed") {
916            return Err("agent run `status` must be completed, cancelled, or failed".into());
917        }
918        let budget = scalar_text(fields, "token_budget")?
919            .parse::<u32>()
920            .map_err(|_| "agent run `token_budget` must be 1..=256".to_string())?;
921        if !(1..=256).contains(&budget) {
922            return Err("agent run `token_budget` must be 1..=256".into());
923        }
924        scalar_text(fields, "tokens_generated")?;
925        scalar_text(fields, "duration_ms")?;
926        scalar_text(fields, "finished_at")?;
927        return Ok(());
928    }
929    if family == "project_agent"
930        && fields.get("kind").and_then(serde_json::Value::as_str) == Some("profile")
931    {
932        require_did(fields, "agent_did")?;
933        require_did(fields, "owner_did")?;
934        scalar_text(fields, "purpose")?;
935        let model_path = scalar_text(fields, "model_path")?.to_ascii_lowercase();
936        if !model_path.ends_with(".gguf")
937            && !model_path.ends_with(".p64")
938            && !model_path.ends_with(".safetensors")
939        {
940            return Err(
941                "agent profile `model_path` must identify a GGUF, P64, or Safetensors model".into(),
942            );
943        }
944        let scope = scalar_text(fields, "scope")?;
945        if !matches!(scope, "none" | "all") && !scope.starts_with("project:") {
946            return Err("agent profile `scope` must be none, all, or project:<tag>".into());
947        }
948        let capabilities = scalar_text(fields, "capabilities")?;
949        if !capabilities
950            .split(',')
951            .map(str::trim)
952            .any(|cap| cap == "local-inference")
953        {
954            return Err("agent profile must include the `local-inference` capability".into());
955        }
956        let max_tokens = scalar_text(fields, "max_tokens")?
957            .parse::<u32>()
958            .map_err(|_| "agent profile `max_tokens` must be 1..=256".to_string())?;
959        if !(1..=256).contains(&max_tokens) {
960            return Err("agent profile `max_tokens` must be 1..=256".into());
961        }
962        return Ok(());
963    }
964    if family != "project_agent"
965        || fields.get("kind").and_then(serde_json::Value::as_str) != Some("turn")
966    {
967        return Ok(());
968    }
969    let conversation = scalar_text(fields, "conversation")?;
970    if conversation.len() > 128 {
971        return Err("agent turn `conversation` cannot exceed 128 bytes".into());
972    }
973    let agent = scalar_text(fields, "agent_did")?;
974    if !agent.starts_with("did:") {
975        return Err("agent turn `agent_did` must be a DID".into());
976    }
977    let model_path = scalar_text(fields, "model_path")?.to_ascii_lowercase();
978    if !model_path.ends_with(".gguf")
979        && !model_path.ends_with(".p64")
980        && !model_path.ends_with(".safetensors")
981    {
982        return Err(
983            "agent turn `model_path` must identify a GGUF, P64, or Safetensors model".into(),
984        );
985    }
986    scalar_text(fields, "prompt")?;
987    scalar_text(fields, "response")?;
988    if scalar_text(fields, "assertion_status")? != "model_assertion_requires_verification" {
989        return Err("agent turn must retain the model-assertion verification label".into());
990    }
991    let review_status = scalar_text(fields, "review_status")?.to_ascii_lowercase();
992    if !matches!(review_status.as_str(), "pending" | "approved" | "rejected") {
993        return Err("agent turn `review_status` must be pending, approved, or rejected".into());
994    }
995    if review_status != "pending" {
996        require_did(fields, "reviewed_by")?;
997        scalar_text(fields, "reviewed_at")?;
998    }
999    Ok(())
1000}
1001
1002/// Cross-record social checks — channel exists, reply target
1003/// resolves, sender is a member.
1004fn validate_social_context(
1005    family: &str,
1006    fields: &BTreeMap<String, serde_json::Value>,
1007    records: &[CopRecord],
1008    current_id: Option<&str>,
1009) -> Result<(), String> {
1010    if family == "social_moderation" {
1011        let message_id = scalar_text(fields, "message_id")?;
1012        let message = records
1013            .iter()
1014            .find(|record| record.family == "social_message" && record.id == message_id)
1015            .ok_or_else(|| format!("moderated message `{message_id}` does not exist"))?;
1016        let thread = scalar_text(fields, "thread")?;
1017        if message
1018            .fields
1019            .get("thread")
1020            .and_then(serde_json::Value::as_str)
1021            .unwrap_or("general")
1022            != thread
1023        {
1024            return Err("moderation thread must match the message thread".into());
1025        }
1026        let channel = channel_record(records, thread)
1027            .ok_or_else(|| "moderation requires a managed channel".to_string())?;
1028        let actor = require_did(fields, "actor_did")?;
1029        let creator = channel
1030            .fields
1031            .get("creator_did")
1032            .and_then(serde_json::Value::as_str)
1033            .unwrap_or_default();
1034        let moderator = records.iter().any(|record| {
1035            record.family == "manifold_participant"
1036                && record
1037                    .fields
1038                    .get("manifold")
1039                    .and_then(serde_json::Value::as_str)
1040                    == Some(format!("channel:{thread}").as_str())
1041                && record
1042                    .fields
1043                    .get("participant")
1044                    .and_then(serde_json::Value::as_str)
1045                    == Some(actor)
1046                && record
1047                    .fields
1048                    .get("role")
1049                    .and_then(serde_json::Value::as_str)
1050                    == Some("moderator")
1051                && record
1052                    .fields
1053                    .get("status")
1054                    .and_then(serde_json::Value::as_str)
1055                    == Some("active")
1056        });
1057        if actor != creator && !moderator {
1058            return Err(
1059                "only the channel creator or an active moderator may hide a message".into(),
1060            );
1061        }
1062        if records.iter().any(|record| {
1063            record.family == "social_moderation"
1064                && record
1065                    .fields
1066                    .get("message_id")
1067                    .and_then(serde_json::Value::as_str)
1068                    == Some(message_id)
1069                && record
1070                    .fields
1071                    .get("action")
1072                    .and_then(serde_json::Value::as_str)
1073                    == Some("hide")
1074        }) {
1075            return Err("this message already has a hide moderation receipt".into());
1076        }
1077        return Ok(());
1078    }
1079
1080    if family == "social_notification" {
1081        let source_id = scalar_text(fields, "source_message_id")?;
1082        let source = records
1083            .iter()
1084            .find(|record| record.family == "social_message" && record.id == source_id)
1085            .ok_or_else(|| format!("source social message `{source_id}` does not exist"))?;
1086        let source_thread = source
1087            .fields
1088            .get("thread")
1089            .and_then(serde_json::Value::as_str)
1090            .unwrap_or("general");
1091        if scalar_text(fields, "thread")? != source_thread {
1092            return Err("notification thread must match its source message".into());
1093        }
1094        if let Some(current_id) = current_id {
1095            let current = records
1096                .iter()
1097                .find(|record| record.family == family && record.id == current_id)
1098                .ok_or_else(|| format!("social notification `{current_id}` does not exist"))?;
1099            for key in ["recipient", "from", "source_message_id", "thread"] {
1100                if current.fields.get(key) != fields.get(key) {
1101                    return Err(format!("social notification `{key}` is immutable"));
1102                }
1103            }
1104            let previous = current
1105                .fields
1106                .get("status")
1107                .and_then(serde_json::Value::as_str)
1108                .unwrap_or("unread");
1109            if previous == "read" && scalar_text(fields, "status")? != "read" {
1110                return Err("a read notification cannot be changed back to unread".into());
1111            }
1112        }
1113        return Ok(());
1114    }
1115
1116    if family == "social_request" {
1117        if let Some(current_id) = current_id {
1118            let current = records
1119                .iter()
1120                .find(|record| record.family == family && record.id == current_id)
1121                .ok_or_else(|| format!("social request `{current_id}` does not exist"))?;
1122            for key in ["from", "to", "request_type", "scope"] {
1123                if current.fields.get(key) != fields.get(key) {
1124                    return Err(format!(
1125                        "social request `{key}` is immutable after creation"
1126                    ));
1127                }
1128            }
1129            let previous = current
1130                .fields
1131                .get("status")
1132                .and_then(serde_json::Value::as_str)
1133                .unwrap_or("pending");
1134            let next = scalar_text(fields, "status")?;
1135            if previous != "pending" && next != previous {
1136                return Err("a decided social request cannot be transitioned again".into());
1137            }
1138        }
1139    }
1140
1141    if family == "channel" {
1142        let channel_id = scalar_text(fields, "channel_id")?;
1143        if records.iter().any(|record| {
1144            record.family == "channel"
1145                && Some(record.id.as_str()) != current_id
1146                && record
1147                    .fields
1148                    .get("channel_id")
1149                    .and_then(serde_json::Value::as_str)
1150                    == Some(channel_id)
1151        }) {
1152            return Err(format!("channel `{channel_id}` already exists"));
1153        }
1154        return Ok(());
1155    }
1156
1157    if family == "presence" {
1158        let did = require_did(fields, "did")?;
1159        let scope = scalar_text(fields, "scope")?;
1160        if records.iter().any(|record| {
1161            record.family == "presence"
1162                && Some(record.id.as_str()) != current_id
1163                && record.fields.get("did").and_then(serde_json::Value::as_str) == Some(did)
1164                && record
1165                    .fields
1166                    .get("scope")
1167                    .and_then(serde_json::Value::as_str)
1168                    == Some(scope)
1169        }) {
1170            return Err(format!(
1171                "presence for `{did}` in scope `{scope}` already exists and must be updated"
1172            ));
1173        }
1174        return Ok(());
1175    }
1176
1177    if family == "manifold_participant" {
1178        let manifold = scalar_text(fields, "manifold")?;
1179        let Some(channel_id) = manifold.strip_prefix("channel:") else {
1180            return Ok(());
1181        };
1182        let participant = require_did(fields, "participant")?;
1183        if let Some(current_id) = current_id {
1184            let current = records
1185                .iter()
1186                .find(|record| record.family == family && record.id == current_id)
1187                .ok_or_else(|| format!("participant record `{current_id}` does not exist"))?;
1188            for key in ["manifold", "participant"] {
1189                if current.fields.get(key) != fields.get(key) {
1190                    return Err(format!("channel participant `{key}` is immutable"));
1191                }
1192            }
1193            let actor = require_did(fields, "acted_by")?;
1194            let channel = channel_record(records, channel_id)
1195                .ok_or_else(|| format!("channel `{channel_id}` does not exist"))?;
1196            let creator = channel
1197                .fields
1198                .get("creator_did")
1199                .and_then(serde_json::Value::as_str)
1200                .unwrap_or_default();
1201            if actor != creator {
1202                return Err("only the channel creator may change participant roles".into());
1203            }
1204            scalar_text(fields, "acted_at")?;
1205        }
1206        if records.iter().any(|record| {
1207            record.family == "manifold_participant"
1208                && Some(record.id.as_str()) != current_id
1209                && record
1210                    .fields
1211                    .get("manifold")
1212                    .and_then(serde_json::Value::as_str)
1213                    == Some(manifold)
1214                && record
1215                    .fields
1216                    .get("participant")
1217                    .and_then(serde_json::Value::as_str)
1218                    == Some(participant)
1219        }) {
1220            return Err(format!(
1221                "participant `{participant}` already has a membership record for `{channel_id}`"
1222            ));
1223        }
1224        let channel = channel_record(records, channel_id)
1225            .ok_or_else(|| format!("channel `{channel_id}` does not exist"))?;
1226        let membership = channel
1227            .fields
1228            .get("membership")
1229            .and_then(serde_json::Value::as_str)
1230            .unwrap_or("invite");
1231        let status = scalar_text(fields, "status")?;
1232        if status == "active" && membership != "open" {
1233            let authorised_by = require_did(fields, "authorised_by")?;
1234            let creator = channel
1235                .fields
1236                .get("creator_did")
1237                .and_then(serde_json::Value::as_str)
1238                .unwrap_or_default();
1239            if authorised_by != creator {
1240                return Err("restricted channel activation requires the creator DID".into());
1241            }
1242        }
1243        return Ok(());
1244    }
1245
1246    if family == "social_request"
1247        && matches!(
1248            fields
1249                .get("request_type")
1250                .and_then(serde_json::Value::as_str),
1251            Some("channel-membership" | "channel-invite")
1252        )
1253    {
1254        let request_type = scalar_text(fields, "request_type")?;
1255        let scope = scalar_text(fields, "scope")?;
1256        let channel_id = scope
1257            .strip_prefix("channel:")
1258            .ok_or_else(|| "channel membership request `scope` must be channel:<id>".to_string())?;
1259        let channel = channel_record(records, channel_id)
1260            .ok_or_else(|| format!("channel `{channel_id}` does not exist"))?;
1261        let membership = channel
1262            .fields
1263            .get("membership")
1264            .and_then(serde_json::Value::as_str)
1265            .unwrap_or("invite");
1266        let creator = channel
1267            .fields
1268            .get("creator_did")
1269            .and_then(serde_json::Value::as_str)
1270            .unwrap_or_default();
1271        if request_type == "channel-membership" {
1272            if membership != "request" {
1273                return Err(format!(
1274                    "channel `{channel_id}` does not accept join requests"
1275                ));
1276            }
1277            if require_did(fields, "to")? != creator {
1278                return Err("a channel join request must be addressed to its creator DID".into());
1279            }
1280        } else {
1281            if membership != "invite" {
1282                return Err(format!("channel `{channel_id}` is not invitation-only"));
1283            }
1284            if require_did(fields, "from")? != creator {
1285                return Err("only the creator DID may invite a restricted-channel member".into());
1286            }
1287        }
1288        return Ok(());
1289    }
1290
1291    if family != "social_message" {
1292        return Ok(());
1293    }
1294    let thread = fields
1295        .get("thread")
1296        .and_then(serde_json::Value::as_str)
1297        .unwrap_or("general");
1298    let Some(channel) = channel_record(records, thread) else {
1299        if let Some(reply_to) = fields
1300            .get("reply_to")
1301            .and_then(serde_json::Value::as_str)
1302            .filter(|value| !value.is_empty())
1303        {
1304            validate_reply_target(records, reply_to, thread)?;
1305        }
1306        return Ok(());
1307    };
1308    if let Some(reply_to) = fields
1309        .get("reply_to")
1310        .and_then(serde_json::Value::as_str)
1311        .filter(|value| !value.is_empty())
1312    {
1313        validate_reply_target(records, reply_to, thread)?;
1314    }
1315    let sender = require_did(fields, "from")?;
1316    let creator = channel
1317        .fields
1318        .get("creator_did")
1319        .and_then(serde_json::Value::as_str)
1320        .unwrap_or_default();
1321    let membership = channel
1322        .fields
1323        .get("membership")
1324        .and_then(serde_json::Value::as_str)
1325        .unwrap_or("invite");
1326    if sender == creator || membership == "open" {
1327        return Ok(());
1328    }
1329    let manifold = format!("channel:{thread}");
1330    let active = records.iter().any(|record| {
1331        record.family == "manifold_participant"
1332            && record
1333                .fields
1334                .get("manifold")
1335                .and_then(serde_json::Value::as_str)
1336                == Some(manifold.as_str())
1337            && record
1338                .fields
1339                .get("participant")
1340                .and_then(serde_json::Value::as_str)
1341                == Some(sender)
1342            && record
1343                .fields
1344                .get("status")
1345                .and_then(serde_json::Value::as_str)
1346                == Some("active")
1347    });
1348    if active {
1349        Ok(())
1350    } else {
1351        Err(format!(
1352            "sender `{sender}` is not an active participant in channel `{thread}`"
1353        ))
1354    }
1355}
1356
1357/// Reply target must exist in the same channel.
1358fn validate_reply_target(
1359    records: &[CopRecord],
1360    reply_to: &str,
1361    thread: &str,
1362) -> Result<(), String> {
1363    let target = records
1364        .iter()
1365        .find(|record| record.family == "social_message" && record.id == reply_to)
1366        .ok_or_else(|| format!("reply target `{reply_to}` does not exist"))?;
1367    let target_thread = target
1368        .fields
1369        .get("thread")
1370        .and_then(serde_json::Value::as_str)
1371        .unwrap_or("general");
1372    if target_thread != thread {
1373        return Err("a reply target must belong to the same thread".into());
1374    }
1375    Ok(())
1376}
1377
1378/// Find the channel record with `channel_id`.
1379fn channel_record<'a>(records: &'a [CopRecord], channel_id: &str) -> Option<&'a CopRecord> {
1380    records.iter().find(|record| {
1381        record.family == "channel"
1382            && record
1383                .fields
1384                .get("channel_id")
1385                .and_then(serde_json::Value::as_str)
1386                == Some(channel_id)
1387    })
1388}
1389
1390/// Extract a required DID field; error when absent.
1391fn require_did<'a>(
1392    fields: &'a BTreeMap<String, serde_json::Value>,
1393    key: &str,
1394) -> Result<&'a str, String> {
1395    let value = scalar_text(fields, key)?;
1396    if !value.starts_with("did:") || value.bytes().any(|byte| byte.is_ascii_whitespace()) {
1397        return Err(format!("social field `{key}` must be a DID"));
1398    }
1399    Ok(value)
1400}
1401
1402/// Current Unix timestamp (seconds).
1403fn unix_now() -> i64 {
1404    SystemTime::now()
1405        .duration_since(UNIX_EPOCH)
1406        .map(|duration| duration.as_secs() as i64)
1407        .unwrap_or(0)
1408}
1409
1410/// Load the persisted ledger from `path`; empty ledger when
1411/// absent or unreadable.
1412fn load_ledger(path: &Path) -> RecordLedger {
1413    let Ok(bytes) = fs::read(path) else {
1414        return RecordLedger::default();
1415    };
1416    if bytes.len() > MAX_FILE_BYTES {
1417        return RecordLedger::default();
1418    }
1419    serde_json::from_slice(&bytes).unwrap_or_default()
1420}
1421
1422/// Persist the ledger to `path` (atomic-ish write; error on I/O
1423/// failure).
1424fn persist(path: &Path, ledger: &RecordLedger) -> Result<(), String> {
1425    if let Some(parent) = path.parent() {
1426        fs::create_dir_all(parent).map_err(|error| error.to_string())?;
1427    }
1428    let encoded = serde_json::to_vec_pretty(ledger).map_err(|error| error.to_string())?;
1429    if encoded.len() > MAX_FILE_BYTES {
1430        return Err("COP record ledger would exceed 2 MiB".into());
1431    }
1432    let staging = path.with_extension("json.tmp");
1433    fs::write(&staging, encoded).map_err(|error| error.to_string())?;
1434    fs::rename(&staging, path).map_err(|error| error.to_string())
1435}
1436
1437#[cfg(test)]
1438mod tests {
1439    use super::*;
1440
1441    // The daemon owns one process-global ledger. These tests replace its path
1442    // with separate temporary ledgers, so serialize that configuration under
1443    // Rust's otherwise parallel test harness.
1444    static TEST_STORE_LOCK: Mutex<()> = Mutex::new(());
1445
1446    /// Global mutex serializing store access across tests/handlers.
1447fn serial_store() -> std::sync::MutexGuard<'static, ()> {
1448        TEST_STORE_LOCK.lock().expect("COP test store lock")
1449    }
1450
1451    fn isolate() -> tempfile::TempDir {
1452        let dir = tempfile::TempDir::new().expect("tempdir");
1453        configure(dir.path().join("poet-cop-records.json"));
1454        dir
1455    }
1456
1457    #[tokio::test]
1458    async fn upsert_query_delete_and_restart_round_trip() {
1459        let _serial = serial_store();
1460        let dir = isolate();
1461        let created = upsert_handler(Bytes::from(
1462            serde_json::json!({
1463                "family": "agreement",
1464                "title": "Humanitarian ICT Commons Accord",
1465                "fields": { "status": "draft", "instrument": "COP-R4" }
1466            })
1467            .to_string(),
1468        ))
1469        .await;
1470        assert_eq!(created.status(), StatusCode::OK);
1471        let listed = query_handler(Bytes::from(
1472            serde_json::json!({ "family": "agreement", "query": "commons" }).to_string(),
1473        ))
1474        .await;
1475        assert_eq!(listed.status(), StatusCode::OK);
1476
1477        configure(dir.path().join("poet-cop-records.json"));
1478        let after_restart = query_handler(Bytes::from(
1479            serde_json::json!({ "family": "agreement", "query": "" }).to_string(),
1480        ))
1481        .await;
1482        assert_eq!(after_restart.status(), StatusCode::OK);
1483    }
1484
1485    #[tokio::test]
1486    async fn unknown_family_and_oversize_are_rejected() {
1487        let _serial = serial_store();
1488        let _dir = isolate();
1489        let unknown = upsert_handler(Bytes::from(
1490            serde_json::json!({ "family": "qapp", "title": "nope" }).to_string(),
1491        ))
1492        .await;
1493        assert_eq!(unknown.status(), StatusCode::BAD_REQUEST);
1494        let huge = query_handler(Bytes::from(vec![b'x'; RECORD_REQUEST_LIMIT_BYTES + 1])).await;
1495        assert_eq!(huge.status(), StatusCode::PAYLOAD_TOO_LARGE);
1496    }
1497
1498    #[test]
1499    fn economic_records_require_auditable_units_and_lifecycle() {
1500        let valid = BTreeMap::from([
1501            ("amount".into(), serde_json::json!("1250.50")),
1502            ("currency".into(), serde_json::json!("AUD")),
1503            ("lifecycle".into(), serde_json::json!("approved")),
1504            ("effective_date".into(), serde_json::json!("2026-08-29")),
1505            ("actor".into(), serde_json::json!("did:q42:treasurer")),
1506            ("provenance".into(), serde_json::json!("invoice:42")),
1507            ("sensitivity".into(), serde_json::json!("restricted")),
1508        ]);
1509        assert!(validate_economic_fields("project_budget", &valid).is_ok());
1510
1511        let mut missing_currency = valid.clone();
1512        missing_currency.remove("currency");
1513        assert!(
1514            validate_economic_fields("project_budget", &missing_currency)
1515                .unwrap_err()
1516                .contains("currency")
1517        );
1518
1519        let mut invalid_amount = valid.clone();
1520        invalid_amount.insert("amount".into(), serde_json::json!("not-a-number"));
1521        assert!(validate_economic_fields("project_budget", &invalid_amount)
1522            .unwrap_err()
1523            .contains("amount"));
1524
1525        let mut false_completion = valid;
1526        false_completion.insert("lifecycle".into(), serde_json::json!("paid"));
1527        assert!(
1528            validate_economic_fields("project_budget", &false_completion)
1529                .unwrap_err()
1530                .contains("lifecycle")
1531        );
1532    }
1533
1534    #[tokio::test]
1535    async fn economic_family_round_trip_preserves_audit_fields() {
1536        let _serial = serial_store();
1537        let _dir = isolate();
1538        let created = upsert_handler(Bytes::from(
1539            serde_json::json!({
1540                "family": "project_actual",
1541                "title": "Accessibility review",
1542                "fields": {
1543                    "amount": "840.00",
1544                    "currency": "AUD",
1545                    "category": "quality",
1546                    "lifecycle": "verified",
1547                    "effective_date": "2026-08-29",
1548                    "actor": "did:q42:reviewer",
1549                    "provenance": "receipt:accessibility-001",
1550                    "sensitivity": "restricted"
1551                }
1552            })
1553            .to_string(),
1554        ))
1555        .await;
1556        assert_eq!(created.status(), StatusCode::OK);
1557
1558        let listed = query_handler(Bytes::from(
1559            serde_json::json!({ "family": "project_actual", "query": "Accessibility" }).to_string(),
1560        ))
1561        .await;
1562        assert_eq!(listed.status(), StatusCode::OK);
1563    }
1564
1565    #[tokio::test]
1566    async fn project_family_kind_filter_selects_matching_records() {
1567        let _serial = serial_store();
1568        let _dir = isolate();
1569        let created = upsert_handler(Bytes::from(
1570            serde_json::json!({
1571                "family": "project_task",
1572                "title": "Bind COP ledger",
1573                "fields": { "status": "open", "kind": "task", "priority": "high" }
1574            })
1575            .to_string(),
1576        ))
1577        .await;
1578        assert_eq!(created.status(), StatusCode::OK);
1579        let other = upsert_handler(Bytes::from(
1580            serde_json::json!({
1581                "family": "project_issue",
1582                "title": "Ledger write failed closed",
1583                "fields": { "status": "open", "kind": "bug", "severity": "high" }
1584            })
1585            .to_string(),
1586        ))
1587        .await;
1588        assert_eq!(other.status(), StatusCode::OK);
1589
1590        let tasks = query_handler(Bytes::from(
1591            serde_json::json!({ "family": "project_task", "query": "", "kind": "task" })
1592                .to_string(),
1593        ))
1594        .await;
1595        assert_eq!(tasks.status(), StatusCode::OK);
1596        let miss = query_handler(Bytes::from(
1597            serde_json::json!({ "family": "project_task", "query": "", "kind": "bug" }).to_string(),
1598        ))
1599        .await;
1600        assert_eq!(miss.status(), StatusCode::OK);
1601    }
1602
1603    #[tokio::test]
1604    async fn dataset_and_ontology_families_round_trip() {
1605        let _serial = serial_store();
1606        let _dir = isolate();
1607        let dataset = upsert_handler(Bytes::from(
1608            serde_json::json!({
1609                "family": "dataset",
1610                "title": "Citation graph",
1611                "fields": { "format": "n3", "sensitivity": "public" }
1612            })
1613            .to_string(),
1614        ))
1615        .await;
1616        assert_eq!(dataset.status(), StatusCode::OK);
1617        let shape = upsert_handler(Bytes::from(
1618            serde_json::json!({
1619                "family": "ontology_shape",
1620                "title": "PrincipalShape",
1621                "fields": { "target": "q42:Principal", "constraint": "sh:not", "value": "owl:Thing" }
1622            })
1623            .to_string(),
1624        ))
1625        .await;
1626        assert_eq!(shape.status(), StatusCode::OK);
1627    }
1628
1629    #[tokio::test]
1630    async fn nested_fields_rejected_and_gov_share_round_trip() {
1631        let _serial = serial_store();
1632        let _dir = isolate();
1633        let nested = upsert_handler(Bytes::from(
1634            serde_json::json!({
1635                "family": "gov_meeting",
1636                "title": "bad",
1637                "fields": { "agenda": { "item": 1 } }
1638            })
1639            .to_string(),
1640        ))
1641        .await;
1642        assert_eq!(nested.status(), StatusCode::BAD_REQUEST);
1643
1644        let meeting = upsert_handler(Bytes::from(
1645            serde_json::json!({
1646                "family": "gov_meeting",
1647                "title": "Commons assembly",
1648                "fields": { "when": "2026-08-28", "quorum": "3" }
1649            })
1650            .to_string(),
1651        ))
1652        .await;
1653        assert_eq!(meeting.status(), StatusCode::OK);
1654
1655        let share = upsert_handler(Bytes::from(
1656            serde_json::json!({
1657                "family": "health_share",
1658                "title": "lab panel",
1659                "fields": { "share_to": "did:example:doctor", "purpose": "clinical-care", "sensitivity": "restricted" }
1660            })
1661            .to_string(),
1662        ))
1663        .await;
1664        assert_eq!(share.status(), StatusCode::OK);
1665
1666        let pulse = try_upsert(
1667            "pulse_event",
1668            "poet/social#1",
1669            BTreeMap::from([
1670                (
1671                    "channel".into(),
1672                    serde_json::Value::String("poet/social".into()),
1673                ),
1674                (
1675                    "payload_type".into(),
1676                    serde_json::Value::String("agent-message".into()),
1677                ),
1678                ("seq".into(), serde_json::json!(1)),
1679            ]),
1680        );
1681        assert!(pulse.is_ok(), "{pulse:?}");
1682
1683        let social = upsert_handler(Bytes::from(
1684            serde_json::json!({
1685                "family": "social_message",
1686                "title": "hello",
1687                "fields": { "from": "did:example:alice", "body": "hi" }
1688            })
1689            .to_string(),
1690        ))
1691        .await;
1692        assert_eq!(social.status(), StatusCode::OK);
1693    }
1694
1695    #[tokio::test]
1696    async fn governance_workflow_families_round_trip() {
1697        let _serial = serial_store();
1698        let _dir = isolate();
1699        for (family, title, fields) in [
1700            (
1701                "context_markup",
1702                "Document term",
1703                serde_json::json!({ "document": "container:1", "byte_span": "0:8" }),
1704            ),
1705            (
1706                "provenance_entry",
1707                "Snapshot author",
1708                serde_json::json!({ "artifact": "checkpoint:1", "actor": "did:example:alice" }),
1709            ),
1710            (
1711                "constituency",
1712                "Data subject",
1713                serde_json::json!({ "artifact": "container:1", "iri": "did:example:alice" }),
1714            ),
1715            (
1716                "constituency_consent",
1717                "Explicit consent",
1718                serde_json::json!({ "constituency": "did:example:alice", "status": "granted" }),
1719            ),
1720        ] {
1721            let response = upsert_handler(Bytes::from(
1722                serde_json::json!({ "family": family, "title": title, "fields": fields })
1723                    .to_string(),
1724            ))
1725            .await;
1726            assert_eq!(response.status(), StatusCode::OK, "family {family}");
1727
1728            let listed = query_handler(Bytes::from(
1729                serde_json::json!({ "family": family, "query": title }).to_string(),
1730            ))
1731            .await;
1732            assert_eq!(listed.status(), StatusCode::OK, "family {family}");
1733        }
1734    }
1735
1736    #[tokio::test]
1737    async fn unconfigured_store_is_unavailable() {
1738        let _serial = serial_store();
1739        *STORE.lock().expect("lock") = None;
1740        let listed = query_handler(Bytes::from(
1741            serde_json::json!({ "family": "agreement", "query": "" }).to_string(),
1742        ))
1743        .await;
1744        assert_eq!(listed.status(), StatusCode::SERVICE_UNAVAILABLE);
1745    }
1746}