localharness 0.67.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
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
use crate::{collect_flags, fmt_interval, fmt_lh, fmt_ttl, load_signer, parse_guild_id, parse_proposal_id, parse_ttl, registry, resolve_member_address, take_tba_flag, tba_execute_diamond_call, truncate_words, INVITE_DEFAULT_TTL_SECS};

// ---- vote (VotingFacet: DAO governance — Rung 4 of the coordination ladder) --
//
// A guild MEMBER proposes a treasury spend, members VOTE one-member-one-vote,
// and a passed measure EXECUTES from the guild's pooled treasury (the same
// `LibGuildStorage` ledger `guild spend` debits, gated on a vote not the Admin
// role). Mirrors the `registry::*_proposal_*` / `propose`/`vote`/`execute`
// helpers; the same sponsored-write + caller-resolution shape as `guild`/`bounty`.
// A `to` arg given as a NAME resolves to its on-chain OWNER address (the
// `resolve_member_address` split), or accepts a raw `0x…` address.

pub(crate) const VOTE_USAGE: &str = "\
usage: localharness vote <propose|cast|execute|list|show|shares|weighted> ...
  vote propose [--as <me>] <guildId> <to> <amount> [--period <dur>] [memo...]
                                       a member proposes a treasury spend (opens a vote)
  vote cast    [--as <me>] [--tba <subguild>] <proposalId> <for|against>
                                       cast a one-member-one-vote ballot;
                                       --tba: a sub-guild's TBA votes in a parent guild's DAO
  vote execute [--as <me>] <proposalId>                 resolve a closed proposal (spends if passed)
  vote list    <guildId>                                list a guild's proposals + tally
  vote show    <proposalId>                             full proposal detail + tally + passing
  to: a subdomain name (resolved to its owner) or a raw 0x address   amount: $LH (e.g. 5 or 0.5)
  dur: 1h / 7d / 30d   (1h … 30d, default 7d)

  SHARE-WEIGHTED board (a cap table — runs in PARALLEL to the 1m1v vote above):
  vote shares set  [--as <me>] <guildId> <member> <count>
                                       admin sets a member's share weight (cap table)
  vote shares show <guildId> [member]  show the cap table (a member's shares, or the total)
  vote weighted propose [--as <me>] <guildId> <to> <amount> [--period <dur>] [memo...]
                                       a member opens a SHARE-WEIGHTED treasury-spend proposal
  vote weighted cast    [--as <me>] [--tba <subguild>] <proposalId> <for|against>
                                       cast a ballot weighted by YOUR shares
  vote weighted execute [--as <me>] <proposalId>        resolve a closed weighted proposal
  vote weighted list    <guildId>                       list a guild's weighted proposals + share tally
  vote weighted show    <proposalId>                    full weighted-proposal detail + share tally
  count: a whole number of shares (unitless, e.g. 60 — NOT $LH)";

/// VotingFacet's `MAX_VOTING_PERIOD` (`LibVotingStorage`): 30 days. `parse_ttl`
/// already enforces the shared 1h minimum (== `MIN_VOTING_PERIOD`), but its
/// upper bound is the invite 90d; clamp here so an out-of-range period fails
/// client-side with a clear message instead of an on-chain `BadVotingPeriod`.
pub(crate) const VOTE_MAX_PERIOD_SECS: u64 = 30 * 24 * 3600;

/// How many of a guild's proposals `vote list` scans from the head. A sane page
/// bound mirroring `BOUNTY_LIST_SCAN`; bump when a cursor walk is worth it.
pub(crate) const VOTE_LIST_SCAN: u64 = 100;

/// Parse a `for`/`against` (or `yes`/`no`) ballot argument to the on-chain
/// `support` bool. Pure + testable; case-insensitive.
pub(crate) fn parse_vote_support(raw: &str) -> Result<bool, String> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "for" | "yes" | "y" | "aye" | "support" => Ok(true),
        "against" | "no" | "n" | "nay" | "oppose" => Ok(false),
        other => Err(format!("ballot must be 'for' or 'against', got '{other}'")),
    }
}

/// Parse a `vote shares set` share count — a plain unitless WHOLE number (NOT
/// 18-dec `$LH`; shares are a cap-table integer). 0 is allowed (revokes a
/// member's weight). Pure + testable.
pub(crate) fn parse_share_count(raw: &str) -> Result<u128, String> {
    raw.trim()
        .parse::<u128>()
        .map_err(|_| format!("share count must be a whole number, got '{raw}'"))
}

