cmn-hypha 0.5.1

The reference CMN client CLI — release spores, query synapses, resolve bonds, and manage your local mycelium.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Agent-First Data output layer. All CLI code emits through Output methods.

use serde::Serialize;
use std::process::ExitCode;
use std::sync::{Mutex, mpsc};
use std::thread::JoinHandle;
use std::time::Instant;

/// Result type that handles output formatting and exit codes.
///
/// A dedicated writer thread owns one [`agent_first_data::CliEmitter`] for the
/// complete command lifecycle. This keeps [`Output`] usable through the
/// thread-safe [`crate::EventSink`] trait while preserving AFDATA ordering,
/// routing, and single-terminal-event enforcement.
pub struct Output {
    sender: mpsc::Sender<OutputMessage>,
    worker: Mutex<Option<JoinHandle<()>>>,
    started: Instant,
}

enum OutputMessage {
    Emit(agent_first_data::Event),
    Finish {
        event: agent_first_data::Event,
        success_code: u8,
        reply: mpsc::SyncSender<u8>,
    },
    Shutdown,
}

fn built_event(
    result: Result<agent_first_data::Event, agent_first_data::BuildError>,
) -> agent_first_data::Event {
    result.unwrap_or_else(|err| agent_first_data::build_cli_error(&err.to_string(), None))
}

/// Scrub every scheme-prefixed URL embedded in diagnostic prose.
///
/// AFDATA intentionally does not scan arbitrary prose, so Hypha performs this
/// boundary pass before placing messages into protocol events.
pub fn redact_urls_in_text(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut rendered = String::with_capacity(text.len());
    let mut copied_until = 0;
    let mut search_from = 0;

    while let Some(relative) = text[search_from..].find("://") {
        let separator = search_from + relative;
        let mut start = separator;
        while start > 0
            && bytes[start - 1].is_ascii()
            && (bytes[start - 1].is_ascii_alphanumeric()
                || matches!(bytes[start - 1], b'+' | b'-' | b'.'))
        {
            start -= 1;
        }
        if start == separator || !bytes[start].is_ascii_alphabetic() {
            search_from = separator + 3;
            continue;
        }

        let mut end = separator + 3;
        while end < bytes.len()
            && !bytes[end].is_ascii_whitespace()
            && !matches!(
                bytes[end],
                b'"' | b'\'' | b'<' | b'>' | b'{' | b'}' | b'\\' | b'|'
            )
        {
            end += 1;
        }
        while end > separator + 3
            && matches!(
                bytes[end - 1],
                b'.' | b',' | b';' | b':' | b'!' | b')' | b']'
            )
        {
            end -= 1;
        }

        rendered.push_str(&text[copied_until..start]);
        rendered.push_str(&agent_first_data::redact_url_secrets(&text[start..end]));
        copied_until = end;
        search_from = end.max(separator + 3);
    }

    rendered.push_str(&text[copied_until..]);
    rendered
}

/// Redact credential-bearing values in embedded CMN documents without
/// rewriting their protocol-defined `url` field name.
///
/// Hypha-owned URL fields use AFDATA's `_url` suffix and are scrubbed by the
/// emitter. CMN v1 documents instead define bare `url` fields, so those values
/// need this schema-preserving adapter before they reach any serializer.
fn redact_embedded_cmn_urls(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Object(fields) => {
            for (name, field) in fields {
                if name == "url"
                    && let serde_json::Value::String(raw_url) = field
                {
                    *raw_url = agent_first_data::redact_url_secrets(raw_url);
                }
                redact_embedded_cmn_urls(field);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                redact_embedded_cmn_urls(item);
            }
        }
        _ => {}
    }
}

/// A Synapse selector accepts either a configured domain or a whole URL. Keep
/// the selector name honest while scrubbing it whenever the supplied value is
/// URL-shaped.
fn redact_url_selectors(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Object(fields) => {
            for (name, field) in fields {
                if name == "synapse_selector"
                    && let serde_json::Value::String(selector) = field
                {
                    *selector = redact_urls_in_text(selector);
                }
                redact_url_selectors(field);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                redact_url_selectors(item);
            }
        }
        _ => {}
    }
}

fn redact_boundary_values(value: &mut serde_json::Value) {
    redact_embedded_cmn_urls(value);
    redact_url_selectors(value);
}

impl Output {
    /// Create a finite one-shot emitter using AFDATA's default split routing.
    pub fn new(format: agent_first_data::OutputFormat) -> Self {
        Self::with_output_to(format, agent_first_data::OutputTo::Split)
    }

