vgi-forge 0.4.15

Forge-neutral adapter trait and types for VGI git namespaces: resources, rights, capabilities, bootstrap plans, events and drift.
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
//! The data an adapter is handed and hands back.
//!
//! Everything here is forge-neutral and serialisable: these are the payloads
//! of the VTC ↔ bridge jobs (`git-ns/bridge/*`), so a third-party bridge in
//! another language sees the same shapes. Types that are expected to grow are
//! `#[non_exhaustive]`; construct them with their constructors or
//! `Default` and field assignment.

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::bootstrap::MergeMethod;
use crate::event::ProtectionGap;
use crate::resource::Resource;
use crate::rights::ForgeRole;

/// Which forge software an adapter speaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ForgeKind {
    /// github.com or GitHub Enterprise Server.
    GitHub,
    /// Forgejo (and Gitea, best effort).
    Forgejo,
}

impl ForgeKind {
    /// Stable lowercase name: `github`, `forgejo`.
    pub fn as_str(self) -> &'static str {
        match self {
            ForgeKind::GitHub => "github",
            ForgeKind::Forgejo => "forgejo",
        }
    }
}

impl fmt::Display for ForgeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Whether a namespace is an organisation or a personal account (§3, §8).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum NamespaceKind {
    /// An organisation: real roles, bot repo creation.
    Organization,
    /// A personal account: the reduced capability set of §8.
    User,
}

/// A bound namespace, as the adapter needs it (§4.1). The VTC's record has
/// more (`id`, `boundBy`, `boundAt`); the adapter needs only what locates the
/// owner on the forge and the credential that acts on it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Namespace {
    /// `host/owner`, e.g. `github.com/acme`.
    pub resource: Resource,
    /// The forge's numeric id for the owner — survives renames.
    pub owner_id: Option<u64>,
    /// Organisation or personal account.
    pub kind: NamespaceKind,
    /// The automation credential's handle on this namespace (a GitHub App
    /// installation id). `None` is manual mode: the VTC governs rights and
    /// the registry, but nothing acts on the forge.
    pub installation_id: Option<u64>,
}

impl Namespace {
    /// A namespace with no owner id and no installation (manual mode).
    pub fn new(resource: Resource, kind: NamespaceKind) -> Self {
        Namespace {
            resource,
            owner_id: None,
            kind,
            installation_id: None,
        }
    }

    /// Set the owner's numeric id.
    pub fn with_owner_id(mut self, id: u64) -> Self {
        self.owner_id = Some(id);
        self
    }

    /// Set the installation id.
    pub fn with_installation(mut self, id: u64) -> Self {
        self.installation_id = Some(id);
        self
    }
}

/// How a forge makes a status check required (§5.8 table).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum RequiredCheckKind {
    /// The forge cannot require a check: repos are flagged *unprotected*.
    #[default]
    None,
    /// A repository ruleset with a required status check (GitHub).
    Ruleset,
    /// Branch protection `status_check_contexts` (Forgejo).
    BranchProtection,
}

/// How a member links their forge account (§4.4).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum LinkMethod {
    /// No automated link; the core records a binding some other way.
    #[default]
    None,
    /// OAuth device flow — works from a terminal (GitHub).
    DeviceFlow,
    /// OAuth2 authorisation code with PKCE, through a browser (Forgejo).
    AuthorizationCodePkce,
}