/// Parse a voting `--period <dur>` to seconds, bounded to VotingFacet's
/// [MIN_VOTING_PERIOD, MAX_VOTING_PERIOD] = 1h…30d. Reuses `parse_ttl` (shared
/// 1h minimum) then clamps the upper bound to 30d (`parse_ttl`'s ceiling is the
/// invite 90d, which the facet would reject). Pure + testable.
pub(crate) fn parse_voting_period(raw: &str) -> Result<u64, String> {
    let secs = parse_ttl(raw)?;
    if secs > VOTE_MAX_PERIOD_SECS {
        return Err(format!("voting period '{raw}' exceeds the 30d maximum"));
    }
    Ok(secs)
}

/// Parsed `vote propose` arguments. `to`/`amount` are required positionals; the
/// memo is the joined positional remainder (so an unquoted multi-word memo works,
/// matching `guild spend`/`bounty post`).
pub(crate) struct ParsedVotePropose {
    guild_id: u64,
    to: String,
    amount_wei: u128,
    period_secs: u64,
    memo: String,
}

pub(crate) fn parse_vote_propose_args(rest: &[String]) -> Result<ParsedVotePropose, String> {
    let ([period], positional) = collect_flags(rest, ["--period"], VOTE_USAGE)?;
    if positional.len() < 3 {
        return Err(format!("vote propose needs <guildId> <to> <amount>\n{VOTE_USAGE}"));
    }
    let guild_id = parse_guild_id(&positional[0])?;
    let to = positional[1].clone();
    let amount_label = &positional[2];
    let amount_wei = match localharness::encoding::parse_token_amount(amount_label) {
        Some(w) if w > 0 => w,
        _ => return Err(format!("amount must be a positive $LH amount, got '{amount_label}'")),
    };
    let period_secs = match period {
        None => INVITE_DEFAULT_TTL_SECS, // 7d, within 1h…30d
        Some(raw) => parse_voting_period(&raw)?,
    };
    let memo = positional[3..].join(" ");
    Ok(ParsedVotePropose { guild_id, to, amount_wei, period_secs, memo })
}

/// `localharness vote <subcommand>` — the DAO-governance router (alias `gov`).
pub(crate) async fn vote(caller: Option<&str>, rest: &[String]) -> i32 {
    match rest.first().map(String::as_str) {
        Some("propose") => vote_propose(caller, &rest[1..]).await,
        Some("cast") => {
            // Optional `--tba <subguild-name>`: a SUB-guild's TBA casts its
            // member-guild ballot in a PARENT guild's DAO (nested divisions) —
            // the TBA executes `vote`, not the caller's own EOA.
            let (tba, positional) = match take_tba_flag(&rest[1..]) {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("{e}");
                    return 2;
                }
            };
            match (positional.first(), positional.get(1)) {
                (Some(id), Some(ballot)) => vote_cast(caller, id, ballot, tba.as_deref()).await,
                _ => {
                    eprintln!("usage: localharness vote cast [--as <me>] [--tba <subguild>] <proposalId> <for|against>");
                    2
                }
            }
        }
        Some("execute") => match rest.get(1) {
            Some(id) => vote_execute(caller, id).await,
            None => {
                eprintln!("usage: localharness vote execute [--as <me>] <proposalId>");
                2
            }
        },
        Some("list") => match rest.get(1) {
            Some(id) => vote_list(id).await,
            None => {
                eprintln!("usage: localharness vote list <guildId>");
                2
            }
        },
        Some("show") => match rest.get(1) {
            Some(id) => vote_show(id).await,
            None => {
                eprintln!("usage: localharness vote show <proposalId>");
                2
            }
        },
        // --- share-weighted board (the cap-table layer) ---
        Some("shares") => vote_shares(caller, &rest[1..]).await,
        Some("weighted") => vote_weighted(caller, &rest[1..]).await,
        _ => {
            eprintln!("{VOTE_USAGE}");
            2
        }
    }
}

/// `vote shares <set|show> …` — the cap-table sub-router (admin assigns share
/// weights; anyone reads them).
pub(crate) async fn vote_shares(caller: Option<&str>, rest: &[String]) -> i32 {
    match rest.first().map(String::as_str) {
        Some("set") => match (rest.get(1), rest.get(2), rest.get(3)) {
            (Some(g), Some(m), Some(c)) => vote_shares_set(caller, g, m, c).await,
            _ => {
                eprintln!("usage: localharness vote shares set [--as <me>] <guildId> <member> <count>");
                2
            }
        },
        Some("show") => match rest.get(1) {
            Some(g) => vote_shares_show(g, rest.get(2).map(String::as_str)).await,
            None => {
                eprintln!("usage: localharness vote shares show <guildId> [member]");
                2
            }
        },
        _ => {
            eprintln!("usage: localharness vote shares <set|show> …");
            2
        }
    }
}

