x0x 0.19.46

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Network and status CLI commands.

use crate::cli::{print_value, DaemonClient};
use anyhow::Result;
use four_word_networking::FourWordAdaptiveEncoder;

/// Inject `location_words` for each address in `external_addrs`.
fn inject_location_words(value: &mut serde_json::Value) {
    let addr_encoder = match FourWordAdaptiveEncoder::new() {
        Ok(e) => e,
        Err(_) => return,
    };

    if let Some(obj) = value.as_object_mut() {
        if let Some(addrs) = obj
            .get("external_addrs")
            .and_then(|v| v.as_array())
            .cloned()
        {
            let location: Vec<serde_json::Value> = addrs
                .iter()
                .filter_map(|a| a.as_str())
                .filter_map(|addr| {
                    addr_encoder.encode(addr).ok().map(|words| {
                        serde_json::json!({
                            "addr": addr,
                            "location_words": words,
                        })
                    })
                })
                .collect();
            if !location.is_empty() {
                obj.insert(
                    "location_words".to_string(),
                    serde_json::Value::Array(location),
                );
            }
        }
    }
}

/// `x0x health` — GET /health
pub async fn health(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/health").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x status` — GET /status
pub async fn status(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let mut resp = client.get("/status").await?;
    let encoder = four_word_networking::IdentityEncoder::new();
    super::identity::inject_identity_words(&encoder, &mut resp);
    inject_location_words(&mut resp);
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x peers` — GET /peers
pub async fn peers(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/peers").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x presence` — GET /presence
pub async fn presence(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/presence").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x network status` — GET /network/status
pub async fn network_status(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/network/status").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x network cache` — GET /network/bootstrap-cache
pub async fn bootstrap_cache(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/network/bootstrap-cache").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x diagnostics connectivity` — GET /diagnostics/connectivity
///
/// Prints the ant-quic NodeStatus snapshot as JSON. Includes UPnP port-mapping
/// state, NAT type, mDNS discovery state, direct vs relayed connection counts,
/// hole-punch success rate, and advertised external addresses. Primary tool
/// for answering "is ant-quic's 100%-connectivity promise holding?".
pub async fn diagnostics_connectivity(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/diagnostics/connectivity").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x diagnostics ack` — GET /diagnostics/ack
///
/// Prints ACK-v2 per-stage latency buckets and outcome counters. This splits
/// the old opaque "ACK timeout" class into sender open/write/finish/read and
/// receiver demux/admission/response-write stages.
pub async fn diagnostics_ack(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/diagnostics/ack").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x diagnostics gossip` — GET /diagnostics/gossip
///
/// Prints PubSub drop-detection counters. Non-zero `decode_to_delivery_drops`
/// means messages reached the local pipeline but failed to hand off to the
/// subscriber channel (buffer full or dropped subscription). Primary tool
/// for the 100%-delivery proof under stress.
pub async fn diagnostics_gossip(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/diagnostics/gossip").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x diagnostics dm` — GET /diagnostics/dm
///
/// Prints direct-message send/receive counters, subscriber fan-out health, and
/// per-peer timing/path state.
pub async fn diagnostics_dm(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/diagnostics/dm").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x diagnostics groups` — GET /diagnostics/groups
///
/// Prints per-group ingest counters: `members_v2_size`, metadata/public
/// listener state, accepted message count, last-message-at, and per-reason
/// drop buckets (`decode_failed`, `author_banned`,
/// `write_policy_violation`, `signature_failed`, `other`). The
/// `write_policy_violation` bucket is the canary for the
/// join-roster-propagation regression — non-zero on the owner side means
/// joiners' messages reached the listener but the owner's `members_v2`
/// view is missing them.
pub async fn diagnostics_groups(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get("/diagnostics/groups").await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x peers probe <peer_id>` — POST /peers/:peer_id/probe
///
/// Active liveness probe (ant-quic 0.27.2 #173). Sends a lightweight probe
/// envelope and waits for the remote reader's ACK-v1 reply. Prints measured
/// round-trip time.
pub async fn peers_probe(
    client: &DaemonClient,
    peer_id: &str,
    timeout_ms: Option<u64>,
) -> Result<()> {
    client.ensure_running().await?;
    let path = if let Some(ms) = timeout_ms {
        format!("/peers/{peer_id}/probe?timeout_ms={ms}")
    } else {
        format!("/peers/{peer_id}/probe")
    };
    let resp = client.post_empty(&path).await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x peers health <peer_id>` — GET /peers/:peer_id/health
///
/// Connection health snapshot for a peer (ant-quic 0.27.1 #170). Returns
/// lifecycle state, generation, directional activity timestamps, and the
/// most-recent close reason.
pub async fn peers_health(client: &DaemonClient, peer_id: &str) -> Result<()> {
    client.ensure_running().await?;
    let resp = client.get(&format!("/peers/{peer_id}/health")).await?;
    print_value(client.format(), &resp);
    Ok(())
}

/// `x0x peers events` — GET /peers/events (SSE).
///
/// Streams peer lifecycle transitions (`Established`, `Replaced`, `Closing`,
/// `Closed`, `ReaderExited`) as they occur. Prints each event as a JSON
/// line to stdout. Press Ctrl-C to stop.
pub async fn peers_events(client: &DaemonClient) -> Result<()> {
    use futures::StreamExt as _;
    client.ensure_running().await?;
    let resp = client.get_stream("/peers/events").await?;
    let mut stream = resp.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let bytes = chunk.map_err(|e| anyhow::anyhow!("stream error: {e}"))?;
        let s = String::from_utf8_lossy(&bytes);
        print!("{s}");
    }
    Ok(())
}

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

    #[test]
    fn inject_location_words_skips_non_object() {
        let mut value = serde_json::json!([1, 2, 3]);
        inject_location_words(&mut value);
        assert!(value.is_array());
    }

    #[test]
    fn inject_location_words_skips_missing_addrs() {
        let mut value = serde_json::json!({"name": "test"});
        inject_location_words(&mut value);
        assert!(value.get("location_words").is_none());
    }

    #[test]
    fn inject_location_words_handles_empty_addrs() {
        let mut value = serde_json::json!({"external_addrs": []});
        inject_location_words(&mut value);
        assert!(value.get("location_words").is_none());
    }

    #[test]
    fn inject_location_words_encodes_valid_addrs() {
        let mut value = serde_json::json!({
            "external_addrs": ["1.2.3.4:5483"]
        });
        inject_location_words(&mut value);
        // May or may not encode depending on FourWordAdaptiveEncoder
        // Just verify it doesn't panic
        let _ = value;
    }
}

/// Start a mock axum server that returns the given JSON for any request.
/// Returns the base URL and a shutdown sender.
#[allow(dead_code)]
async fn start_mock_server(
    response_json: serde_json::Value,
) -> (String, tokio::sync::oneshot::Sender<()>) {
    use std::sync::Arc;

    let json = Arc::new(response_json);
    let app = axum::Router::new().fallback(move |_req: axum::extract::Request| {
        let json = Arc::clone(&json);
        async move {
            let body = serde_json::to_vec(&*json).unwrap();
            axum::response::Response::builder()
                .status(200)
                .header("content-type", "application/json")
                .body(axum::body::Body::from(body))
                .unwrap()
        }
    });

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (tx, rx) = tokio::sync::oneshot::channel::<()>();

    tokio::spawn(async move {
        axum::serve(listener, app.into_make_service())
            .with_graceful_shutdown(async {
                rx.await.ok();
            })
            .await
            .ok();
    });

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    (format!("http://{}", addr), tx)
}

#[tokio::test]
async fn health_returns_mock_response() {
    let mock_resp = serde_json::json!({"status": "ok", "version": "0.19.42"});
    let (url, _shutdown) = start_mock_server(mock_resp.clone()).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = health(&client).await;
    assert!(result.is_ok(), "health should succeed: {:?}", result);
}

#[tokio::test]
async fn status_returns_mock_response() {
    let mock_resp = serde_json::json!({
        "agent_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "peers": 5,
        "status": "connected"
    });
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = status(&client).await;
    assert!(result.is_ok(), "status should succeed: {:?}", result);
}

#[tokio::test]
async fn peers_returns_mock_response() {
    let mock_resp = serde_json::json!([{"peer_id": "abc123", "state": "connected"}]);
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = peers(&client).await;
    assert!(result.is_ok(), "peers should succeed: {:?}", result);
}

#[tokio::test]
async fn presence_returns_mock_response() {
    let mock_resp = serde_json::json!([{"agent_id": "abc", "online": true}]);
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = presence(&client).await;
    assert!(result.is_ok(), "presence should succeed: {:?}", result);
}

#[tokio::test]
async fn network_status_returns_mock_response() {
    let mock_resp = serde_json::json!({"nat_type": "FullCone", "external_addrs": ["1.2.3.4:5483"]});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = network_status(&client).await;
    assert!(
        result.is_ok(),
        "network_status should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn bootstrap_cache_returns_mock_response() {
    let mock_resp = serde_json::json!([{"addr": "1.2.3.4:5483", "peer_id": "abc"}]);
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = bootstrap_cache(&client).await;
    assert!(
        result.is_ok(),
        "bootstrap_cache should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn diagnostics_connectivity_returns_mock_response() {
    let mock_resp = serde_json::json!({"nat_type": "FullCone", "upnp": true});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = diagnostics_connectivity(&client).await;
    assert!(
        result.is_ok(),
        "diagnostics_connectivity should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn diagnostics_gossip_returns_mock_response() {
    let mock_resp = serde_json::json!({"decode_to_delivery_drops": 0, "messages_received": 100});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = diagnostics_gossip(&client).await;
    assert!(
        result.is_ok(),
        "diagnostics_gossip should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn diagnostics_dm_returns_mock_response() {
    let mock_resp = serde_json::json!({"messages_sent": 50, "messages_received": 30});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = diagnostics_dm(&client).await;
    assert!(
        result.is_ok(),
        "diagnostics_dm should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn diagnostics_groups_returns_mock_response() {
    let mock_resp = serde_json::json!({"groups": [{"name": "test-group", "members": 3}]});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = diagnostics_groups(&client).await;
    assert!(
        result.is_ok(),
        "diagnostics_groups should succeed: {:?}",
        result
    );
}

#[tokio::test]
async fn peers_probe_returns_mock_response() {
    let mock_resp = serde_json::json!({"rtt_ms": 42});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = peers_probe(&client, "abc123", Some(5000)).await;
    assert!(result.is_ok(), "peers_probe should succeed: {:?}", result);
}

#[tokio::test]
async fn peers_health_returns_mock_response() {
    let mock_resp = serde_json::json!({"state": "Established", "generation": 3});
    let (url, _shutdown) = start_mock_server(mock_resp).await;
    let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();

    let result = peers_health(&client, "abc123").await;
    assert!(result.is_ok(), "peers_health should succeed: {:?}", result);
}