zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Summary v2 (ADR ZC-0019 ยง4): what `GET /v2/summary` returns.
//! `docs/agent-api/summary.v2.json` is the fixture: zc's tests serialize to
//! it, and the desktop app decodes it. An incompatible change bumps
//! `summary_version`.
//!
//! Built from summary v1 (the same merged hub + local view) plus what only v2
//! carries: `nodes`, `jobs`, `ledger`, and the slots of features that do not
//! exist yet (`squads`, `sandbox`, `policy`), which are `null` until they
//! ship -- never an empty value that would read as "none".

use crate::agent::jobs::Job;
use crate::agent::summary::{
    Account, HourlyHistory, HubStatus, Links, MeshStatus, NetworkCapacity, PriceRange, Prices,
    Problem, Requests, Summary, WorkerCounts,
};
use serde::{Deserialize, Serialize};

pub const SUMMARY_V2_VERSION: u32 = 2;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SummaryV2 {
    pub summary_version: u32,
    pub agent_version: String,
    pub as_of: String,
    pub env: String,
    pub hub: HubStatus,
    pub problems: Vec<Problem>,
    pub account: Option<Account>,
    /// This node first, then the account's other devices as the hub lists
    /// them. This node is always present, even before the hub answers.
    pub nodes: Vec<Node>,
    pub jobs: Jobs,
    /// `null` until the hub's ledger has answered once.
    pub ledger: Option<Ledger>,
    /// `null` until squads exist (zc#517).
    pub squads: Option<Vec<serde_json::Value>>,
    /// `null` until the sandbox runtime exists (zc#510).
    pub sandbox: Option<serde_json::Value>,
    /// The effective `policy.toml` (zc#514); `null` before the node has one.
    pub policy: Option<serde_json::Value>,
    /// What the node policy admitted and refused, by reason, with the last
    /// refusals (the broker mirrors it to `admission.json`). Absent until the
    /// broker has refused something.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admission: Option<serde_json::Value>,
    /// What the node could have earned and did not (ZC-0025): capacity per
    /// class (total / budget / free), eligible-idle seconds, utilisation, and
    /// refusals by reason, as the broker mirrors them (`revenue.json`). Absent
    /// until the broker has written one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revenue: Option<serde_json::Value>,
    pub prices: Prices,
    pub mesh: MeshStatus,
    pub links: Links,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<HourlyHistory>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkCapacity>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    pub node_pubkey: String,
    pub name: String,
    pub this_node: bool,
    /// `fresh` | `stale` | `gone` from the hub; `null` for this node before
    /// the hub has listed it.
    pub freshness: Option<String>,
    pub last_seen_at: Option<String>,
    /// How this node's workers run: `host` | `container`. Only known for
    /// this node; `null` for the others until the hub reports it.
    pub backend: Option<String>,
    /// The budget this node gives and how much of it is used: `null` until
    /// budgets exist (zc#513).
    pub budget: Option<serde_json::Value>,
    /// Worker rows the hub lists for this node.
    pub hub_workers: u32,
    /// What its workers charge, lowest to highest; `null` when none do.
    pub effective_price_per_hour: Option<PriceRange>,
    pub link: Option<String>,
    /// Only on this node: what the agent itself supervises.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub local: Option<LocalNode>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LocalNode {
    pub sharing: bool,
    pub broker: String,
    pub workers: WorkerCounts,
    pub requests: Requests,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Jobs {
    pub live: Vec<Job>,
    /// Jobs that finished in the last 24 hours.
    pub done_24h: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ledger {
    /// Always `jpy`: amounts are yen (ADR 0027).
    pub unit: String,
    pub today: LedgerPeriod,
    pub month: LedgerPeriod,
    /// The IANA zone "today" and "this month" start in.
    pub tz: String,
    /// Earned per day over the last 7 days, oldest first, today last (the
    /// hub's `week`). Empty when the hub does not send it.
    #[serde(default)]
    pub days: Vec<LedgerDay>,
    /// Last calendar month's earnings, for "vs last month"; `null` when the
    /// hub does not send it.
    #[serde(default)]
    pub prev_month_earned: Option<f64>,
    /// When the hub last answered, RFC 3339 UTC.
    pub as_of: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerDay {
    /// `YYYY-MM-DD` in `tz`.
    pub date: String,
    pub earned: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerPeriod {
    pub earned: f64,
    /// `null` where the hub does not break it out (today's spend).
    pub spent: Option<f64>,
    /// Per job source; `null` until the hub attributes transactions to a
    /// source (zc#516).
    pub by_source: Option<serde_json::Value>,
}

/// What v2 adds to the v1 summary.
pub struct Extras {
    pub backend: &'static str,
    pub jobs: Jobs,
    pub ledger: Option<Ledger>,
    pub policy: Option<serde_json::Value>,
    pub admission: Option<serde_json::Value>,
    pub revenue: Option<serde_json::Value>,
}

pub fn build(v1: Summary, x: Extras) -> SummaryV2 {
    let me = &v1.this_mac;
    let local = LocalNode {
        sharing: me.sharing,
        broker: me.broker.clone(),
        workers: me.workers,
        requests: me.requests,
    };
    let mut nodes: Vec<Node> = vec![];
    let mut this_seen = false;
    for d in v1.devices.iter().flatten() {
        let this = d.this_mac;
        this_seen |= this;
        nodes.push(Node {
            node_pubkey: d.node_pubkey.clone(),
            name: d.name.clone(),
            this_node: this,
            freshness: Some(d.freshness.clone()),
            last_seen_at: d.last_seen_at.clone(),
            backend: this.then(|| x.backend.to_string()),
            budget: None,
            hub_workers: d.workers,
            effective_price_per_hour: d.effective_price_per_hour,
            link: d.link.clone(),
            local: this.then(|| local.clone()),
        });
    }
    if !this_seen {
        nodes.push(Node {
            node_pubkey: me.node_pubkey.clone(),
            name: me.name.clone(),
            this_node: true,
            freshness: None,
            last_seen_at: None,
            backend: Some(x.backend.to_string()),
            budget: None,
            hub_workers: 0,
            effective_price_per_hour: None,
            link: None,
            local: Some(local),
        });
    }
    // This node first; the rest keep the hub's order.
    nodes.sort_by_key(|n| !n.this_node);
    SummaryV2 {
        summary_version: SUMMARY_V2_VERSION,
        agent_version: v1.agent_version,
        as_of: v1.as_of,
        env: v1.env,
        hub: v1.hub,
        problems: v1.problems,
        account: v1.account,
        nodes,
        jobs: x.jobs,
        ledger: x.ledger,
        squads: None,
        sandbox: None,
        policy: x.policy,
        admission: x.admission,
        revenue: x.revenue,
        prices: v1.prices,
        mesh: v1.mesh,
        links: v1.links,
        history: v1.history,
        network: v1.network,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const V1: &str = include_str!("../../docs/agent-api/summary.v1.json");
    const V2: &str = include_str!("../../docs/agent-api/summary.v2.json");

    fn fixture() -> SummaryV2 {
        let v1: Summary = serde_json::from_str(V1).unwrap();
        build(
            v1,
            Extras {
                backend: "container",
                jobs: Jobs {
                    live: vec![Job {
                        id: "j42".into(),
                        state: "live".into(),
                        source: None,
                        squad: None,
                        worker: "jeans-mbp-w0".into(),
                        started_at: "2026-09-13T01:41:50Z".into(),
                        finished_at: None,
                        requests: 3,
                    }],
                    done_24h: 17,
                },
                ledger: Some(Ledger {
                    unit: "jpy".into(),
                    today: LedgerPeriod {
                        earned: 12.4,
                        spent: None,
                        by_source: None,
                    },
                    month: LedgerPeriod {
                        earned: 310.2,
                        spent: Some(42.0),
                        by_source: None,
                    },
                    tz: "Asia/Tokyo".into(),
                    days: vec![
                        LedgerDay {
                            date: "2026-09-07".into(),
                            earned: 8.0,
                        },
                        LedgerDay {
                            date: "2026-09-08".into(),
                            earned: 11.5,
                        },
                        LedgerDay {
                            date: "2026-09-09".into(),
                            earned: 0.0,
                        },
                        LedgerDay {
                            date: "2026-09-10".into(),
                            earned: 9.2,
                        },
                        LedgerDay {
                            date: "2026-09-11".into(),
                            earned: 14.1,
                        },
                        LedgerDay {
                            date: "2026-09-12".into(),
                            earned: 13.0,
                        },
                        LedgerDay {
                            date: "2026-09-13".into(),
                            earned: 12.4,
                        },
                    ],
                    prev_month_earned: Some(262.9),
                    as_of: "2026-09-13T01:41:30Z".into(),
                }),
                policy: None,
                admission: None,
                revenue: None,
            },
        )
    }

    /// The fixture is the contract: what zc serializes is exactly it.
    #[test]
    fn serializes_to_the_v2_fixture() {
        let ours = serde_json::to_value(fixture()).unwrap();
        let theirs: serde_json::Value = serde_json::from_str(V2).unwrap();
        assert_eq!(
            ours,
            theirs,
            "{}",
            serde_json::to_string_pretty(&ours).unwrap()
        );
        let back: SummaryV2 = serde_json::from_str(V2).unwrap();
        assert_eq!(back, fixture());
    }

    #[test]
    fn this_node_comes_first_and_is_there_before_the_hub_answers() {
        let s = fixture();
        assert!(s.nodes[0].this_node && s.nodes[0].local.is_some());
        assert_eq!(s.nodes.iter().filter(|n| n.this_node).count(), 1);
        assert!(s.nodes[1..]
            .iter()
            .all(|n| n.local.is_none() && n.backend.is_none()));

        let mut v1: Summary = serde_json::from_str(V1).unwrap();
        v1.devices = None;
        let s = build(
            v1,
            Extras {
                backend: "host",
                jobs: Jobs {
                    live: vec![],
                    done_24h: 0,
                },
                ledger: None,
                policy: None,
                admission: None,
                revenue: None,
            },
        );
        assert_eq!(s.nodes.len(), 1);
        assert_eq!(
            (
                s.nodes[0].this_node,
                s.nodes[0].backend.as_deref(),
                s.nodes[0].freshness.as_deref()
            ),
            (true, Some("host"), None)
        );
        let wire = serde_json::to_value(&s).unwrap();
        for k in ["squads", "sandbox", "policy", "ledger"] {
            assert!(wire[k].is_null(), "{k} is null, not absent or empty");
            assert!(wire.as_object().unwrap().contains_key(k));
        }
    }
}