/// `vote weighted <propose|cast|execute|list|show> …` — the share-weighted
/// board sub-router (the same lifecycle as the 1m1v `vote`, but tallying
/// shares).
pub(crate) async fn vote_weighted(caller: Option<&str>, rest: &[String]) -> i32 {
    match rest.first().map(String::as_str) {
        Some("propose") => vote_weighted_propose(caller, &rest[1..]).await,
        Some("cast") => {
            let (tba, positional) = match take_tba_flag(&rest[1..]) {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("{e}");
                    return 2;
                }
            };
            match (positional.first(), positional.get(1)) {
                (Some(id), Some(ballot)) => vote_weighted_cast(caller, id, ballot, tba.as_deref()).await,
                _ => {
                    eprintln!("usage: localharness vote weighted cast [--as <me>] [--tba <subguild>] <proposalId> <for|against>");
                    2
                }
            }
        }
        Some("execute") => match rest.get(1) {
            Some(id) => vote_weighted_execute(caller, id).await,
            None => {
                eprintln!("usage: localharness vote weighted execute [--as <me>] <proposalId>");
                2
            }
        },
        Some("list") => match rest.get(1) {
            Some(id) => vote_weighted_list(id).await,
            None => {
                eprintln!("usage: localharness vote weighted list <guildId>");
                2
            }
        },
        Some("show") => match rest.get(1) {
            Some(id) => vote_weighted_show(id).await,
            None => {
                eprintln!("usage: localharness vote weighted show <proposalId>");
                2
            }
        },
        _ => {
            eprintln!("usage: localharness vote weighted <propose|cast|execute|list|show> …");
            2
        }
    }
}

/// `vote propose <guildId> <to> <amount> [--period <dur>] [memo]` — a guild
/// member opens a treasury-spend proposal (`propose`). No escrow: the spend is
/// debited from the guild treasury at `execute` time if it passes. Reads the new
/// proposalId back from `proposalsOf(guildId, …)` (its last entry).
pub(crate) async fn vote_propose(caller: Option<&str>, rest: &[String]) -> i32 {
    let ParsedVotePropose { guild_id, to, amount_wei, period_secs, memo } =
        match parse_vote_propose_args(rest) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("{e}");
                return 2;
            }
        };
    let to_hex = match resolve_member_address(&to).await {
        Ok(a) => a,
        Err(e) => {
            eprintln!("vote propose: {e}");
            return 1;
        }
    };
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!(
        "proposing to spend {} from guild #{guild_id} to {to_hex} (votes for {}) …",
        fmt_lh(amount_wei),
        fmt_ttl(period_secs)
    );
    match registry::propose_sponsored(&signer, guild_id, &to_hex, amount_wei, memo.as_bytes(), period_secs)
    .await
    {
        Ok(tx) => {
            // The new proposalId is the last entry in the guild's proposal list.
            let id_note = match registry::proposals_of(guild_id, 0, VOTE_LIST_SCAN).await {
                Ok(ids) if !ids.is_empty() => Some(ids[ids.len() - 1]),
                _ => None,
            };
            match id_note {
                Some(id) => {
                    println!("✓ proposal #{id} opened — voting closes in {}", fmt_ttl(period_secs));
                    println!("  members vote:  vote cast {id} <for|against>");
                    println!("  after it closes, anyone runs:  vote execute {id}");
                }
                None => {
                    println!("✓ proposal opened — see it with `vote list {guild_id}`");
                }
            }
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote propose failed: {e}");
            1
        }
    }
}

/// `vote cast [--tba <subguild>] <proposalId> <for|against>` — cast a
/// one-member-one-vote ballot (`vote(proposalId, support)`). With `--tba
/// <subguild-name>` the SUB-guild's TBA casts the ballot (NESTED divisions: a
/// member-guild votes in a parent guild's DAO), routed through the sponsored
/// tba-execute path; without it the caller's own EOA votes. The voter must be a
/// member of the proposal's guild and not have voted already (enforced on-chain).
pub(crate) async fn vote_cast(caller: Option<&str>, id_arg: &str, ballot: &str, tba: Option<&str>) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let support = match parse_vote_support(ballot) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("vote cast: {e}");
            return 2;
        }
    };
    // NESTED path: a sub-guild's TBA casts the ballot in the parent guild's DAO.
    if let Some(subguild) = tba {
        let side = if support { "for" } else { "against" };
        return tba_execute_diamond_call(
            caller,
            subguild,
            registry::encode_vote_calldata(proposal_id, support),
            &format!("'{subguild}' voting {side} on proposal #{proposal_id}"),
        )
        .await;
    }
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    let side = if support { "for" } else { "against" };
    println!("casting a '{side}' vote on proposal #{proposal_id}");
    match registry::vote_sponsored(&signer, proposal_id, support)
        .await
    {
        Ok(tx) => {
            println!("✓ voted {side} on proposal #{proposal_id}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote cast failed: {e}");
            1
        }
    }
}