    /// Create an emitter using the requested AFDATA destination policy.
    pub fn with_output_to(
        format: agent_first_data::OutputFormat,
        output_to: agent_first_data::OutputTo,
    ) -> Self {
        let started = Instant::now();
        let (sender, receiver) = mpsc::channel();
        let worker = std::thread::spawn(move || {
            let mut emitter = agent_first_data::CliEmitter::from_output_to(output_to, format)
                .with_strict_protocol();
            while let Ok(message) = receiver.recv() {
                match message {
                    OutputMessage::Emit(event) => {
                        let _ = emitter.emit(event);
                    }
                    OutputMessage::Finish {
                        event,
                        success_code,
                        reply,
                    } => {
                        let code = emitter.finish(event, success_code);
                        let _ = reply.send(code);
                        break;
                    }
                    OutputMessage::Shutdown => break,
                }
            }
        });
        Self {
            sender,
            worker: Mutex::new(Some(worker)),
            started,
        }
    }

    fn elapsed_ms(&self) -> u64 {
        u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX)
    }

    fn elapsed_trace(&self) -> serde_json::Value {
        serde_json::json!({"duration_ms": self.elapsed_ms()})
    }

    fn with_elapsed_trace(&self, mut trace: serde_json::Value) -> serde_json::Value {
        if let serde_json::Value::Object(fields) = &mut trace {
            fields.insert("duration_ms".to_string(), self.elapsed_ms().into());
        }
        trace
    }

    /// Best-effort emit for mid-stream events (progress/log/warn): a failed
    /// write (including a hung-up reader) is intentionally ignored so
    /// diagnostics never abort the command.
    fn emit(&self, event: agent_first_data::Event) {
        let _ = self.sender.send(OutputMessage::Emit(event));
    }

    /// Emit a terminal event (`result`/`error`) and resolve the process exit
    /// code through [`agent_first_data::CliEmitter::finish`]: `success_code` on
    /// a clean write, `0` on broken pipe, and `4` on any other output failure.
    fn finish(&self, event: agent_first_data::Event, success_code: u8) -> ExitCode {
        let (reply, result) = mpsc::sync_channel(1);
        if self
            .sender
            .send(OutputMessage::Finish {
                event,
                success_code,
                reply,
            })
            .is_err()
        {
            return ExitCode::from(4);
        }
        ExitCode::from(result.recv().unwrap_or(4))
    }

    /// `{kind: "result", result: ..., trace: {duration_ms}}` → stdout.
    pub fn ok<T: Serialize>(&self, result: T) -> ExitCode {
        match serde_json::to_value(&result) {
            Ok(mut result_value) => {
                redact_boundary_values(&mut result_value);
                self.finish(
                    agent_first_data::json_result(result_value)
                        .trace(self.elapsed_trace())
                        .build(),
                    0,
                )
            }
            Err(err) => self.error(
                "serialize_error",
                &format!("Failed to serialize command result: {err}"),
            ),
        }
    }

    /// `{kind: "result", result: ..., trace: ...}` → stdout.
    pub fn ok_trace<T: Serialize>(&self, result: T, trace: impl Serialize) -> ExitCode {
        let mut result_value = match serde_json::to_value(&result) {
            Ok(value) => value,
            Err(err) => {
                return self.error(
                    "serialize_error",
                    &format!("Failed to serialize command result: {err}"),
                );
            }
        };
        let mut trace_value = match serde_json::to_value(&trace) {
            Ok(value) if value.is_object() => value,
            Ok(_) => {
                return self.error(
                    "serialize_error",
                    "Command trace must serialize as an object",
                );
            }
            Err(err) => {
                return self.error(
                    "serialize_error",
                    &format!("Failed to serialize command trace: {err}"),
                );
            }
        };
        redact_boundary_values(&mut result_value);
        redact_boundary_values(&mut trace_value);
        self.finish(
            agent_first_data::json_result(result_value)
                .trace(self.with_elapsed_trace(trace_value))
                .build(),
            0,
        )
    }

    /// `{kind: "result", result: ...}` → stdout, with a caller-chosen exit code.
    ///
    /// For machine-checkable "is there drift" style results (e.g. `hatch bond
    /// sync --check`) where the outcome is a normal, well-formed result (not an
    /// error) but CI still needs a distinct non-zero exit to gate on.
    pub fn ok_with_code<T: Serialize>(&self, result: T, code: u8) -> ExitCode {
        match serde_json::to_value(&result) {
            Ok(mut result_value) => {
                redact_boundary_values(&mut result_value);
                self.finish(
                    agent_first_data::json_result(result_value)
                        .trace(self.elapsed_trace())
                        .build(),
                    code,
                )
            }
            Err(err) => self.error(
                "serialize_error",
                &format!("Failed to serialize command result: {err}"),
            ),
        }
    }

    /// `{kind: "error", error: {code, message, hint, retryable}, trace}` →
    /// the configured diagnostic destination.
    pub fn error(&self, error_code: &str, message: &str) -> ExitCode {
        self.error_hint(error_code, message, None)
    }

    /// Like [`error`] but with an actionable hint for remediation.
    pub fn error_hint(&self, error_code: &str, message: &str, hint: Option<&str>) -> ExitCode {
        let message = redact_urls_in_text(message);
        let hint = redact_urls_in_text(actionable_hint(error_code, hint));
        self.finish(
            built_event(
                agent_first_data::json_error(error_code, &message)
                    .hint(&hint)
                    .trace(self.elapsed_trace())
                    .build(),
            ),
            1,
        )
    }

    /// Output error from anyhow::Error
    pub fn error_from(&self, error_code: &str, err: &anyhow::Error) -> ExitCode {
        self.error(error_code, &err.to_string())
    }

    /// Output error from [`crate::HyphaError`] (includes hint when present).
    pub fn error_hypha(&self, err: &crate::HyphaError) -> ExitCode {
        self.error_hint(&err.code, &err.message, err.hint.as_deref())
    }

    /// Agent-First Data progress step → the configured diagnostic destination.
    /// `{kind: "progress", progress: {current, total, message, ...}, trace}`.
    pub fn progress(&self, step: u32, total: u32, message: &str, data: serde_json::Value) {
        let mut fields = match data {
            serde_json::Value::Object(map) => map,
            _ => serde_json::Map::new(),
        };
        fields.insert("current".into(), step.into());
        fields.insert("total".into(), total.into());
        fields.insert("message".into(), redact_urls_in_text(message).into());
        let mut progress = serde_json::Value::Object(fields);
        redact_boundary_values(&mut progress);
        self.emit(
            agent_first_data::json_progress(progress)
                .trace(self.elapsed_trace())
                .build(),
        );
    }

    /// Byte-level protocol-v1 download progress → the configured diagnostic destination.
    /// `{kind: "progress", progress: {event, downloaded_bytes, total_bytes}}`.
    pub fn download_progress(&self, downloaded_bytes: u64, total_bytes: Option<u64>) {
        self.emit(
            agent_first_data::json_progress(serde_json::json!({
                "event": "download_progress",
                "downloaded_bytes": downloaded_bytes,
                "total_bytes": total_bytes,
            }))
            .trace(self.elapsed_trace())
            .build(),
        );
    }

    /// Non-fatal informational log → the configured diagnostic destination.
    pub fn log(&self, code: &str, message: &str) {
        self.log_data(
            "info",
            code,
            message,
            serde_json::Value::Object(Default::default()),
        );
    }

    /// Structured non-fatal log with additional tool-defined fields.
    pub fn log_data(&self, level: &str, code: &str, message: &str, data: serde_json::Value) {
        let mut fields = match data {
            serde_json::Value::Object(map) => map,
            _ => serde_json::Map::new(),
        };
        fields.insert("level".into(), level.into());
        fields.insert("event".into(), code.into());
        fields.insert("message".into(), redact_urls_in_text(message).into());
        let mut log = serde_json::Value::Object(fields);
        redact_boundary_values(&mut log);
        self.emit(
            agent_first_data::json_log(log)
                .trace(self.elapsed_trace())
                .build(),
        );
    }

    /// Non-fatal warning → the configured diagnostic destination.
    pub fn warn(&self, code: &str, message: &str) {
        self.log_data(
            "warn",
            code,
            message,
            serde_json::Value::Object(Default::default()),
        );
    }

    /// Emit a protocol-v1 startup log event to the diagnostic destination.
    pub fn startup(&self, args: serde_json::Value) {
        let (config, config_error) = match crate::config::HyphaConfig::load() {
            Ok(cfg) => match serde_json::to_value(&cfg) {
                Ok(config) => (config, None),
                Err(err) => (
                    serde_json::Value::Null,
                    Some(serde_json::json!({
                        "code": "config_serialize_error",
                        "message": err.to_string(),
                    })),
                ),
            },
            Err(err) => (
                serde_json::Value::Null,
                Some(serde_json::json!({
                    "code": err.code,
                    "message": err.message,
                    "hint": err.hint,
                })),
            ),
        };

        let env = serde_json::json!({
            "CMN_HOME": std::env::var("CMN_HOME").ok(),
            "SYNAPSE_TOKEN_SECRET": crate::env::var("SYNAPSE_TOKEN_SECRET").ok(),
        });
        self.log_data(
            "info",
            "startup",
            "Hypha command started",
            serde_json::json!({
                "category": "startup",
                "config": config,
                "config_error": config_error,
                "args": args,
                "env": env
            }),
        );
    }
}

