haps 0.1.0

Hashtree Package System: signed packages, content-addressed distribution, social discovery
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
use anyhow::{Context, Result, ensure};
use clap::{Parser, Subcommand};
use haps::comments::{self, Comments, Scope};
use haps::{
    install::{Installation, ensure_public_key, load_keys},
    model::*,
    repository::{Repository, Snapshot},
    trust::{Trust, attest},
};
use nostr::{Event, EventBuilder, EventId, Keys, Kind, Tag, Timestamp};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
    process::ExitCode,
};

#[derive(Parser)]
#[command(version, about = "Haps — Hashtree Package System")]
struct Cli {
    #[arg(long, global = true, env = "HAPS_HOME")]
    home: Option<PathBuf>,
    /// Start a fresh configuration without the maintainer catalog or trust seed.
    #[arg(long, global = true, env = "HAPS_NO_DEFAULTS")]
    no_defaults: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Show, replace, or disable the local social-graph starting point.
    StartingPoint {
        public_key: Option<String>,
        #[arg(long, conflicts_with = "public_key")]
        clear: bool,
    },
    /// Create or use a Nostr publishing identity. No account registration.
    Identity {
        #[command(subcommand)]
        action: IdentityAction,
    },
    /// Give a publisher a local name, such as alice/package.
    Alias {
        #[command(subcommand)]
        action: AliasAction,
    },
    /// Show this machine's package target.
    Target,
    /// Sign a staged directory and build a shareable hashtree catalog locally.
    Pack {
        manifest: PathBuf,
        #[arg(long)]
        payload: PathBuf,
        #[arg(long)]
        out: PathBuf,
        #[arg(long)]
        key_file: Option<PathBuf>,
    },
    /// Inspect or explicitly execute a build recipe from a pinned Git checkout.
    Build {
        repository: String,
        #[arg(long)]
        rev: String,
        #[arg(long, default_value = "haps-build.toml")]
        recipe: String,
        /// Run the recipe with your user permissions. Builds are not sandboxed.
        #[arg(long)]
        execute: bool,
        /// Install the locally signed build after it succeeds.
        #[arg(long, requires = "execute")]
        install: bool,
    },
    /// Configure catalogs and pin their publishers' public keys.
    Source {
        #[command(subcommand)]
        action: SourceAction,
    },
    /// Search signed hashtree indexes, ranked by your social graph.
    Search {
        query: String,
    },
    /// Inspect the publisher, exact release ID, and social evidence.
    Info {
        package: String,
        #[arg(long)]
        version: Option<semver::Version>,
    },
    /// Install a package. Use publisher/name when a name is ambiguous.
    Install {
        package: String,
        #[arg(long)]
        version: Option<semver::Version>,
        #[arg(long)]
        allow_untrusted: bool,
        #[arg(long, default_value_t = 0)]
        require_attestations: usize,
    },
    /// Update an installed package while retaining its publisher and review policy.
    Update {
        package: String,
        #[arg(long)]
        allow_untrusted: bool,
    },
    /// Run an installed command without changing your system PATH.
    Run {
        package: String,
        #[arg(long)]
        command: Option<String>,
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Show an installed directory (including native app bundles).
    Path {
        package: String,
    },
    List,
    /// Activate the previous installed version.
    Rollback {
        package: String,
    },
    /// Remove from the installed set. Retain cached files for recovery.
    Remove {
        package: String,
    },
    /// Follow a publisher locally; optionally export the signed Nostr follow event.
    Follow {
        public_key: String,
        #[arg(long)]
        export: Option<PathBuf>,
    },
    /// Import verified Nostr follows, mutes, and release attestations.
    Import {
        events: PathBuf,
    },
    /// Sign a review of an exact release; no relay publishing is performed.
    Attest {
        release_id: String,
        #[arg(long)]
        note: String,
        #[arg(long)]
        revoke: bool,
        #[arg(long)]
        out: PathBuf,
    },
    /// Write a signed package comment, release comment, or reply.
    Comment {
        package: String,
        text: String,
        /// Target an exact release event ID instead of the whole package.
        #[arg(long)]
        release: Option<String>,
        #[arg(long)]
        reply_to: Option<String>,
        /// Export the NIP-22 event for sharing. No relay publishing.
        #[arg(long)]
        out: PathBuf,
    },
    /// Read imported comments, with social context and local mutes applied.
    Comments {
        package: String,
        #[arg(long)]
        release: Option<String>,
    },
}

#[derive(Subcommand)]
enum IdentityAction {
    Init,
    /// Use a public key for discovery without storing its secret key.
    Use {
        public_key: String,
    },
    Show,
}

#[derive(Subcommand)]
enum SourceAction {
    Add {
        name: String,
        location: String,
        #[arg(long)]
        author: String,
    },
    List,
    Remove {
        name: String,
    },
}

#[derive(Subcommand)]
enum AliasAction {
    Add { name: String, public_key: String },
    List,
    Remove { name: String },
}

#[derive(Default, Serialize, Deserialize)]
struct Config {
    identity: Option<String>,
    sources: BTreeMap<String, Source>,
    #[serde(skip)]
    aliases: BTreeMap<String, String>,
    #[serde(default)]
    starting_point: Option<String>,
}

fn fresh_config(no_defaults: bool) -> Result<Config> {
    let mut config = Config::default();
    if !no_defaults {
        let npub = hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB;
        let key = ensure_public_key(npub)?;
        config.starting_point = Some(key.clone());
        config.sources.insert(
            "iris".into(),
            Source {
                location: format!("htree://{npub}/haps-packages"),
                author: key,
                sequence: 0,
                event_id: String::new(),
            },
        );
    }
    Ok(config)
}

fn resolve_key(config: &Config, key: &str) -> Result<String> {
    ensure_public_key(config.aliases.get(key).map(String::as_str).unwrap_or(key))
}

fn resolve_package(config: &Config, package: &str) -> Result<String> {
    if let Some((key, name)) = package.split_once('/') {
        safe_name(name)?;
        return Ok(format!("{}/{}", resolve_key(config, key)?, name));
    }
    Ok(package.into())
}

fn publisher_label(aliases: &BTreeMap<String, String>, author: &str) -> String {
    use nostr::nips::nip19::ToBech32;
    aliases
        .iter()
        .find(|(_, key)| key.as_str() == author)
        .map(|(alias, _)| alias.clone())
        .unwrap_or_else(|| {
            nostr::PublicKey::parse(author)
                .map(|p| p.to_bech32().unwrap())
                .unwrap_or_else(|_| author.into())
        })
}

#[derive(Serialize, Deserialize)]
struct Source {
    location: String,
    author: String,
    sequence: u64,
    event_id: String,
}

struct Candidate {
    source: String,
    release: Release,
}

fn save_config(home: &Path, config: &Config) -> Result<()> {
    atomic_write(
        &home.join("config.json"),
        &serde_json::to_vec_pretty(config)?,
    )
}

fn load_trust(home: &Path, config: &Config) -> Result<Trust> {
    // An unset identity has no author relationships; explicit installs can still
    // proceed with --allow-untrusted after inspection.
    let mut trust = Trust::new(
        config
            .identity
            .clone()
            .unwrap_or_else(|| "unconfigured".into()),
    );
    let file = home.join("social.json");
    if file.exists() {
        let events: Vec<Event> = read_json(&file)?;
        ensure!(events.len() <= 10_000, "social event limit exceeded");
        for event in events {
            trust.ingest(event)?;
        }
    }
    trust.set_starting_point(config.starting_point.clone())?;
    Ok(trust)
}

fn save_trust(home: &Path, trust: &Trust) -> Result<()> {
    atomic_write(
        &home.join("social.json"),
        &serde_json::to_vec_pretty(&trust.events())?,
    )
}

fn load_comments(home: &Path) -> Result<Comments> {
    let mut comments = Comments::default();
    let path = home.join("comments.json");
    if path.exists() {
        for event in read_json::<Vec<Event>>(&path)? {
            comments.ingest(event)?;
        }
    }
    Ok(comments)
}

fn save_comments(home: &Path, comments: &Comments) -> Result<()> {
    let bytes = serde_json::to_vec_pretty(&comments.events())?;
    ensure!(
        bytes.len() <= MAX_METADATA,
        "local comments exceed metadata limit"
    );
    atomic_write(&home.join("comments.json"), &bytes)
}

fn select_discussion(
    candidates: Vec<Candidate>,
    package: &str,
    release: Option<&str>,
) -> Result<Candidate> {
    if let Some(id) = release {
        let id = EventId::from_hex(id)?;
        let filtered: Vec<_> = candidates
            .into_iter()
            .filter(|c| c.release.event.id == id)
            .collect();
        let normalized = if let Some((key, name)) = package.split_once('/') {
            format!("{}/{}", ensure_public_key(key)?, name)
        } else {
            package.into()
        };
        let candidate = filtered
            .into_iter()
            .find(|c| {
                c.release.identity() == normalized || c.release.data.package.name == normalized
            })
            .context("release does not belong to this package or is unavailable")?;
        return Ok(candidate);
    }
    // Package discussion is shared across operating systems and versions.
    let normalized = if let Some((key, name)) = package.split_once('/') {
        format!("{}/{}", ensure_public_key(key)?, name)
    } else {
        package.into()
    };
    let mut filtered: Vec<_> = candidates
        .into_iter()
        .filter(|c| c.release.identity() == normalized || c.release.data.package.name == normalized)
        .collect();
    let authors: BTreeSet<_> = filtered.iter().map(|c| c.release.author()).collect();
    ensure!(
        authors.len() == 1,
        "package missing or ambiguous; use publisher/name"
    );
    filtered.sort_by(|a, b| {
        b.release
            .data
            .package
            .version
            .cmp(&a.release.data.package.version)
    });
    Ok(filtered.remove(0))
}

fn own_keys(home: &Path, config: &Config) -> Result<Keys> {
    let keys = load_keys(&home.join("identity.key"))?;
    ensure!(
        config.identity.as_deref() == Some(keys.public_key().to_hex().as_str()),
        "active identity does not match local signing key"
    );
    Ok(keys)
}

fn check_checkpoint(source: &mut Source, snapshot: &Snapshot) -> Result<()> {
    ensure!(
        snapshot.head.sequence >= source.sequence,
        "catalog rollback detected"
    );
    ensure!(
        source.event_id.is_empty()
            || snapshot.head.sequence != source.sequence
            || snapshot.event.id.to_hex() == source.event_id,
        "catalog changed at the same sequence"
    );
    source.sequence = snapshot.head.sequence;
    source.event_id = snapshot.event.id.to_hex();
    Ok(())
}

async fn candidates(
    home: &Path,
    config: &mut Config,
    query: Option<&str>,
) -> Result<Vec<Candidate>> {
    ensure!(
        !config.sources.is_empty(),
        "no sources configured; use `haps source add`"
    );
    let mut found = Vec::new();
    let mut seen = BTreeMap::new();
    for (name, source) in &mut config.sources {
        let repo = Repository::open(&source.location, &home.join("cache"))?;
        let snapshot = repo
            .catalog(&source.author)
            .await
            .with_context(|| format!("source {name} is unavailable or invalid"))?;
        check_checkpoint(source, &snapshot)?;
        let releases = if let Some(query) = query {
            repo.search(&snapshot, query).await?
        } else {
            repo.releases(&snapshot).await?
        };
        for release in releases {
            if let Some(id) = seen.insert(release.coordinate(), release.event.id) {
                ensure!(
                    id == release.event.id,
                    "conflicting signed releases at {}",
                    release.coordinate()
                );
                continue;
            }
            found.push(Candidate {
                source: name.clone(),
                release,
            });
        }
    }
    save_config(home, config)?;
    Ok(found)
}

fn select(
    mut candidates: Vec<Candidate>,
    package: &str,
    version: Option<&semver::Version>,
    aliases: &BTreeMap<String, String>,
    trust: &Trust,
) -> Result<Candidate> {
    let package = if let Some((key, name)) = package.split_once('/') {
        format!("{}/{}", ensure_public_key(key)?, name)
    } else {
        package.to_string()
    };
    candidates.retain(|c| {
        (c.release.identity() == package || c.release.data.package.name == package)
            && c.release.data.package.target == target()
            && version.is_none_or(|v| &c.release.data.package.version == v)
            && (version.is_some() || c.release.data.package.version.pre.is_empty())
    });
    let authors: BTreeSet<_> = candidates.iter().map(|c| c.release.author()).collect();
    ensure!(
        !candidates.is_empty(),
        "no matching release for {}",
        target()
    );
    if authors.len() > 1 {
        use std::io::{IsTerminal, Write};
        let mut choices: Vec<_> = authors.into_iter().collect();
        let approvals = |author: &str| {
            candidates
                .iter()
                .filter(|c| c.release.author() == author)
                .max_by(|a, b| {
                    a.release
                        .data
                        .package
                        .version
                        .cmp(&b.release.data.package.version)
                })
                .map_or(0, |c| trust.attesters(&c.release).len())
        };
        choices.sort_by_key(|author| {
            (
                trust.muted(author),
                trust.distance(author).unwrap_or(u32::MAX),
                std::cmp::Reverse(approvals(author)),
                publisher_label(aliases, author),
            )
        });
        let options: Vec<_> = choices
            .iter()
            .map(|author| {
                format!(
                    "{}/{} ({author}; {}; {} approvals{})",
                    publisher_label(aliases, author),
                    package,
                    match trust.distance(author) {
                        Some(0) => "you".into(),
                        Some(1) => "you follow".into(),
                        Some(hops) => format!("{hops} hops away"),
                        None => "outside your graph".into(),
                    },
                    approvals(author),
                    if trust.muted(author) { "; muted" } else { "" }
                )
            })
            .collect();
        ensure!(
            std::io::stdin().is_terminal(),
            "multiple publishers use this name; choose an explicit publisher/name:\n{}",
            options.join("\n")
        );
        for (index, option) in options.iter().enumerate() {
            eprintln!("  {}. {option}", index + 1);
        }
        eprint!("Choose a publisher [1-{}]: ", choices.len());
        std::io::stderr().flush()?;
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        let index: usize = input.trim().parse().context("enter a listed number")?;
        ensure!(
            index > 0 && index <= choices.len(),
            "invalid publisher selection"
        );
        candidates.retain(|c| c.release.author() == choices[index - 1]);
    }
    candidates.sort_by(|a, b| {
        b.release
            .data
            .package
            .version
            .cmp(&a.release.data.package.version)
    });
    Ok(candidates.remove(0))
}

fn print_release(release: &Release, trust: &Trust) -> Result<()> {
    println!(
        "{}",
        serde_json::to_string_pretty(&serde_json::json!({
            "package": release.data.package, "publisher": release.author(),
            "release_id": release.event.id.to_hex(), "manifest": release.data.manifest,
            "follow_distance": trust.distance(&release.author()), "muted": trust.muted(&release.author()),
            "attesters": trust.attesters(release),
        }))?
    );
    Ok(())
}

#[tokio::main]
async fn main() -> ExitCode {
    match execute(Cli::parse()).await {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            eprintln!("haps: {error:#}");
            ExitCode::FAILURE
        }
    }
}