/// `vote execute <proposalId>` — resolve a closed proposal (`execute`).
/// PERMISSIONLESS: spends the treasury to the recipient if it passed, else fails
/// with no spend. Idempotent (a second execute reverts).
pub(crate) async fn vote_execute(caller: Option<&str>, id_arg: &str) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("executing proposal #{proposal_id}");
    match registry::execute_proposal_sponsored(&signer, proposal_id)
    .await
    {
        Ok(tx) => {
            // Read the resolved status back so the user sees passed-vs-failed.
            let outcome = match registry::get_proposal(proposal_id).await {
                Ok(p) => match p.status {
                    3 => " — PASSED, treasury spent".to_string(),
                    2 => " — FAILED, no spend".to_string(),
                    _ => String::new(),
                },
                Err(_) => String::new(),
            };
            println!("✓ proposal #{proposal_id} resolved{outcome}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote execute failed: {e}");
            1
        }
    }
}

/// Render one proposal row for `vote list`. Pure (no I/O) so the layout is
/// unit-testable: id, status, for/against/quorum tally, deadline (relative),
/// passing flag, memo snippet.
pub(crate) fn format_proposal_row(id: u64, p: &registry::Proposal, t: &registry::Tally, memo: &str, now: u64) -> String {
    let when = if p.deadline == 0 {
        "".to_string()
    } else if p.deadline <= now {
        "CLOSED".to_string()
    } else {
        format!("in {}", fmt_interval(p.deadline - now))
    };
    let snippet = truncate_words(memo, 60);
    format!(
        "  #{id}  [{status}]  for {f} / against {a}  quorum {q}  closes {when}  {passing}\n      {snippet}",
        status = p.status_label(),
        f = t.for_votes,
        a = t.against_votes,
        q = t.quorum,
        passing = if t.passing { "(passing)" } else { "(not passing)" },
    )
}

/// `vote list <guildId>` — list a guild's proposals + their live tally
/// (`proposalsOf` + a `getProposal`/`tallyOf` per id). Read-only, no `$LH`.
pub(crate) async fn vote_list(id_arg: &str) -> i32 {
    let guild_id = match parse_guild_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let ids = match registry::proposals_of(guild_id, 0, VOTE_LIST_SCAN).await {
        Ok(ids) => ids,
        Err(e) => {
            eprintln!("vote list failed: {e}");
            return 1;
        }
    };
    let name = registry::guild_name(guild_id).await.unwrap_or_default();
    let label = if name.is_empty() {
        format!("guild #{guild_id}")
    } else {
        format!("guild #{guild_id} '{name}'")
    };
    if ids.is_empty() {
        println!("{label} has no proposals — open one with `vote propose {guild_id} <to> <amount>`");
        return 0;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    println!("{label}{} proposal(s):", ids.len());
    for id in ids {
        let p = match registry::get_proposal(id).await {
            Ok(p) => p,
            Err(e) => {
                println!("  #{id}  (could not read: {e})");
                continue;
            }
        };
        let t = registry::tally_of(id).await.unwrap_or(registry::Tally {
            for_votes: 0,
            against_votes: 0,
            quorum: 0,
            votes_cast: 0,
            passing: false,
        });
        let memo = registry::proposal_memo_of(id).await.unwrap_or_default();
        println!("{}", format_proposal_row(id, &p, &t, &memo, now));
    }
    0
}

/// `vote show <proposalId>` — full proposal detail + tally + whether it WOULD
/// pass right now (`getProposal` + `tallyOf` + `proposalMemoOf`). Read-only.
pub(crate) async fn vote_show(id_arg: &str) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let p = match registry::get_proposal(proposal_id).await {
        Ok(p) => p,
        Err(e) => {
            eprintln!("vote show: {e}");
            return 1;
        }
    };
    let t = registry::tally_of(proposal_id).await.ok();
    let memo = registry::proposal_memo_of(proposal_id).await.unwrap_or_default();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let when = if p.deadline == 0 {
        "".to_string()
    } else if p.deadline <= now {
        "CLOSED (ready to execute)".to_string()
    } else {
        format!("in {}", fmt_interval(p.deadline - now))
    };
    println!("proposal #{proposal_id}  [{}]", p.status_label());
    println!("  guild     #{}", p.guild_id);
    println!("  proposer  {}", p.proposer);
    println!("  spend     {} -> {}", fmt_lh(p.amount), p.to);
    println!("  closes    {when}");
    match t {
        Some(t) => {
            println!(
                "  tally     for {} / against {}   quorum {}  cast {}  {}",
                t.for_votes,
                t.against_votes,
                t.quorum,
                t.votes_cast,
                if t.passing { "(passing)" } else { "(not passing)" }
            );
        }
        None => println!("  tally     for {} / against {}", p.for_votes, p.against_votes),
    }
    if !memo.is_empty() {
        println!("  memo      {memo}");
    }
    0
}