/// What a forge — and one namespace on it — can do (§5.8).
///
/// The core and the UX branch on this, never on [`ForgeKind`]. A personal
/// GitHub account is not a special case: it is the GitHub adapter returning
/// a smaller set here.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Capabilities {
    /// The adapter holds a credential for this namespace and can act on it
    /// at all. `false` is manual mode: every forge-side step is a human's.
    pub automation: bool,
    /// The bridge can create repositories here. Without it, `repo/create`
    /// reserves the name and returns manual steps.
    pub bot_can_create_repos: bool,
    /// The forge roles available on repositories here, lowest first.
    /// [`crate::collapse_to_ladder`] fits a requested role onto it.
    pub role_levels: Vec<ForgeRole>,
    /// How the verify-trust check is made required.
    pub required_checks: RequiredCheckKind,
    /// Whether the forge pushes change events. Without them, drift is found
    /// by a scheduled `inspect` sweep.
    pub webhooks: bool,
    /// How members link their forge accounts.
    pub account_link: LinkMethod,
    /// Whether the credential can be narrowed to one repository per job.
    pub per_repo_tokens: bool,
    /// The check runs from a namespace-level workflow pinned to a revision
    /// (a GitHub org ruleset's required workflow), so a pull request cannot
    /// change what checks it. Without it the repository's own workflow is
    /// guarded by owner review instead (§9).
    #[serde(default)]
    pub required_workflow: bool,
    /// Without a namespace workflow, a repository with a single owner gets
    /// no review requirement on its workflow (there is nobody else to
    /// review), so its owner could weaken their own check. The UI shows
    /// "solo: workflow edits not review-protected" for such repositories;
    /// [`ProtectionState::check_source_guard`] says which applies to each.
    #[serde(default)]
    pub single_owner_repos_unreviewed: bool,
    /// The bridge itself runs verify-trust against each pull request and
    /// posts the check under its own forge identity, and the protection
    /// requires the check *from that identity* (§9, "forged check runs").
    /// Nothing in the repository decides what runs, and no CI workflow can
    /// post a check that counts. The bridge becomes a merge dependency, as
    /// the registry already is.
    #[serde(default)]
    pub bridge_posted_check: bool,
}

/// What keeps a repository's check out of reach of the pull request it
/// checks (§9), as observed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[non_exhaustive]
pub enum CheckSourceGuard {
    /// Not observed (manual mode, or not inspected).
    #[default]
    Unknown,
    /// A namespace-level workflow pinned to a commit. Its shortfalls are in
    /// [`ProtectionState::other_gaps`].
    RequiredWorkflow,
    /// Workflow changes need an owner's approving review.
    OwnerReview {
        /// The accounts the managed owner rule names (ids resolved from the
        /// forge's current logins).
        reviewers: Vec<ForgeAccount>,
        /// What is wrong with it; empty when it holds.
        issues: Vec<String>,
    },
    /// No review guard: the repository's own workflow can be changed by a
    /// pull request its owner merges. Accepted for a single-owner
    /// repository.
    Unreviewed,
    /// The bridge runs the check itself and the protection accepts it only
    /// from the bridge's own forge identity
    /// ([`Capabilities::bridge_posted_check`]): nothing in the repository
    /// is on the check's path.
    BridgePosted,
}

/// A person's account on a forge. The numeric id is authoritative; the login
/// is for display and can be renamed and re-registered (§4.4).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ForgeAccount {
    /// Numeric account id.
    pub id: u64,
    /// Login at the time it was read. Display only.
    pub login: String,
}

impl ForgeAccount {
    /// An account from its id and current login.
    pub fn new(id: u64, login: impl Into<String>) -> Self {
        ForgeAccount {
            id,
            login: login.into(),
        }
    }
}

/// One person's desired role on one repository.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RoleAssignment {
    /// Who.
    pub account: ForgeAccount,
    /// The role they should hold.
    pub role: ForgeRole,
}

impl RoleAssignment {
    /// Assign `role` to `account`.
    pub fn new(account: ForgeAccount, role: ForgeRole) -> Self {
        RoleAssignment { account, role }
    }
}

/// What to do with direct collaborators the desired set does not mention.
///
/// Removing one *named* account whatever its role (a `git-ns/bridge/job`
/// 0.2 `removeAccounts` entry) needs no mode of its own: the caller lists it
/// in `desired` with [`ForgeRole::None`](crate::ForgeRole::None), which an
/// adapter converges by taking the account's direct role away — matched by
/// id, with the login read fresh from the forge — and treats as already
/// converged when the account holds none.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Unlisted {
    /// Leave them. Drift mode `report` (the default for roles, §5.6): the
    /// core reports them and a human adopts or reverts.
    #[default]
    Keep,
    /// Remove them. Drift mode `enforce`.
    Remove,
}

