cmn-hypha 0.3.0

CMN CLI tool — spawn, grow, release, taste, bond, and absorb spores on the Code Mycelial Network
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
use super::*;

/// Remove and recreate a directory so extraction/cloning starts from empty.
fn reset_dir(dir: &std::path::Path) -> Result<(), crate::HyphaError> {
    if dir.exists() {
        std::fs::remove_dir_all(dir).map_err(|e| {
            crate::HyphaError::new("bond_error", format!("Failed to reset content dir: {}", e))
        })?;
    }
    std::fs::create_dir_all(dir).map_err(|e| {
        crate::HyphaError::new(
            "bond_error",
            format!("Failed to recreate content dir: {}", e),
        )
    })
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub(super) struct BondIndexEntry {
    hash: String,
    dir: String,
    uri: String,
    relation: substrate::BondRelation,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct BondIndexFile {
    #[serde(default)]
    bonds: Vec<BondIndexEntry>,
}

/// Handle the `bond fetch` command — fetch all bonds from spore.core.json to .cmn/bonds/
pub async fn bond_fetch(
    dir: &std::path::Path,
    clean: bool,
    status: bool,
    sink: &dyn crate::EventSink,
) -> Result<crate::output::BondResult, crate::HyphaError> {
    bond_in_dir(dir, clean, status, sink).await
}

pub async fn handle_bond_fetch(out: &Output, clean: bool, status: bool) -> ExitCode {
    let cwd = match std::env::current_dir() {
        Ok(d) => d,
        Err(e) => {
            return out.error(
                "dir_error",
                &format!("Failed to get current directory: {}", e),
            )
        }
    };
    let sink = crate::api::OutSink(out);
    match bond_in_dir(&cwd, clean, status, &sink).await {
        Ok(output) => out.ok(serde_json::to_value(output).unwrap_or_default()),
        Err(e) => out.error_hypha(&e),
    }
}

/// Bond implementation that works in any directory — library level.
pub(super) async fn bond_in_dir(
    dir: &std::path::Path,
    clean: bool,
    status: bool,
    sink: &dyn crate::EventSink,
) -> Result<crate::output::BondResult, crate::HyphaError> {
    let spore_core_path = dir.join("spore.core.json");
    if !spore_core_path.exists() {
        return Err(crate::HyphaError::with_hint(
            "bond_error",
            "spore.core.json not found",
            "run from a spore directory",
        ));
    }

    let spore_core = std::fs::read_to_string(&spore_core_path).map_err(|e| {
        crate::HyphaError::new(
            "bond_error",
            format!("Failed to read spore.core.json: {}", e),
        )
    })?;

    let core: substrate::SporeCore = serde_json::from_str(&spore_core).map_err(|e| {
        crate::HyphaError::new(
            "bond_error",
            format!("Failed to parse spore.core.json: {}", e),
        )
    })?;

    // Collect bondable spore bonds.
    // (uri, domain, hash, relation, id)
    let mut spore_refs: Vec<(
        String,
        String,
        String,
        substrate::BondRelation,
        Option<String>,
    )> = Vec::new();
    for reference in &core.bonds {
        let uri_str = reference.uri.as_str();
        let relation = reference.relation.clone();
        if relation.is_excluded_from_bond_fetch() {
            continue;
        }
        let uri = match CmnUri::parse(uri_str) {
            Ok(u) => u,
            Err(_) => continue,
        };
        let hash = match uri.hash.clone() {
            Some(h) => h,
            None => continue,
        };
        spore_refs.push((
            uri_str.to_string(),
            uri.domain.clone(),
            hash,
            relation,
            reference.id.clone(),
        ));
    }

    let refs_dir = dir.join(".cmn/bonds");
    let refs_json_path = refs_dir.join("bonds.json");
    let index = load_refs_json(&refs_json_path);

    // --status
    if status {
        let mut statuses = Vec::new();
        for (uri_str, _domain, hash, relation, _id) in &spore_refs {
            let bonded = index.iter().any(|entry| entry.hash == *hash);
            statuses.push(crate::output::BondStatusRef {
                uri: uri_str.clone(),
                relation: relation.clone(),
                bonded: json!(bonded),
            });
        }
        for reference in &core.bonds {
            let relation = reference.relation.clone();
            if relation.is_excluded_from_bond_fetch() {
                statuses.push(crate::output::BondStatusRef {
                    uri: reference.uri.clone(),
                    relation,
                    bonded: json!("excluded"),
                });
            }
        }
        return Ok(crate::output::BondResult::Status(
            crate::output::BondStatusOutput { bonds: statuses },
        ));
    }

    // --clean
    if clean {
        let mut reserved_dirs = std::collections::HashSet::new();
        let valid_dirs: std::collections::HashSet<String> = spore_refs
            .iter()
            .map(|(_, _, h, _, id)| {
                resolve_bond_dir_name(&refs_dir, &index, &mut reserved_dirs, id.as_deref(), h)
            })
            .collect();
        let mut removed = Vec::new();
        let mut kept = Vec::new();
        for entry in &index {
            let dir_name = index_dir_name(entry);
            if !is_safe_bond_dir_name(dir_name) {
                sink.emit(crate::HyphaEvent::Warn {
                    message: format!(
                        "Skipping unsafe bond directory in bonds.json: '{}'",
                        dir_name
                    ),
                });
                continue;
            }
            if valid_dirs.contains(dir_name) {
                kept.push(entry.clone());
            } else {
                let ref_dir = refs_dir.join(dir_name);
                if ref_dir.is_dir() {
                    let _ = std::fs::remove_dir_all(&ref_dir);
                }
                removed.push(dir_name.to_string());
            }
        }
        if refs_dir.exists() {
            if let Ok(entries) = std::fs::read_dir(&refs_dir) {
                for fs_entry in entries.flatten() {
                    let path = fs_entry.path();
                    if !path.is_dir() {
                        continue;
                    }
                    let dir_name = fs_entry.file_name().to_string_lossy().to_string();
                    if !is_safe_bond_dir_name(&dir_name) {
                        continue;
                    }
                    if !valid_dirs.contains(&dir_name)
                        && std::fs::remove_dir_all(&path).is_ok()
                        && !removed.contains(&dir_name)
                    {
                        removed.push(dir_name);
                    }
                }
            }
        }
        let _ = write_refs_json(&refs_json_path, &kept);
        return Ok(crate::output::BondResult::Clean(
            crate::output::BondCleanOutput { cleaned: removed },
        ));
    }

    // Main bond
    if spore_refs.is_empty() {
        return Ok(crate::output::BondResult::Bond(crate::output::BondOutput {
            bonded: vec![],
            message: Some("No spore bonds to fetch".to_string()),
        }));
    }

    // Pre-check taste status for all refs. If any are not tasted or toxic,
    // return the full list so the caller can act on all of them at once.
    let cache = CacheDir::new()?;
    {
        let mut taste_refs = Vec::new();
        let mut any_blocked = false;
        for (uri_str, _domain, hash, relation, id) in &spore_refs {
            let domain_cache = cache.domain(_domain);
            let taste_status = match domain_cache.load_taste(hash) {
                None => {
                    any_blocked = true;
                    "not_tasted".to_string()
                }
                Some(t) if t.verdict == substrate::TasteVerdict::Toxic => {
                    any_blocked = true;
                    "toxic".to_string()
                }
                Some(t) => t.verdict.to_string(),
            };
            taste_refs.push(crate::output::BondTasteRef {
                uri: uri_str.clone(),
                relation: relation.clone(),
                id: id.clone(),
                taste: taste_status,
            });
        }
        if any_blocked {
            return Ok(crate::output::BondResult::TasteRequired(
                crate::output::BondTasteRequired { refs: taste_refs },
            ));
        }
    }

    std::fs::create_dir_all(&refs_dir).map_err(|e| {
        crate::HyphaError::new("bond_error", format!("Failed to create .cmn/bonds/: {}", e))
    })?;

    let mut bonded = Vec::new();
    let mut index_entries: Vec<BondIndexEntry> = Vec::new();
    let mut reserved_dirs = std::collections::HashSet::new();

    for (uri_str, domain, hash, relation, id) in &spore_refs {
        // Taste already verified in pre-check above; re-check for safety.
        check_taste(sink, &cache, uri_str, domain, hash)?;

        let dir_name =
            resolve_bond_dir_name(&refs_dir, &index, &mut reserved_dirs, id.as_deref(), hash);

        if !is_safe_bond_dir_name(&dir_name) {
            return Err(crate::HyphaError::new(
                "bond_error",
                format!("Unsafe bond directory name: '{}'", dir_name),
            ));
        }
        let ref_dir = refs_dir.join(&dir_name);
        let content_dir = ref_dir.join("content");

        if ref_dir.exists() {
            index_entries.push(BondIndexEntry {
                hash: hash.clone(),
                dir: dir_name,
                uri: uri_str.clone(),
                relation: relation.clone(),
                id: id.clone(),
                name: None,
            });
            bonded.push(crate::output::BondedRef {
                uri: uri_str.clone(),
                relation: relation.clone(),
                status: "already_bonded".to_string(),
            });
            continue;
        }

        let domain_cache = cache.domain(domain);

        let entry = get_cmn_entry(sink, &domain_cache, cache.cmn_ttl_ms).await?;
        let capsule = primary_capsule(&entry)?;
        let ep = &capsule.endpoints;
        let (manifest, spore) =
            fetch_verified_spore(sink, capsule, hash, &domain_cache, cache.cmn_ttl_ms).await?;

        std::fs::create_dir_all(&content_dir).map_err(|e| {
            crate::HyphaError::new(
                "bond_error",
                format!("Failed to create {}: {}", content_dir.display(), e),
            )
        })?;

        let manifest_path = ref_dir.join("spore.json");
        let manifest_pretty = serde_json::to_string_pretty(&spore).map_err(|e| {
            crate::HyphaError::new("bond_error", format!("Failed to format spore.json: {}", e))
        })?;
        std::fs::write(&manifest_path, manifest_pretty).map_err(|e| {
            crate::HyphaError::new("bond_error", format!("Failed to write spore.json: {}", e))
        })?;

        let dist_array = spore.distributions();
        if dist_array.is_empty() {
            return Err(crate::HyphaError::new(
                "manifest_failed",
                format!("No distribution options for {}", hash),
            ));
        }

        let archive_endpoints = ep
            .iter()
            .filter(|endpoint| endpoint.kind == "archive")
            .collect::<Vec<_>>();
        let mut downloaded = false;
        for dist_entry in dist_array {
            if dist_has_type(dist_entry, "archive") {
                for archive_ep in &archive_endpoints {
                    let archive_url = build_archive_url_from_endpoint(archive_ep, hash)?;

                    reset_dir(&content_dir)?;

                    match download_and_extract_to_dir(
                        &archive_url,
                        &content_dir,
                        archive_ep.format.as_deref(),
                    )
                    .await
                    {
                        Ok(_) => {
                            downloaded = true;
                            break;
                        }
                        Err(e) => {
                            sink.emit(crate::HyphaEvent::Warn {
                                message: format!("Failed to download from {}: {}", archive_url, e),
                            });
                        }
                    }
                }
                if downloaded {
                    break;
                }
            } else if let Some(git_url) = dist_git_url(dist_entry) {
                let git_ref = dist_git_ref(dist_entry);
                reset_dir(&content_dir)?;

                match clone_git_to_dir(git_url, git_ref, &content_dir, &cache).await {
                    Ok(_) => {
                        downloaded = true;
                        break;
                    }
                    Err(e) => {
                        sink.emit(crate::HyphaEvent::Warn {
                            message: format!("Failed to clone from {}: {}", git_url, e),
                        });
                    }
                }
            }
        }

        if !downloaded {
            return Err(crate::HyphaError::new(
                "fetch_failed",
                format!("Failed to download content for {}", hash),
            ));
        }

        verify_downloaded_content(sink, &ref_dir, &content_dir, &manifest, hash, &domain_cache)?;

        let name = spore.capsule.core.name.as_str();

        index_entries.push(BondIndexEntry {
            hash: hash.clone(),
            dir: dir_name,
            uri: uri_str.clone(),
            relation: relation.clone(),
            id: id.clone(),
            name: Some(name.to_string()),
        });

        bonded.push(crate::output::BondedRef {
            uri: uri_str.clone(),
            relation: relation.clone(),
            status: "bonded".to_string(),
        });
    }

    if let Err(e) = write_refs_json(&refs_json_path, &index_entries) {
        sink.emit(crate::HyphaEvent::Warn {
            message: format!("Failed to write bonds.json: {}", e),
        });
    }

    Ok(crate::output::BondResult::Bond(crate::output::BondOutput {
        bonded,
        message: None,
    }))
}

/// Load bonds.json index, returns empty vec if missing/invalid
pub(super) fn load_refs_json(path: &std::path::Path) -> Vec<BondIndexEntry> {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|s| serde_json::from_str::<BondIndexFile>(&s).ok())
        .map(|index| index.bonds)
        .unwrap_or_default()
}

fn index_dir_name(entry: &BondIndexEntry) -> &str {
    if entry.dir.is_empty() {
        &entry.hash
    } else {
        &entry.dir
    }
}

fn resolve_bond_dir_name(
    refs_dir: &std::path::Path,
    index: &[BondIndexEntry],
    reserved_dirs: &mut std::collections::HashSet<String>,
    id: Option<&str>,
    hash: &str,
) -> String {
    let preferred_dir_name = substrate::local_dir_name(id, None, hash);
    let preferred_belongs_to_hash = index
        .iter()
        .any(|entry| entry.hash == hash && index_dir_name(entry) == preferred_dir_name.as_str());
    let dir_name = if preferred_dir_name != hash
        && (reserved_dirs.contains(&preferred_dir_name)
            || index.iter().any(|entry| {
                index_dir_name(entry) == preferred_dir_name.as_str() && entry.hash != hash
            })
            || (refs_dir.join(&preferred_dir_name).exists() && !preferred_belongs_to_hash))
    {
        hash.to_string()
    } else {
        preferred_dir_name
    };
    reserved_dirs.insert(dir_name.clone());
    dir_name
}

/// Write bonds.json index
pub(super) fn write_refs_json(
    path: &std::path::Path,
    entries: &[BondIndexEntry],
) -> Result<(), crate::HyphaError> {
    let index = BondIndexFile {
        bonds: entries.to_vec(),
    };
    let pretty = serde_json::to_string_pretty(&index).map_err(|e| {
        crate::HyphaError::new(
            "bond_write_failed",
            format!("Failed to format bonds: {}", e),
        )
    })?;
    std::fs::write(path, pretty)
        .map_err(|e| crate::HyphaError::new("bond_write_failed", e.to_string()))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;

    #[test]
    fn resolve_bond_dir_name_falls_back_to_hash_when_derivation_is_empty() {
        let refs_dir = std::env::temp_dir().join("cmn-bond-dir-name-empty");
        let mut reserved_dirs = std::collections::HashSet::new();

        let dir_name =
            resolve_bond_dir_name(&refs_dir, &[], &mut reserved_dirs, Some(".."), "b3.hash");

        assert_eq!(dir_name, "b3.hash");
    }

    #[test]
    fn resolve_bond_dir_name_falls_back_to_hash_on_collision() {
        let refs_dir = std::env::temp_dir().join("cmn-bond-dir-name-collision");
        let mut reserved_dirs = std::collections::HashSet::from(["a-b".to_string()]);

        let dir_name =
            resolve_bond_dir_name(&refs_dir, &[], &mut reserved_dirs, Some("a/b"), "b3.hash");

        assert_eq!(dir_name, "b3.hash");
    }
}