impl Drop for Output {
    fn drop(&mut self) {
        let _ = self.sender.send(OutputMessage::Shutdown);
        if let Ok(worker) = self.worker.get_mut()
            && let Some(worker) = worker.take()
        {
            let _ = worker.join();
        }
    }
}

fn actionable_hint<'a>(error_code: &str, hint: Option<&'a str>) -> &'a str {
    if let Some(hint) = hint.filter(|h| !h.trim().is_empty()) {
        return hint;
    }
    match error_code {
        "invalid_args" | "invalid_value" | "unknown_key" | "missing_domain" => {
            "run hypha --help or the relevant subcommand --help, then retry with valid inputs"
        }
        "invalid_uri" | "uri_error" | "cmn_invalid" => {
            "use a CMN URI in the form cmn://domain or cmn://domain/b3.hash"
        }
        "synapse_error" | "network_error" | "NETWORK_ERR" => {
            "check the synapse URL, network connectivity, and any configured auth token"
        }
        "not_found" | "missing_spore" | "not_cached" | "spore_not_found" => {
            "verify the domain/hash and run hypha sense or hypha cache list before retrying"
        }
        "spore_security_rejected" => {
            "received content targets protected control paths; inspect the spore and only relax cache.spore_reject_path_components if you accept that risk"
        }
        "skill_error" => "run hypha skill --help and retry with the suggested options",
        _ => "read the error field, check hypha --help for the expected input, and retry",
    }
}