/// Repository visibility.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Visibility {
    /// Anyone can read.
    #[default]
    Public,
    /// Only collaborators and org members with access.
    Private,
    /// Enterprise members (GitHub Enterprise).
    Internal,
}

/// A repository to create (§5.2 `git-ns/repo/create`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RepoSpec {
    /// The full resource, `host/owner/name`.
    pub resource: Resource,
    /// Visibility.
    pub visibility: Visibility,
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The repository's owners (`git.repo.own` holders) with linked forge
    /// accounts — who may approve changes to its workflows where the forge
    /// guards them with owner review (§9).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub owners: Vec<ForgeAccount>,
}

impl RepoSpec {
    /// A public repository with no description.
    pub fn new(resource: Resource) -> Self {
        RepoSpec {
            resource,
            visibility: Visibility::Public,
            description: None,
            owners: Vec::new(),
        }
    }

    /// Add an owner.
    pub fn with_owner(mut self, owner: ForgeAccount) -> Self {
        self.owners.push(owner);
        self
    }

    /// Set the visibility.
    pub fn with_visibility(mut self, visibility: Visibility) -> Self {
        self.visibility = visibility;
        self
    }

    /// Set the description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Access an account has to a repository that is not a direct role on it —
/// what is left after its direct role was taken away (`git-ns/bridge/job`
/// 0.2 `removeAccounts`), and which the bridge reports rather than changes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IndirectAccess {
    /// The account's effective role on the repository, as the forge reports
    /// it.
    pub role: ForgeRole,
    /// Where it comes from, as far as the forge says. Empty when it does not
    /// say.
    pub via: Vec<AccessSource>,
}

impl IndirectAccess {
    /// `role`, coming from `via`.
    pub fn new(role: ForgeRole, via: Vec<AccessSource>) -> Self {
        IndirectAccess { role, via }
    }
}

impl fmt::Display for IndirectAccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`{}` access", self.role)?;
        if self.via.is_empty() {
            return f.write_str(" from something other than a direct role");
        }
        for (i, v) in self.via.iter().enumerate() {
            f.write_str(match i {
                0 => " ",
                _ if i + 1 == self.via.len() => " and ",
                _ => ", ",
            })?;
            write!(f, "{v}")?;
        }
        Ok(())
    }
}

/// Where access that is not a direct role comes from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind", content = "name")]
#[non_exhaustive]
pub enum AccessSource {
    /// Membership of a team with access to the repository (the team's
    /// name).
    Team(String),
    /// Being an owner of the organisation (its login).
    OrgOwner(String),
    /// The permission every member of the organisation has on its
    /// repositories (the organisation's login).
    OrgMember(String),
}

impl fmt::Display for AccessSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AccessSource::Team(t) => write!(f, "through team `{t}`"),
            AccessSource::OrgOwner(o) => write!(f, "as an owner of `{o}`"),
            AccessSource::OrgMember(o) => write!(f, "as a member of `{o}` (its base permission)"),
        }
    }
}

/// A collaborator as observed on the forge.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Collaborator {
    /// Who.
    pub account: ForgeAccount,
    /// Their role (the base role, for a forge with custom roles).
    pub role: ForgeRole,
    /// An invitation not yet accepted. Counts as present for drift: the
    /// adapter has done its part.
    pub pending: bool,
}

impl Collaborator {
    /// An accepted collaborator.
    pub fn new(account: ForgeAccount, role: ForgeRole) -> Self {
        Collaborator {
            account,
            role,
            pending: false,
        }
    }