async fn execute(mut cli: Cli) -> Result<u8> {
    if matches!(cli.command, Command::Target) {
        println!("{}", target());
        return Ok(0);
    }
    let home = cli
        .home
        .or_else(|| dirs::data_local_dir().map(|p| p.join("haps")))
        .context("set HAPS_HOME or --home")?;
    fs::create_dir_all(&home)?;
    let home = home.canonicalize()?;
    let guard = lock(&home.join(".cli.lock"))?;
    let config_file = home.join("config.json");
    let mut config: Config = if config_file.exists() {
        read_json(&config_file)?
    } else {
        fresh_config(cli.no_defaults)?
    };
    config.aliases = haps::aliases::read()?;
    if !config_file.exists() {
        if config.starting_point.is_some() {
            let name = hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_ALIAS;
            if !config.aliases.contains_key(name) {
                haps::aliases::add(name, hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB)?;
                config.aliases = haps::aliases::read()?;
            }
            eprintln!(
                "Starting point: Sirius Business Ltd (maintainer). Use `haps starting-point` to inspect or change it; `haps starting-point --clear` disables it."
            );
        }
        save_config(&home, &config)?;
    }
    let mut trust = load_trust(&home, &config)?;
    match &mut cli.command {
        Command::Install { package, .. }
        | Command::Info { package, .. }
        | Command::Update { package, .. }
        | Command::Run { package, .. }
        | Command::Path { package }
        | Command::Rollback { package }
        | Command::Remove { package }
        | Command::Comment { package, .. }
        | Command::Comments { package, .. } => {
            *package = resolve_package(&config, package)?;
        }
        _ => {}
    }
    let installation = Installation::new(home.clone())?;
    match cli.command {
        Command::Target => unreachable!(),
        Command::StartingPoint { public_key, clear } => {
            if clear {
                config.starting_point = None;
                save_config(&home, &config)?;
                println!("Starting point disabled");
            } else if let Some(key) = public_key {
                config.starting_point = Some(resolve_key(&config, &key)?);
                save_config(&home, &config)?;
            }
            println!("{}", config.starting_point.as_deref().unwrap_or("none"));
        }
        Command::Alias { action } => match action {
            AliasAction::Add { name, public_key } => {
                let key = ensure_public_key(&public_key)?;
                haps::aliases::add(&name, &key)?;
                println!("{name}: {key}");
            }
            AliasAction::List => println!("{}", serde_json::to_string_pretty(&config.aliases)?),
            AliasAction::Remove { name } => {
                haps::aliases::remove(&name)?;
            }
        },
        Command::Identity { action } => match action {
            IdentityAction::Init => {
                let path = home.join("identity.key");
                ensure!(
                    !path.exists(),
                    "identity already exists; use `haps identity show`"
                );
                let keys = Keys::generate();
                use std::io::Write;
                let mut options = fs::OpenOptions::new();
                options.write(true).create_new(true);
                #[cfg(unix)]
                {
                    use std::os::unix::fs::OpenOptionsExt;
                    options.mode(0o600);
                }
                let mut file = options.open(path)?;
                file.write_all(keys.secret_key().to_secret_hex().as_bytes())?;
                file.sync_all()?;
                config.identity = Some(keys.public_key().to_hex());
                save_config(&home, &config)?;
                println!("{}", keys.public_key().to_hex());
            }
            IdentityAction::Use { public_key } => {
                config.identity = Some(ensure_public_key(&public_key)?);
                save_config(&home, &config)?;
                println!("{}", config.identity.unwrap());
            }
            IdentityAction::Show => {
                println!("{}", config.identity.context("no identity configured")?)
            }
        },
        Command::Pack {
            manifest,
            payload,
            out,
            key_file,
        } => {
            let spec: PackageSpec = toml::from_str(&fs::read_to_string(manifest)?)?;
            let keys = load_keys(&key_file.unwrap_or_else(|| home.join("identity.key")))?;
            let repo = Repository::local(out)?;
            let release = repo.publish(&keys, spec, &payload).await?;
            println!("{}", serde_json::to_string_pretty(&release.event)?);
        }
        Command::Build {
            repository,
            rev,
            recipe,
            execute,
            install,
        } => {
            let checkout = haps::build::Checkout::fetch(
                SourceInfo {
                    git: repository,
                    rev,
                },
                &recipe,
                &home.join("builds"),
            )?;
            println!("{}", serde_json::to_string_pretty(&checkout.recipe)?);
            if execute {
                let keys = own_keys(&home, &config)?;
                let payload = checkout.execute()?;
                let repo = Repository::local(home.join("built-packages"))?;
                let release = repo
                    .publish(&keys, checkout.recipe.package.clone(), &payload)
                    .await?;
                if install {
                    installation.install(&repo, &release).await?;
                }
                println!("Built {} {}", release.identity(), release.event.id);
            } else {
                println!(
                    "Preview only. Add --execute to run these commands with your user permissions; add --install to activate the result. Build recipes are not sandboxed."
                );
            }
        }
        Command::Source { action } => match action {
            SourceAction::Add {
                name,
                location,
                author,
            } => {
                safe_name(&name)?;
                ensure!(
                    !config.sources.contains_key(&name),
                    "source already exists; remove it explicitly before replacing its publisher pin"
                );
                let author = resolve_key(&config, &author)?;
                let location = if location.starts_with("https://")
                    || location.starts_with("http://")
                    || location.starts_with("htree://")
                {
                    location
                } else {
                    Path::new(&location)
                        .canonicalize()?
                        .to_str()
                        .context("non-UTF8 source path")?
                        .to_string()
                };
                let repo = Repository::open(&location, &home.join("cache"))?;
                let snapshot = repo.catalog(&author).await?;
                config.sources.insert(
                    name.clone(),
                    Source {
                        location,
                        author,
                        sequence: snapshot.head.sequence,
                        event_id: snapshot.event.id.to_hex(),
                    },
                );
                save_config(&home, &config)?;
                println!("Added {name}");
            }
            SourceAction::List => println!("{}", serde_json::to_string_pretty(&config.sources)?),
            SourceAction::Remove { name } => {
                ensure!(config.sources.remove(&name).is_some(), "source not found");
                save_config(&home, &config)?;
            }
        },
        Command::Search { query } => {
            let mut results = candidates(&home, &mut config, Some(&query)).await?;
            results.retain(|c| !trust.muted(&c.release.author()));
            // Unknown authors sort after known authors; fewer hops first.
            results.sort_by_key(|c| {
                (
                    trust.distance(&c.release.author()).unwrap_or(u32::MAX),
                    std::cmp::Reverse(trust.attesters(&c.release).len()),
                )
            });
            for candidate in results {
                print_release(&candidate.release, &trust)?;
            }
        }
        Command::Info { package, version } => {
            let candidate = select(
                candidates(&home, &mut config, None).await?,
                &package,
                version.as_ref(),
                &config.aliases,
                &trust,
            )?;
            print_release(&candidate.release, &trust)?;
        }
        Command::Install {
            package,
            version,
            allow_untrusted,
            require_attestations,
        } => {
            let candidate = select(
                candidates(&home, &mut config, None).await?,
                &package,
                version.as_ref(),
                &config.aliases,
                &trust,
            )?;
            let require_attestations = require_attestations.max(
                installation
                    .receipts()?
                    .get(&candidate.release.identity())
                    .map_or(0, |r| r.minimum_attestations),
            );
            trust.authorize(&candidate.release, allow_untrusted, require_attestations)?;
            let repo = Repository::open(
                &config.sources[&candidate.source].location,
                &home.join("cache"),
            )?;
            installation
                .install_with_policy(&repo, &candidate.release, require_attestations)
                .await?;
            println!(
                "Installed {} {}",
                candidate.release.identity(),
                candidate.release.data.package.version
            );
        }
        Command::Update {
            package,
            allow_untrusted,
        } => {
            let receipt = installation.receipt(&package)?;
            let current = Release::verify(receipt.current)?;
            let candidate = select(
                candidates(&home, &mut config, None).await?,
                &current.identity(),
                None,
                &config.aliases,
                &trust,
            )?;
            trust.authorize(
                &candidate.release,
                allow_untrusted,
                receipt.minimum_attestations,
            )?;
            installation
                .install_with_policy(
                    &Repository::open(
                        &config.sources[&candidate.source].location,
                        &home.join("cache"),
                    )?,
                    &candidate.release,
                    receipt.minimum_attestations,
                )
                .await?;
            println!(
                "Installed {} {}",
                candidate.release.identity(),
                candidate.release.data.package.version
            );
        }
        Command::Run {
            package,
            command,
            args,
        } => {
            #[cfg(target_os = "macos")]
            if command.is_none() {
                let release = Release::verify(installation.receipt(&package)?.current)?;
                if let Some(app) = release.data.package.app {
                    let path = installation.path(&package)?.join(safe_path(&app)?);
                    drop(guard);
                    let status = std::process::Command::new("open")
                        .arg("-a")
                        .arg(path)
                        .arg("--args")
                        .args(args)
                        .status()?;
                    return Ok(if status.success() { 0 } else { 1 });
                }
            }
            let executable = installation.command(&package, command.as_deref())?;
            drop(guard);
            let status = std::process::Command::new(executable).args(args).status()?;
            return Ok(status
                .code()
                .and_then(|c| u8::try_from(c).ok())
                .unwrap_or(1));
        }
        Command::Path { package } => println!("{}", installation.path(&package)?.display()),
        Command::List => {
            for (id, receipt) in installation.receipts()? {
                let release = Release::verify(receipt.current)?;
                println!(
                    "{id}\t{}\t{}",
                    release.data.package.version, release.event.id
                );
            }
        }
        Command::Rollback { package } => {
            installation.rollback(&package)?;
            println!("Rolled back {package}");
        }
        Command::Remove { package } => {
            installation.remove(&package)?;
            println!("Removed {package}");
        }
        Command::Follow { public_key, export } => {
            let keys = own_keys(&home, &config)?;
            let public_key = nostr::PublicKey::parse(&resolve_key(&config, &public_key)?)?;
            let old = trust
                .events()
                .into_iter()
                .find(|e| e.kind == Kind::ContactList && e.pubkey == keys.public_key());
            let mut tags: Vec<Tag> = old
                .as_ref()
                .map(|e| e.tags.iter().cloned().collect())
                .unwrap_or_default();
            if !tags.iter().any(|t| {
                t.as_slice().first().is_some_and(|v| v == "p")
                    && t.as_slice().get(1) == Some(&public_key.to_hex())
            }) {
                tags.push(Tag::public_key(public_key));
            }
            let timestamp = Timestamp::from(
                Timestamp::now().as_secs().max(
                    old.as_ref()
                        .map(|e| e.created_at.as_secs() + 1)
                        .unwrap_or(0),
                ),
            );
            let event = EventBuilder::new(
                Kind::ContactList,
                old.as_ref().map(|e| e.content.as_str()).unwrap_or(""),
            )
            .tags(tags)
            .custom_created_at(timestamp)
            .sign_with_keys(&keys)?;
            trust.ingest(event.clone())?;
            save_trust(&home, &trust)?;
            if let Some(path) = export {
                atomic_write(&path, &serde_json::to_vec_pretty(&event)?)?;
            }
            println!("Following {} locally", public_key.to_hex());
        }
        Command::Import { events } => {
            let value: serde_json::Value = read_json(&events)?;
            let events: Vec<Event> = if value.is_array() {
                serde_json::from_value(value)?
            } else {
                vec![serde_json::from_value(value)?]
            };
            ensure!(events.len() <= 10_000, "too many events");
            let count = events.len();
            let mut comments = load_comments(&home)?;
            for event in events {
                if event.kind == Kind::Comment {
                    comments.ingest(event)?;
                } else {
                    trust.ingest(event)?;
                }
            }
            save_trust(&home, &trust)?;
            save_comments(&home, &comments)?;
            println!("Imported {count} signed events");
        }
        Command::Attest {
            release_id,
            note,
            revoke,
            out,
        } => {
            let keys = own_keys(&home, &config)?;
            let mut event = attest(&keys, EventId::from_hex(&release_id)?, !revoke, note)?;
            let identifier = tag_value(&event, "d")?;
            let previous = trust
                .events()
                .into_iter()
                .filter(|e| {
                    e.pubkey == keys.public_key()
                        && e.kind == APP_KIND
                        && tag_value(e, "d").ok() == Some(identifier)
                })
                .map(|e| e.created_at.as_secs())
                .max();
            if let Some(previous) = previous
                && previous >= event.created_at.as_secs()
            {
                event = EventBuilder::new(APP_KIND, event.content.clone())
                    .tags(event.tags.clone())
                    .custom_created_at(Timestamp::from(previous + 1))
                    .sign_with_keys(&keys)?;
            }
            trust.ingest(event.clone())?;
            save_trust(&home, &trust)?;
            atomic_write(&out, &serde_json::to_vec_pretty(&event)?)?;
            println!("{}", event.id);
        }
        Command::Comment {
            package,
            text,
            release,
            reply_to,
            out,
        } => {
            let candidate = select_discussion(
                candidates(&home, &mut config, None).await?,
                &package,
                release.as_deref(),
            )?;
            let mut comments = load_comments(&home)?;
            let parent = reply_to.as_deref().map(EventId::from_hex).transpose()?;
            let parent = parent
                .map(|id| comments.get(&id).context("reply target is not imported"))
                .transpose()?;
            let root = if release.is_some() {
                candidate.release.event.clone()
            } else {
                let source = &config.sources[&candidate.source];
                let repo = Repository::open(&source.location, &home.join("cache"))?;
                let snapshot = repo.catalog(&source.author).await?;
                let cid = snapshot
                    .catalog
                    .packages
                    .get(&candidate.release.identity())
                    .context("package card is missing")?;
                let event: Event = repo.json(cid).await?;
                ensure!(
                    event.pubkey == candidate.release.event.pubkey
                        && tag_value(&event, "d")?
                            == format!("haps/package/{}", candidate.release.data.package.name),
                    "package card publisher/name mismatch"
                );
                event
            };
            let event = comments::create(
                &own_keys(&home, &config)?,
                &root,
                release.is_some(),
                parent,
                text,
            )?;
            comments.ingest(event.clone())?;
            save_comments(&home, &comments)?;
            atomic_write(&out, &serde_json::to_vec_pretty(&event)?)?;
            println!("{}", event.id);
        }
        Command::Comments { package, release } => {
            let candidate = select_discussion(
                candidates(&home, &mut config, None).await?,
                &package,
                release.as_deref(),
            )?;
            let scope = if release.is_some() {
                Scope::release(&candidate.release)
            } else {
                Scope::package(&candidate.release)
            };
            let comments = load_comments(&home)?;
            for event in comments.thread(&scope) {
                if trust.muted(&event.pubkey.to_hex()) {
                    continue;
                }
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "event": event, "follow_distance": trust.distance(&event.pubkey.to_hex()),
                    }))?
                );
            }
        }
    }
    Ok(0)
}