/// Bridges [`crate::EventSink`] to an existing [`Output`].
///
/// Used in `handle_*` CLI wrappers so inner lib functions (which now take
/// `&dyn EventSink`) can still emit warnings through the normal CLI output.
pub struct OutSink<'a>(pub &'a Output);

impl crate::EventSink for OutSink<'_> {
    fn emit(&self, event: crate::HyphaEvent) {
        match event {
            crate::HyphaEvent::Progress {
                current,
                total,
                message,
            } => {
                self.0
                    .progress(current, total, &message, serde_json::Value::Null);
            }
            crate::HyphaEvent::DownloadProgress {
                downloaded_bytes,
                total_bytes,
            } => {
                self.0.download_progress(downloaded_bytes, total_bytes);
            }
            crate::HyphaEvent::Log { message } => {
                self.0.log("log", &message);
            }
            crate::HyphaEvent::Warn { message } => {
                self.0.warn("warn", &message);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{redact_boundary_values, redact_embedded_cmn_urls, redact_urls_in_text};

    #[test]
    fn diagnostic_prose_scrubs_urls_without_damaging_punctuation() {
        let secret = "diagnostic-query-secret";
        let message = format!(
            "request failed (https://user:password@example.com/api?token_secret={secret}), fallback cmn://example.com/b3.test"
        );

        let redacted = redact_urls_in_text(&message);

        assert!(!redacted.contains("password"));
        assert!(!redacted.contains(secret));
        assert!(redacted.contains("), fallback cmn://example.com/b3.test"));
    }

    #[test]
    fn embedded_cmn_url_is_scrubbed_without_renaming_the_protocol_field() {
        let secret = "embedded-cmn-secret";
        let mut document = serde_json::json!({
            "$schema": "https://cmn.dev/schemas/v1/spore.json",
            "capsule": {
                "uri": "cmn://example.com/b3.test",
                "dist": [{
                    "type": "git",
                    "url": format!(
                        "https://user:password@example.com/repo?token_secret={secret}"
                    )
                }]
            }
        });

        redact_embedded_cmn_urls(&mut document);

        let distribution = &document["capsule"]["dist"][0];
        let rendered_url = distribution["url"].as_str().unwrap();
        assert!(!rendered_url.contains("password"));
        assert!(!rendered_url.contains(secret));
        assert!(distribution.get("url").is_some());
        assert!(distribution.get("distribution_url").is_none());
        assert_eq!(document["capsule"]["uri"], "cmn://example.com/b3.test");
    }

    #[test]
    fn synapse_selector_scrubs_urls_but_preserves_domain_selectors() {
        let secret = "selector-secret";
        let mut values = serde_json::json!([
            {"synapse_selector": "synapse.example.com"},
            {
                "synapse_selector": format!(
                    "https://user:password@synapse.example.com?token_secret={secret}"
                )
            }
        ]);

        redact_boundary_values(&mut values);

        assert_eq!(values[0]["synapse_selector"], "synapse.example.com");
        let rendered_selector = values[1]["synapse_selector"].as_str().unwrap();
        assert!(!rendered_selector.contains("password"));
        assert!(!rendered_selector.contains(secret));
    }
}