// ---- share-weighted board (WeightedVotingFacet) -------------------------
//
// A cap-table layer that COEXISTS with the 1m1v board above over the SAME
// guild treasury: an Admin assigns SHARES, a member proposes a treasury spend,
// members vote with weight == their shares, a passed measure executes via the
// shared GuildFacet `_spendCore`. Quorum = more than half of a total-shares
// snapshot; threshold = strict majority of cast shares.

/// `vote shares set <guildId> <member> <count>` — admin sets a member's share
/// weight (`setShares`). `<member>` is resolved the same way as `vote propose`'s
/// `to` (a name → its owner address, or a raw 0x). Owner/admin-gated on-chain.
pub(crate) async fn vote_shares_set(caller: Option<&str>, guild_arg: &str, member_arg: &str, count_arg: &str) -> i32 {
    let guild_id = match parse_guild_id(guild_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let shares = match parse_share_count(count_arg) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("vote shares set: {e}");
            return 2;
        }
    };
    let member_hex = match resolve_member_address(member_arg).await {
        Ok(a) => a,
        Err(e) => {
            eprintln!("vote shares set: {e}");
            return 1;
        }
    };
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("setting {member_hex} to {shares} share(s) in guild #{guild_id}");
    match registry::set_shares_sponsored(&signer, guild_id, &member_hex, shares).await {
        Ok(tx) => {
            let total = registry::total_shares_of(guild_id).await.unwrap_or(0);
            println!("{member_hex} now holds {shares} of {total} share(s) in guild #{guild_id}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote shares set failed: {e}");
            1
        }
    }
}

/// `vote shares show <guildId> [member]` — read the cap table. With a `member`,
/// show that member's shares (and the guild total); without, just the total.
pub(crate) async fn vote_shares_show(guild_arg: &str, member_arg: Option<&str>) -> i32 {
    let guild_id = match parse_guild_id(guild_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let total = match registry::total_shares_of(guild_id).await {
        Ok(t) => t,
        Err(e) => {
            eprintln!("vote shares show failed: {e}");
            return 1;
        }
    };
    println!("guild #{guild_id}{total} total share(s)");
    if let Some(member) = member_arg {
        let member_hex = match resolve_member_address(member).await {
            Ok(a) => a,
            Err(e) => {
                eprintln!("vote shares show: {e}");
                return 1;
            }
        };
        match registry::shares_of(guild_id, &member_hex).await {
            Ok(s) => println!("  {member_hex}: {s} share(s)"),
            Err(e) => {
                eprintln!("vote shares show: {e}");
                return 1;
            }
        }
    }
    0
}

/// `vote weighted propose <guildId> <to> <amount> [--period <dur>] [memo]` — a
/// member opens a SHARE-WEIGHTED treasury-spend proposal (`proposeWeighted`).
/// Reuses the SAME positional/period parsing as the 1m1v `vote propose`.
pub(crate) async fn vote_weighted_propose(caller: Option<&str>, rest: &[String]) -> i32 {
    let ParsedVotePropose { guild_id, to, amount_wei, period_secs, memo } =
        match parse_vote_propose_args(rest) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("{e}");
                return 2;
            }
        };
    let to_hex = match resolve_member_address(&to).await {
        Ok(a) => a,
        Err(e) => {
            eprintln!("vote weighted propose: {e}");
            return 1;
        }
    };
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!(
        "proposing (share-weighted) to spend {} from guild #{guild_id} to {to_hex} (votes for {}) …",
        fmt_lh(amount_wei),
        fmt_ttl(period_secs)
    );
    match registry::propose_weighted_sponsored(
        &signer,
        guild_id,
        &to_hex,
        amount_wei,
        period_secs,
        memo.as_bytes(),
    )
    .await
    {
        Ok(tx) => {
            let id_note = match registry::weighted_proposals_of(guild_id, 0, VOTE_LIST_SCAN).await {
                Ok(ids) if !ids.is_empty() => Some(ids[ids.len() - 1]),
                _ => None,
            };
            match id_note {
                Some(id) => {
                    println!("✓ weighted proposal #{id} opened — voting closes in {}", fmt_ttl(period_secs));
                    println!("  share-holders vote:  vote weighted cast {id} <for|against>");
                    println!("  after it closes, anyone runs:  vote weighted execute {id}");
                }
                None => {
                    println!("✓ weighted proposal opened — see it with `vote weighted list {guild_id}`");
                }
            }
            println!("  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote weighted propose failed: {e}");
            1
        }
    }
}