    /// A pending invitation.
    pub fn invited(account: ForgeAccount, role: ForgeRole) -> Self {
        Collaborator {
            account,
            role,
            pending: true,
        }
    }
}

/// The default-branch protection that makes the check mean something, as
/// observed. Each flag is the *protective* state, so `Default` is "nothing
/// protected".
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProtectionState {
    /// The managed rule (ruleset, branch protection) exists.
    pub present: bool,
    /// It is enforced, not disabled or in evaluate-only mode.
    pub enforced: bool,
    /// It covers the default branch.
    pub covers_default_branch: bool,
    /// Changes must come through a pull request.
    pub requires_pull_request: bool,
    /// Status checks the rule requires (by context name).
    pub required_checks: Vec<String>,
    /// Force-pushes are blocked.
    pub blocks_force_push: bool,
    /// Branch deletion is blocked.
    pub blocks_deletion: bool,
    /// Actors allowed to bypass it. Must be empty (§5.3).
    pub bypass_actors: Vec<String>,
    /// Shortfalls in what keeps the check's own workflow out of the change
    /// under test's reach (a namespace required workflow, owner review),
    /// which the fields above cannot express. The adapter fills this in.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub other_gaps: Vec<ProtectionGap>,
    /// Which guard keeps the check out of the pull request's reach.
    #[serde(default)]
    pub check_source_guard: CheckSourceGuard,
    /// Paths a pull request may not change (forge glob syntax), for a forge
    /// that protects the workflow this way. Empty when not read.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub protected_paths: Vec<String>,
    /// The merge methods the repository allows, for an adapter that reads
    /// them. `None`: not observed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merge_methods: Option<Vec<MergeMethod>>,
    /// Whether the forge's CI is enabled on the repository, for an adapter
    /// that reads it. `None`: not observed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ci_enabled: Option<bool>,
}

/// A repository as observed on the forge.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RepoState {
    /// Where it is now (after any rename or transfer).
    pub resource: Resource,
    /// The forge's numeric repo id — rights are keyed on this (§9).
    pub forge_id: u64,
    /// Visibility.
    pub visibility: Visibility,
    /// Archived (read-only).
    pub archived: bool,
    /// The default branch, if the repository has any commits.
    pub default_branch: Option<String>,
    /// Direct collaborators and pending invitations.
    pub collaborators: Vec<Collaborator>,
    /// The managed default-branch protection.
    pub protection: ProtectionState,
}

impl RepoState {
    /// A state with no collaborators and no protection.
    pub fn new(resource: Resource, forge_id: u64) -> Self {
        RepoState {
            resource,
            forge_id,
            visibility: Visibility::Public,
            archived: false,
            default_branch: None,
            collaborators: Vec::new(),
            protection: ProtectionState::default(),
        }
    }
}

/// What the VTC says a repository should look like on the forge: the
/// enforced projection of §2.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Projection {
    /// The resource the VTC holds for the repository.
    pub resource: Resource,
    /// The forge id the VTC recorded, if it has one. When set, a state with
    /// the same id at a different resource is a rename, not a new repo.
    pub forge_id: Option<u64>,
    /// Desired roles for people with linked accounts. Nobody else should
    /// hold a direct role.
    pub roles: Vec<RoleAssignment>,
    /// The check that must be required on the default branch
    /// (`Verify commit trust`). `None` for a repo not yet bootstrapped.
    pub required_check: Option<String>,
    /// Whether the repository should be archived.
    pub archived: bool,
    /// The visibility the VTC recorded, if it tracks one.
    pub visibility: Option<Visibility>,
    /// The repository's owners with linked forge accounts. Where the forge
    /// guards workflows with owner review, two or more owners must all be
    /// reviewers; one owner is a solo repository with no review guard.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub owners: Vec<ForgeAccount>,
}

impl Projection {
    /// A projection with no roles and no required check.
    pub fn new(resource: Resource) -> Self {
        Projection {
            resource,
            forge_id: None,
            roles: Vec::new(),
            required_check: None,
            archived: false,
            visibility: None,
            owners: Vec::new(),
        }
    }
}