/// `vote weighted cast [--tba <subguild>] <proposalId> <for|against>` — cast a
/// ballot weighted by YOUR shares (`voteWeighted`). With `--tba <subguild>` the
/// sub-guild's TBA casts the ballot (nested divisions). The voter must be a
/// member with > 0 shares and not have voted (enforced on-chain).
pub(crate) async fn vote_weighted_cast(caller: Option<&str>, id_arg: &str, ballot: &str, tba: Option<&str>) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let support = match parse_vote_support(ballot) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("vote weighted cast: {e}");
            return 2;
        }
    };
    if let Some(subguild) = tba {
        let side = if support { "for" } else { "against" };
        return tba_execute_diamond_call(
            caller,
            subguild,
            registry::encode_vote_weighted_calldata(proposal_id, support),
            &format!("'{subguild}' weighted-voting {side} on proposal #{proposal_id}"),
        )
        .await;
    }
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    let side = if support { "for" } else { "against" };
    println!("casting a share-weighted '{side}' vote on proposal #{proposal_id}");
    match registry::vote_weighted_sponsored(&signer, proposal_id, support).await {
        Ok(tx) => {
            println!("✓ voted {side} (weighted) on proposal #{proposal_id}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote weighted cast failed: {e}");
            1
        }
    }
}

/// `vote weighted execute <proposalId>` — resolve a closed weighted proposal
/// (`executeWeighted`). PERMISSIONLESS; spends the treasury if it passed.
pub(crate) async fn vote_weighted_execute(caller: Option<&str>, id_arg: &str) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let signer = match load_signer(caller) {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    println!("executing weighted proposal #{proposal_id}");
    match registry::execute_weighted_proposal_sponsored(&signer, proposal_id).await {
        Ok(tx) => {
            let outcome = match registry::get_weighted_proposal(proposal_id).await {
                Ok(p) => match p.status {
                    3 => " — PASSED, treasury spent".to_string(),
                    2 => " — FAILED, no spend".to_string(),
                    _ => String::new(),
                },
                Err(_) => String::new(),
            };
            println!("✓ weighted proposal #{proposal_id} resolved{outcome}  tx: {tx}");
            0
        }
        Err(e) => {
            eprintln!("vote weighted execute failed: {e}");
            1
        }
    }
}

/// Render one weighted-proposal row for `vote weighted list`. Pure (no I/O) so
/// the layout is unit-testable: id, status, for/against/quorum SHARE tally,
/// deadline (relative), passing flag, memo snippet. Analogue of
/// [`format_proposal_row`] but showing shares.
pub(crate) fn format_weighted_proposal_row(
    id: u64,
    p: &registry::WeightedProposal,
    t: &registry::WeightedTally,
    memo: &str,
    now: u64,
) -> String {
    let when = if p.deadline == 0 {
        "".to_string()
    } else if p.deadline <= now {
        "CLOSED".to_string()
    } else {
        format!("in {}", fmt_interval(p.deadline - now))
    };
    let snippet = truncate_words(memo, 60);
    format!(
        "  #{id}  [{status}]  for {f} / against {a} shares  quorum {q} shares  closes {when}  {passing}\n      {snippet}",
        status = p.status_label(),
        f = t.for_shares,
        a = t.against_shares,
        q = t.quorum_shares,
        passing = if t.passing { "(passing)" } else { "(not passing)" },
    )
}

/// `vote weighted list <guildId>` — list a guild's weighted proposals + their
/// live SHARE tally. Read-only.
pub(crate) async fn vote_weighted_list(id_arg: &str) -> i32 {
    let guild_id = match parse_guild_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let ids = match registry::weighted_proposals_of(guild_id, 0, VOTE_LIST_SCAN).await {
        Ok(ids) => ids,
        Err(e) => {
            eprintln!("vote weighted list failed: {e}");
            return 1;
        }
    };
    let name = registry::guild_name(guild_id).await.unwrap_or_default();
    let label = if name.is_empty() {
        format!("guild #{guild_id}")
    } else {
        format!("guild #{guild_id} '{name}'")
    };
    if ids.is_empty() {
        println!("{label} has no weighted proposals — open one with `vote weighted propose {guild_id} <to> <amount>`");
        return 0;
    }
    let total = registry::total_shares_of(guild_id).await.unwrap_or(0);
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    println!("{label}{} weighted proposal(s)  ({total} total shares):", ids.len());
    for id in ids {
        let p = match registry::get_weighted_proposal(id).await {
            Ok(p) => p,
            Err(e) => {
                println!("  #{id}  (could not read: {e})");
                continue;
            }
        };
        let t = registry::weighted_tally_of(id).await.unwrap_or(registry::WeightedTally {
            for_shares: 0,
            against_shares: 0,
            quorum_shares: 0,
            cast_shares: 0,
            passing: false,
        });
        let memo = registry::weighted_proposal_memo_of(id).await.unwrap_or_default();
        println!("{}", format_weighted_proposal_row(id, &p, &t, &memo, now));
    }
    0
}

/// `vote weighted show <proposalId>` — full weighted-proposal detail + share
/// tally + whether it WOULD pass right now. Read-only.
pub(crate) async fn vote_weighted_show(id_arg: &str) -> i32 {
    let proposal_id = match parse_proposal_id(id_arg) {
        Ok(id) => id,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let p = match registry::get_weighted_proposal(proposal_id).await {
        Ok(p) => p,
        Err(e) => {
            eprintln!("vote weighted show: {e}");
            return 1;
        }
    };
    let t = registry::weighted_tally_of(proposal_id).await.ok();
    let memo = registry::weighted_proposal_memo_of(proposal_id).await.unwrap_or_default();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let when = if p.deadline == 0 {
        "".to_string()
    } else if p.deadline <= now {
        "CLOSED (ready to execute)".to_string()
    } else {
        format!("in {}", fmt_interval(p.deadline - now))
    };
    println!("weighted proposal #{proposal_id}  [{}]", p.status_label());
    println!("  guild     #{}", p.guild_id);
    println!("  proposer  {}", p.proposer);
    println!("  spend     {} -> {}", fmt_lh(p.amount), p.to);
    println!("  closes    {when}");
    println!("  snapshot  {} total share(s) at propose", p.snapshot_total_shares);
    match t {
        Some(t) => {
            println!(
                "  tally     for {} / against {} shares   quorum {} shares  cast {}  {}",
                t.for_shares,
                t.against_shares,
                t.quorum_shares,
                t.cast_shares,
                if t.passing { "(passing)" } else { "(not passing)" }
            );
        }
        None => println!("  tally     for {} / against {} shares", p.for_shares, p.against_shares),
    }
    if !memo.is_empty() {
        println!("  memo      {memo}");
    }
    0
}

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

    /// The ballot arg parses for/against (and common synonyms), case-insensitive;
    /// garbage is rejected. This bool is the on-chain `support` flag.
    #[test]
    fn parse_vote_support_maps_for_against() {
        for raw in ["for", "FOR", "yes", " Y ", "aye", "support"] {
            assert_eq!(parse_vote_support(raw), Ok(true), "{raw}");
        }
        for raw in ["against", "AGAINST", "no", " N ", "nay", "oppose"] {
            assert_eq!(parse_vote_support(raw), Ok(false), "{raw}");
        }
        assert!(parse_vote_support("maybe").is_err());
        assert!(parse_vote_support("").is_err());
    }

    /// The voting period clamps to VotingFacet's 1h…30d (the facet would revert
    /// `BadVotingPeriod` outside that). 1h passes; a 90d (valid for invites) is
    /// rejected for a vote; sub-1h is rejected by the shared `parse_ttl`.
    #[test]
    fn parse_voting_period_bounds_to_30d() {
        assert_eq!(parse_voting_period("1h"), Ok(3600));
        assert_eq!(parse_voting_period("7d"), Ok(7 * 86_400));
        assert_eq!(parse_voting_period("30d"), Ok(30 * 86_400));
        assert!(parse_voting_period("31d").is_err()); // over MAX_VOTING_PERIOD
        assert!(parse_voting_period("90d").is_err()); // invite-valid, vote-invalid
        assert!(parse_voting_period("30m").is_err()); // under the 1h minimum
    }

    /// `vote propose` parsing: required positionals (guildId/to/amount), an
    /// optional `--period`, and a multi-word memo from the positional remainder.
    /// `--period` may sit anywhere; default period is 7d (within 1h…30d).
    #[test]
    fn parse_vote_propose_args_positionals_and_period() {
        // guildId + to + amount + multi-word memo, no --period → default 7d.
        let p = parse_vote_propose_args(&args(&["5", "alice", "2.5", "q3", "grant"])).unwrap();
        assert_eq!(p.guild_id, 5);
        assert_eq!(p.to, "alice");
        assert_eq!(p.amount_wei, 2_500_000_000_000_000_000); // 2.5 $LH
        assert_eq!(p.period_secs, INVITE_DEFAULT_TTL_SECS);
        assert_eq!(p.memo, "q3 grant");

        // --period anywhere; memo can be empty.
        let p = parse_vote_propose_args(&args(&["3", "--period", "1h", "0x1111111111111111111111111111111111111111", "1"])).unwrap();
        assert_eq!(p.guild_id, 3);
        assert_eq!(p.to, "0x1111111111111111111111111111111111111111");
        assert_eq!(p.amount_wei, 1_000_000_000_000_000_000);
        assert_eq!(p.period_secs, 3600);
        assert_eq!(p.memo, "");

        // Missing positionals / bad amount / out-of-range period are errors.
        assert!(parse_vote_propose_args(&args(&["5", "alice"])).is_err()); // no amount
        assert!(parse_vote_propose_args(&args(&["5", "alice", "0"])).is_err()); // zero amount
        assert!(parse_vote_propose_args(&args(&["5", "alice", "1", "--period", "90d"])).is_err());
    }

    /// `format_proposal_row` shows id, status, tally, deadline (relative), the
    /// passing flag, and a flattened memo snippet.
    #[test]
    fn format_proposal_row_contains_key_fields() {
        let p = registry::Proposal {
            guild_id: 5,
            proposer: "0xproposer".into(),
            to: "0xrecipient".into(),
            amount: 2_000_000_000_000_000_000,
            deadline: 1_000 + 3600, // 1h out from `now`
            status: 0,              // active
            for_votes: 2,
            against_votes: 1,
        };
        let t = registry::Tally { for_votes: 2, against_votes: 1, quorum: 2, votes_cast: 3, passing: true };
        let row = format_proposal_row(9, &p, &t, "fund\nthe audit", 1_000);
        assert!(row.contains("#9"));
        assert!(row.contains("[active]"));
        assert!(row.contains("for 2 / against 1"));
        assert!(row.contains("quorum 2"));
        assert!(row.contains("closes in 1h"));
        assert!(row.contains("(passing)"));
        assert!(row.contains("fund the audit")); // newline flattened
    }

    /// A CLOSED (deadline past) proposal reads CLOSED + the not-passing label
    /// when the tally hasn't met quorum/majority.
    #[test]
    fn format_proposal_row_closed_and_not_passing() {
        let p = registry::Proposal {
            guild_id: 1,
            proposer: "0x0".into(),
            to: "0x0".into(),
            amount: 0,
            deadline: 100, // in the past
            status: 2,     // failed
            for_votes: 0,
            against_votes: 0,
        };
        let t = registry::Tally { for_votes: 0, against_votes: 0, quorum: 1, votes_cast: 0, passing: false };
        let row = format_proposal_row(2, &p, &t, "", 5_000);
        assert!(row.contains("[failed]"));
        assert!(row.contains("closes CLOSED"));
        assert!(row.contains("(not passing)"));
    }

    /// `parse_share_count` takes a plain whole number (NOT 18-dec $LH); 0 is
    /// allowed (revokes); decimals / negatives / garbage are rejected.
    #[test]
    fn parse_share_count_whole_numbers_only() {
        assert_eq!(parse_share_count("60"), Ok(60));
        assert_eq!(parse_share_count(" 0 "), Ok(0)); // 0 revokes; trimmed
        assert_eq!(parse_share_count("1000000"), Ok(1_000_000));
        assert!(parse_share_count("2.5").is_err()); // not 18-dec $LH
        assert!(parse_share_count("-1").is_err());
        assert!(parse_share_count("abc").is_err());
        assert!(parse_share_count("").is_err());
    }

    /// `format_weighted_proposal_row` shows id, status, the SHARE tally
    /// (for/against/quorum shares), relative deadline, the passing flag, and a
    /// flattened memo snippet.
    #[test]
    fn format_weighted_proposal_row_contains_share_fields() {
        let p = registry::WeightedProposal {
            guild_id: 5,
            proposer: "0xproposer".into(),
            to: "0xrecipient".into(),
            amount: 2_000_000_000_000_000_000,
            deadline: 1_000 + 3600, // 1h out from `now`
            status: 0,              // active
            for_shares: 60,
            against_shares: 10,
            snapshot_total_shares: 100,
        };
        let t = registry::WeightedTally {
            for_shares: 60,
            against_shares: 10,
            quorum_shares: 51,
            cast_shares: 70,
            passing: true,
        };
        let row = format_weighted_proposal_row(9, &p, &t, "fund\nthe audit", 1_000);
        assert!(row.contains("#9"));
        assert!(row.contains("[active]"));
        assert!(row.contains("for 60 / against 10 shares"));
        assert!(row.contains("quorum 51 shares"));
        assert!(row.contains("closes in 1h"));
        assert!(row.contains("(passing)"));
        assert!(row.contains("fund the audit")); // newline flattened
    }
}