/// What happened to one person in [`crate::Forge::apply_roles`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RoleChange {
    /// Who.
    pub account: ForgeAccount,
    /// Role before.
    pub from: ForgeRole,
    /// Role requested.
    pub to: ForgeRole,
    /// What the forge did.
    pub outcome: RoleOutcome,
}

impl RoleChange {
    /// A change of `account` from `from` to `to`, with its outcome.
    pub fn new(
        account: ForgeAccount,
        from: ForgeRole,
        to: ForgeRole,
        outcome: RoleOutcome,
    ) -> Self {
        RoleChange {
            account,
            from,
            to,
            outcome,
        }
    }
}

/// Outcome of one role change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "status", content = "detail")]
#[non_exhaustive]
pub enum RoleOutcome {
    /// Applied directly.
    Applied,
    /// An invitation was sent (or updated); the person must accept.
    Invited,
    /// The forge refused; the message says why.
    Failed(String),
}

/// Result of converging a repository's roles.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ApplyReport {
    /// Every change attempted, in order.
    pub changes: Vec<RoleChange>,
    /// People already at their desired role.
    pub unchanged: Vec<ForgeAccount>,
    /// Direct collaborators not in the desired set that were left alone
    /// because the call said [`Unlisted::Keep`].
    pub kept_unlisted: Vec<Collaborator>,
}

impl ApplyReport {
    /// Whether every attempted change went through.
    pub fn is_complete(&self) -> bool {
        !self
            .changes
            .iter()
            .any(|c| matches!(c.outcome, RoleOutcome::Failed(_)))
    }
}

/// Start binding a namespace (§4.1 step 1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BindRequest {
    /// The namespace to bind, `host/owner`.
    pub namespace: Resource,
    /// Single-use nonce the caller generated and stored (with its 15-minute
    /// expiry); the forge will hand it back on the callback.
    pub state: String,
}

impl BindRequest {
    /// Bind `namespace`, with `state` as the nonce.
    pub fn new(namespace: Resource, state: impl Into<String>) -> Self {
        BindRequest {
            namespace,
            state: state.into(),
        }
    }
}

/// Where to send the admin next.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[non_exhaustive]
pub enum BindStep {
    /// Open this URL in the admin's browser (App install, OAuth consent).
    Redirect {
        /// The URL.
        url: String,
    },
}

/// The forge's redirect back to the bridge after a bind.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BindCallback {
    /// The callback's query parameters, as received.
    pub params: BTreeMap<String, String>,
    /// The nonce the caller issued for this bind, looked up from its store.
    /// The adapter compares it in constant time; the caller consumes it
    /// whatever the outcome, so it is single-use.
    pub expected_state: String,
    /// The namespace the bind was started for. An install on any other owner
    /// is refused.
    pub expected_namespace: Resource,
}

impl BindCallback {
    /// A callback for `expected_namespace`, with the issued nonce.
    pub fn new(
        params: BTreeMap<String, String>,
        expected_state: impl Into<String>,
        expected_namespace: Resource,
    ) -> Self {
        BindCallback {
            params,
            expected_state: expected_state.into(),
            expected_namespace,
        }
    }
}

/// A completed bind.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct NamespaceBinding {
    /// The namespace, with owner id, kind and installation filled in.
    pub namespace: Namespace,
    /// Permissions the adapter needs that the installation does not grant
    /// (an owner who declined an upgrade). Empty when fully capable.
    pub missing_permissions: Vec<String>,
    /// What the namespace can do, as found while binding (a probe of the
    /// forge's plan, say). Persist it: the adapter's copy is in memory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Capabilities>,
}

impl NamespaceBinding {
    /// A binding, with the permissions the installation lacks.
    pub fn new(namespace: Namespace, missing_permissions: Vec<String>) -> Self {
        NamespaceBinding {
            namespace,
            missing_permissions,
            capabilities: None,
        }
    }

    /// Attach the capabilities found while binding.
    pub fn with_capabilities(mut self, capabilities: Capabilities) -> Self {
        self.capabilities = Some(capabilities);
        self
    }
}

/// Where a member goes to link their account.
///
/// `Debug` is hand-written: `device_code` redeems the member's authorisation
/// once they approve, so it must not reach a log.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[non_exhaustive]
pub enum LinkStep {
    /// OAuth device flow: show `user_code` and `verification_uri`; the
    /// bridge polls with `device_code`.
    DeviceCode {
        /// Opaque handle the bridge polls with. Keep it server-side: it is
        /// what redeems the member's authorisation.
        device_code: String,
        /// Short code the member types in.
        user_code: String,
        /// Where they type it.
        verification_uri: String,
        /// Seconds until the codes expire.
        expires_in: u64,
        /// Minimum seconds between polls.
        interval: u64,
    },
    /// Open this URL (authorisation-code flows).
    Redirect {
        /// The URL.
        url: String,
    },
}

impl fmt::Debug for LinkStep {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LinkStep::DeviceCode {
                user_code,
                verification_uri,
                expires_in,
                interval,
                ..
            } => f
                .debug_struct("DeviceCode")
                .field("device_code", &"<redacted>")
                .field("user_code", user_code)
                .field("verification_uri", verification_uri)
                .field("expires_in", expires_in)
                .field("interval", interval)
                .finish(),
            LinkStep::Redirect { url } => f.debug_struct("Redirect").field("url", url).finish(),
        }
    }
}

/// Completion input for a link. `Debug` redacts the device code, as for
/// [`LinkStep`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[non_exhaustive]
pub enum LinkCallback {
    /// Poll a device flow to completion.
    DeviceCode {
        /// From [`LinkStep::DeviceCode`].
        device_code: String,
        /// From [`LinkStep::DeviceCode`].
        interval: u64,
        /// From [`LinkStep::DeviceCode`]; polling stops at this deadline.
        expires_in: u64,
    },
    /// An authorisation-code redirect. Build it with
    /// [`LinkCallback::redirect`].
    #[non_exhaustive]
    Redirect {
        /// Query parameters received.
        params: BTreeMap<String, String>,
        /// The member (DID) the caller started this link for, from its own
        /// session — never from the redirect. An adapter whose `state` is
        /// bound to the member checks it, so a link started by one person
        /// cannot be completed into another's session (login CSRF).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        member: Option<String>,
    },
}

impl fmt::Debug for LinkCallback {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LinkCallback::DeviceCode {
                interval,
                expires_in,
                ..
            } => f
                .debug_struct("DeviceCode")
                .field("device_code", &"<redacted>")
                .field("interval", interval)
                .field("expires_in", expires_in)
                .finish(),
            LinkCallback::Redirect { params, member } => f
                .debug_struct("Redirect")
                .field("params", &params.keys().collect::<Vec<_>>())
                .field("member", member)
                .finish(),
        }
    }
}

impl LinkCallback {
    /// An authorisation-code redirect for `member`, the DID the caller
    /// passed to [`crate::Forge::begin_account_link`].
    pub fn redirect(params: BTreeMap<String, String>, member: impl Into<String>) -> LinkCallback {
        LinkCallback::Redirect {
            params,
            member: Some(member.into()),
        }
    }

    /// The callback that polls the device flow `step` started. `None` for a
    /// step that is not a device flow.
    pub fn from_device_step(step: &LinkStep) -> Option<LinkCallback> {
        match step {
            LinkStep::DeviceCode {
                device_code,
                interval,
                expires_in,
                ..
            } => Some(LinkCallback::DeviceCode {
                device_code: device_code.clone(),
                interval: *interval,
                expires_in: *expires_in,
            }),
            LinkStep::Redirect { .. } => None,
        }
    }
}