vgi-bridge 0.16.0

The per-community VGI bridge: holds the community's forge credentials, takes git-ns/bridge jobs from its VTC over TSP or DIDComm, runs the forge adapters, reports results, events and drift, and posts the commit-trust check where no forge feature can be trusted to.
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
//! Forge webhooks → `git-ns/bridge/event`s.
//!
//! The adapter verifies the delivery's signature before a byte of it is
//! parsed ([`vgi_forge::Forge::parse_event`]); a delivery that fails is
//! refused with 401 and never reported (spec: MUST NOT report an event from
//! an unverified webhook). A verified event is only ever a prompt: the
//! bridge inspects the repository it names and reports what the forge shows
//! *now*, with the complete drift — so a replayed or reordered delivery
//! costs a read, not a wrong state at the VTC. Repeats are dropped by
//! delivery id as well.
//!
//! Raw payloads are never forwarded (spec: they carry far more than any
//! event needs): only the forge-neutral fields below leave the bridge.

use std::sync::Arc;

use http::{HeaderMap, StatusCode};
use serde_json::json;
use vgi_forge::{ForgeEventKind, HookDecision, InstallationChange, Resource};

use crate::bridge::{Bridge, now};
use crate::jobs::{self, Ctx};
use crate::mapping::Report;
use crate::store::{BranchLedger, NamespaceRecord, NamespaceState, RepoRecord, Table, repo_key};

/// The namespace-level repository the GitHub adapter keeps for the
/// required workflow. Part of the binding, never reported as unmanaged
/// (spec).
const NAMESPACE_REPOS: [&str; 1] = [".vgi"];

/// The adapter a delivery is for: the GitHub App the route names
/// (`/github/<host>/<owner>/webhook`), or the Forgejo host's. Its own
/// webhook secret must verify the delivery.
fn webhook_adapter(
    bridge: &Bridge,
    host: &str,
    owner: Option<&str>,
) -> Option<crate::registry::Adapter> {
    match owner {
        Some(o) => bridge.adapters.get_github(host, o),
        None => bridge.adapters.get(host),
    }
}

/// Whose deliveries these are. A GitHub App's webhook secret is set by the
/// organisation that owns the App, so a delivery it verifies speaks for that
/// organisation **only**: every namespace, repository and installation it
/// may touch is its owner's. A Forgejo bot's covers its host.
#[derive(Debug, Clone)]
pub(crate) struct Scope {
    host: String,
    /// The GitHub App's owner (lowercase); `None` for Forgejo.
    owner: Option<String>,
}

impl Scope {
    /// Whether `r` lies in this scope.
    pub(crate) fn covers(&self, r: &Resource) -> bool {
        r.host() == self.host
            && self
                .owner
                .as_ref()
                .is_none_or(|o| r.owner().eq_ignore_ascii_case(o))
    }

    /// Whether a delivery about repository `repo` (forge id `id`) may be
    /// acted on: `repo` is in scope, and the repository the bridge records
    /// under that id (if any) is too — a delivery cannot name another
    /// owner's repository by its id. With `need_record`, the id must be one
    /// the bridge manages.
    pub(crate) fn admits_repo(
        &self,
        bridge: &Bridge,
        repo: &Resource,
        id: u64,
        need_record: bool,
    ) -> bool {
        if !self.covers(repo) {
            return false;
        }
        match repo_record(bridge, &self.host, id) {
            Some(rec) => {
                self.covers(&rec.resource)
                    && namespace_record(bridge, &rec.namespace)
                        .is_some_and(|n| self.covers(&n.resource))
            }
            None => !need_record,
        }
    }

    /// Whether every resource an event names lies in scope. A transfer may
    /// name the other side's owner (it moved in or out), but one of its
    /// sides must be this owner's.
    fn admits(&self, kind: &ForgeEventKind) -> bool {
        match kind {
            ForgeEventKind::RepoCreated { repo, .. }
            | ForgeEventKind::RepoDeleted { repo, .. }
            | ForgeEventKind::RepoArchived { repo, .. }
            | ForgeEventKind::RepoVisibilityChanged { repo, .. }
            | ForgeEventKind::CollaboratorChanged { repo, .. }
            | ForgeEventKind::PullRequestOpened { repo, .. } => self.covers(repo),
            ForgeEventKind::RepoRenamed { from, to, .. } => self.covers(from) && self.covers(to),
            ForgeEventKind::RepoTransferred {
                from_namespace, to, ..
            } => self.covers(to) || from_namespace.as_ref().is_some_and(|f| self.covers(f)),
            ForgeEventKind::OrgMembershipChanged { namespace, .. }
            | ForgeEventKind::TeamMembershipChanged { namespace, .. }
            | ForgeEventKind::InstallationChanged { namespace, .. } => self.covers(namespace),
            ForgeEventKind::ProtectionChanged {
                repo, namespace, ..
            } => self.covers(namespace) && repo.as_ref().is_none_or(|r| self.covers(r)),
            _ => false,
        }
    }
}

fn repo_record(bridge: &Bridge, host: &str, id: u64) -> Option<RepoRecord> {
    bridge
        .store
        .get::<RepoRecord>(Table::Repos, &repo_key(host, id))
        .ok()
        .flatten()
}

fn namespace_record(bridge: &Bridge, id: &str) -> Option<NamespaceRecord> {
    bridge
        .store
        .get::<NamespaceRecord>(Table::Namespaces, id)
        .ok()
        .flatten()
}

/// Handle a webhook for `host` (and, on GitHub, the App `owner` owns).
/// Returns the status to answer the forge with.
pub(crate) async fn on_webhook(
    bridge: &Arc<Bridge>,
    host: &str,
    owner: Option<&str>,
    headers: &HeaderMap,
    body: &[u8],
) -> StatusCode {
    let Some(adapter) = webhook_adapter(bridge, host, owner) else {
        return StatusCode::NOT_FOUND;
    };
    let scope = Scope {
        host: host.to_string(),
        owner: owner.map(str::to_ascii_lowercase),
    };

    #[cfg(feature = "forge-github")]
    if let Some(g) = adapter.github() {
        // A push: the Dependabot re-sign's provenance ledger.
        match g.parse_push(headers, body) {
            Ok(Some(push)) => {
                // The provenance ledger the re-sign trusts: only for a
                // repository this owner's namespace manages.
                if !scope.admits_repo(bridge, &push.repo, push.repo_id, true) {
                    tracing::warn!(%host, owner = ?scope.owner, repo = %push.repo, id = push.repo_id,
                        "dropping a push for a repository outside the App's organisation");
                    return StatusCode::NO_CONTENT;
                }
                return crate::resign::on_push(bridge, host, push);
            }
            Ok(None) => {}
            Err(e) => {
                tracing::warn!(%host, error = %e, "refused a webhook");
                return StatusCode::UNAUTHORIZED;
            }
        }
        // A pull request opened or reopened (event 0.4): reported to the
        // VTC beside the bridge-posted check the same delivery may prompt,
        // never instead of it. Deduplicated under its own key, so the
        // check's handling of the delivery is unaffected.
        if let Ok(Some(ev)) = adapter.forge().parse_event(headers, body)
            && matches!(ev.kind, ForgeEventKind::PullRequestOpened { .. })
        {
            pull_request_opened(bridge, &scope, ev.delivery_id.as_deref(), ev.kind);
        }
        match g.parse_check_trigger(headers, body) {
            Ok(mut triggers) if !triggers.is_empty() => {
                let before = triggers.len();
                triggers.retain(|t| scope.admits_repo(bridge, &t.repo, t.repo_id, false));
                if triggers.len() != before {
                    tracing::warn!(%host, owner = ?scope.owner,
                        "dropping check triggers for repositories outside the App's organisation");
                }
                if triggers.is_empty() {
                    return StatusCode::NO_CONTENT;
                }
                let key = triggers[0]
                    .delivery_id
                    .as_deref()
                    .map(|d| format!("{host}#{d}"));
                if let Some(k) = &key
                    && already_seen(bridge, k)
                {
                    return StatusCode::OK;
                }
                // A Dependabot pull request may be re-signed; that runs on
                // its own, beside the check.
                crate::resign::on_pull_request_triggers(bridge, &triggers);
                // Recorded as handled only once every check it called for
                // was posted (or deliberately skipped): a delivery whose
                // check failed to post is processed again when GitHub
                // redelivers it.
                crate::checks::spawn(bridge, triggers, move |b| {
                    if let Some(k) = key {
                        let _ = b.store.put(Table::Deliveries, &k, &now());
                    }
                });
                return StatusCode::ACCEPTED;
            }
            Ok(_) => {}
            Err(e) => {
                tracing::warn!(%host, error = %e, "refused a webhook");
                return StatusCode::UNAUTHORIZED;
            }
        }
    }

    let event = match adapter.forge().parse_event(headers, body) {
        Ok(Some(e)) => e,
        Ok(None) => return StatusCode::NO_CONTENT,
        Err(e) => {
            tracing::warn!(%host, error = %e, "refused a webhook");
            return StatusCode::UNAUTHORIZED;
        }
    };
    if !scope.admits(&event.kind) {
        tracing::warn!(%host, owner = ?scope.owner, event = ?event.kind,
            "dropping an event that names a namespace or repository outside the App's organisation");
        return StatusCode::NO_CONTENT;
    }
    if let ForgeEventKind::PullRequestOpened { .. } = &event.kind {
        pull_request_opened(bridge, &scope, event.delivery_id.as_deref(), event.kind);
        return StatusCode::ACCEPTED;
    }
    if seen(bridge, host, event.delivery_id.as_deref()) {
        return StatusCode::OK;
    }
    let event = match adapter.hooks().on_event(&event) {
        HookDecision::Modify(e) => e,
        HookDecision::Abort(why) => {
            tracing::info!(%why, "an adapter hook dropped an event");
            return StatusCode::NO_CONTENT;
        }
        _ => event,
    };
    let me = Arc::clone(bridge);
    // Answer the forge now; the inspection that follows may take a while.
    tokio::spawn(async move { handle(&me, &scope, event.kind).await });
    StatusCode::ACCEPTED
}

/// Whether delivery `key` was already handled.
fn already_seen(bridge: &Bridge, key: &str) -> bool {
    matches!(bridge.store.get::<i64>(Table::Deliveries, key), Ok(Some(_)))
}

/// Record a delivery id; `true` if it was already handled.
fn seen(bridge: &Bridge, host: &str, delivery: Option<&str>) -> bool {
    let Some(d) = delivery else { return false };
    !bridge
        .store
        .put_new(Table::Deliveries, &format!("{host}#{d}"), &now())
        .unwrap_or(true)
}

/// The bound namespace containing `r`, if it lies in `scope`.
fn namespace_in(bridge: &Bridge, scope: &Scope, r: &Resource) -> Option<NamespaceRecord> {
    if !scope.covers(r) {
        return None;
    }
    bridge
        .store
        .list::<NamespaceRecord>(Table::Namespaces)
        .ok()?
        .into_iter()
        .map(|(_, n)| n)
        .find(|n| {
            n.state == NamespaceState::Bound && n.resource.contains(r) && scope.covers(&n.resource)
        })
}

/// The repository the bridge records under forge id `id` in namespace
/// `ns` — never one of another namespace, whatever id a delivery names.
fn repo_in(bridge: &Bridge, ns: &NamespaceRecord, id: u64) -> Option<RepoRecord> {
    repo_record(bridge, ns.resource.host(), id).filter(|r| r.namespace == ns.id)
}

/// Whether some other namespace than `ns` records or manages forge id `id`.
fn claimed_elsewhere(bridge: &Bridge, ns: &NamespaceRecord, id: u64) -> bool {
    let host = ns.resource.host();
    if repo_record(bridge, host, id).is_some_and(|r| r.namespace != ns.id) {
        return true;
    }
    bridge
        .store
        .list::<NamespaceRecord>(Table::Namespaces)
        .unwrap_or_default()
        .into_iter()
        .any(|(_, n)| n.id != ns.id && n.resource.host() == host && n.managed.contains(&id))
}

/// [`detach`] forge id `id` from `ns` — refused (and logged) when another
/// namespace records or manages it: a delivery for one namespace never
/// detaches another's repository.
fn detach_from(bridge: &Bridge, ns: &NamespaceRecord, id: u64) -> bool {
    if claimed_elsewhere(bridge, ns, id) {
        tracing::warn!(namespace = %ns.id, forge_id = id,
            "not detaching a repository another namespace governs");
        return false;
    }
    detach(bridge, ns.resource.host(), id);
    true
}

/// A repository came into namespace `to_ns` that another organisation's
/// namespace still records (that organisation's App sent no transfer, or
/// has not yet). One organisation's webhook never changes another's
/// state on its own word: the move is confirmed with GitHub first — where
/// `to_ns`'s installation sees repository `forge_id` now — and only then is
/// the old side detached and told (`repoTransferred`).
async fn confirm_transfer_in(bridge: &Bridge, to_ns: &NamespaceRecord, forge_id: u64) {
    let Some(rec) = repo_record(bridge, to_ns.resource.host(), forge_id) else {
        return;
    };
    if rec.namespace == to_ns.id {
        return;
    }
    let Some(old_ns) = namespace_record(bridge, &rec.namespace) else {
        return;
    };
    #[cfg(feature = "forge-github")]
    {
        let Some(g) = bridge
            .adapters
            .for_resource(&to_ns.resource)
            .and_then(|a| a.github().cloned())
        else {
            return;
        };
        match g.repository_by_id(&to_ns.resource, forge_id).await {
            Ok(Some(now)) if to_ns.resource.contains(&now) && !old_ns.resource.contains(&now) => {
                tracing::info!(from = %rec.resource, to = %now,
                    "GitHub confirms a repository moved to another organisation; detaching it there");
                transferred_out(bridge, &old_ns, &rec.resource, &now, forge_id).await;
            }
            Ok(other) => tracing::warn!(forge_id, now = ?other,
                "a transfer in that GitHub does not confirm; the other organisation's record is left alone"),
            Err(e) => tracing::warn!(forge_id, error = %e,
                "could not confirm a transfer with GitHub; the other organisation's record is left alone"),
        }
    }
    #[cfg(not(feature = "forge-github"))]
    let _ = old_ns;
}

/// Stop governing repository `forge_id` on `host`: its record, its place in
/// every managed set (the store's and the adapter's, which would otherwise
/// write it back), and the Dependabot provenance ledgers kept for it.
/// Nothing of it is carried anywhere: a repository that comes back — into
/// this namespace or another one this bridge serves — starts unmanaged
/// (event 0.2: rights never follow a repository out of its namespace).
pub(crate) fn detach(bridge: &Bridge, host: &str, forge_id: u64) {
    let _ = bridge.store.delete(Table::Repos, &repo_key(host, forge_id));
    let namespaces = bridge
        .store
        .list::<NamespaceRecord>(Table::Namespaces)
        .unwrap_or_default();
    for (id, ns) in namespaces {
        if ns.resource.host() != host || !ns.managed.contains(&forge_id) {
            continue;
        }
        let managed = bridge
            .store
            .update::<NamespaceRecord, _>(Table::Namespaces, &id, |n| {
                let Some(mut n) = n else {
                    return Ok((None, None));
                };
                n.managed.remove(&forge_id);
                let m = n.managed.clone();
                Ok((Some(n), Some(m)))
            });
        #[cfg(feature = "forge-github")]
        if let (Ok(Some(m)), Some(g)) = (
            managed,
            bridge
                .adapters
                .for_resource(&ns.resource)
                .and_then(|a| a.github().cloned()),
        ) {
            g.set_managed_repositories(&ns.resource, m);
        }
        #[cfg(not(feature = "forge-github"))]
        let _ = managed;
    }
    let prefix = format!("{host}#{forge_id}#");
    if let Ok(ledgers) = bridge.store.list::<BranchLedger>(Table::Branches) {
        for (key, _) in ledgers.into_iter().filter(|(k, _)| k.starts_with(&prefix)) {
            let _ = bridge.store.delete(Table::Branches, &key);
        }
    }
}

/// Detach every repository namespace `ns_id` records at `resource` under a
/// forge id other than `forge_id`: the name was reused (event 0.2 — the
/// governed repository was deleted or moved without an event, and the
/// newcomer inherits nothing). Returns whether there was one.
pub(crate) fn detach_reused_name(
    bridge: &Bridge,
    ns_id: &str,
    resource: &Resource,
    forge_id: u64,
) -> bool {
    let stale: Vec<RepoRecord> = bridge
        .store
        .list::<RepoRecord>(Table::Repos)
        .unwrap_or_default()
        .into_iter()
        .map(|(_, r)| r)
        .filter(|r| r.namespace == ns_id && r.resource == *resource && r.forge_id != forge_id)
        .collect();
    for r in &stale {
        tracing::warn!(
            %resource, old = r.forge_id, new = forge_id,
            "a new repository took a governed name; the old one is no longer managed"
        );
        detach(bridge, resource.host(), r.forge_id);
    }
    !stale.is_empty()
}

/// Report `resource` (forge id `forge_id`) to namespace `ns` as a repository
/// the VTC did not create or adopt — unless it is the bridge's own
/// namespace-level repository, or one `ns` manages (another organisation's
/// record of it does not stop the report). A repository this
/// namespace records at the same name under another forge id is detached
/// first (name reuse).
pub(crate) async fn report_unmanaged(
    bridge: &Bridge,
    ns: &NamespaceRecord,
    resource: &Resource,
    forge_id: u64,
) {
    if NAMESPACE_REPOS.contains(&resource.repo_name().unwrap_or_default())
        || repo_in(bridge, ns, forge_id).is_some()
    {
        return;
    }
    detach_reused_name(bridge, &ns.id, resource, forge_id);
    let ev = json!({ "type": "repoCreatedUnmanaged", "forgeId": forge_id.to_string(), "resource": resource.as_str() });
    report(bridge, &ns.id, ev).await;
}

/// A repository left namespace `from_ns` (from `from` to `to`): detach it
/// and report `repoTransferred` there. When `to` lies in another namespace
/// this bridge serves, it arrives there unmanaged and is reported so —
/// its state here is never carried across.
pub(crate) async fn transferred_out(
    bridge: &Bridge,
    from_ns: &NamespaceRecord,
    from: &Resource,
    to: &Resource,
    forge_id: u64,
) {
    if !detach_from(bridge, from_ns, forge_id) {
        return;
    }
    if NAMESPACE_REPOS.contains(&from.repo_name().unwrap_or_default()) {
        return;
    }
    let ev = json!({ "type": "repoTransferred", "forgeId": forge_id.to_string(), "from": from.as_str(), "to": to.as_str() });
    report(bridge, &from_ns.id, ev).await;
    // The receiving side, only when it is this same owner's (a jobs-path
    // transfer between its own namespaces); another owner's App reports its
    // own side.
    let same_owner = Scope {
        host: from_ns.resource.host().to_string(),
        owner: Some(from_ns.resource.owner().to_ascii_lowercase()),
    };
    if let Some(to_ns) = namespace_in(bridge, &same_owner, to)
        && to_ns.id != from_ns.id
    {
        report_unmanaged(bridge, &to_ns, to, forge_id).await;
    }
}

async fn inspect_in(bridge: &Bridge, ns: &NamespaceRecord, repo: &Resource) {
    let Ok(ctx) = Ctx::load(bridge, &ns.id) else {
        return;
    };
    let lock = bridge.ns_lock(&ns.id);
    let _g = lock.lock().await;
    if let Err(e) = jobs::inspect_repo(bridge, &ctx, repo, true, None).await {
        tracing::warn!(%repo, error = %e, "could not inspect after a webhook");
    }
}

/// A pull request opened or reopened on a repository the namespace manages
/// → `pullRequestOpened` (`git-ns/bridge/event` 0.4), queued for the VTC to
/// decide on its pull-request policy. Returns whether one was queued.
///
/// Nothing is reported unless the VTC takes event 0.4
/// ([`crate::config::EventVersion::reports_pull_requests`]): below it there
/// is no pull-request gate, and no pull request is ever sent under an older
/// type. Nor for a repository the namespace does not manage (the VTC
/// governs no other), one of the binding's own (`.vgi`), or one outside the
/// delivering App's organisation. Only who and where leave the bridge —
/// never the title, body, branches or diff. Each delivery is reported once
/// (by delivery id, under a key of its own: the same delivery's check is
/// recorded separately).
pub(crate) fn pull_request_opened(
    bridge: &Arc<Bridge>,
    scope: &Scope,
    delivery_id: Option<&str>,
    kind: ForgeEventKind,
) -> bool {
    let ForgeEventKind::PullRequestOpened {
        repo,
        forge_id,
        number,
        reopened,
        author,
        actor,
        draft,
        from_fork,
    } = kind
    else {
        return false;
    };
    if !bridge.cfg.event_version.reports_pull_requests() {
        tracing::debug!(%repo, number,
            "not reporting a pull request: event_version is below 0.4 (no pull-request gate)");
        return false;
    }
    if !scope.admits_repo(bridge, &repo, forge_id, true) {
        tracing::debug!(%repo, forge_id, "not reporting a pull request on an unmanaged repository");
        return false;
    }
    let Some(ns) = namespace_in(bridge, scope, &repo) else {
        return false;
    };
    if NAMESPACE_REPOS.contains(&repo.repo_name().unwrap_or_default())
        || !ns.managed.contains(&forge_id)
        || repo_in(bridge, &ns, forge_id).is_none()
    {
        return false;
    }
    if let Some(d) = delivery_id {
        let key = format!("{}#{d}#pullRequestOpened", repo.host());
        if !bridge
            .store
            .put_new(Table::Deliveries, &key, &now())
            .unwrap_or(false)
        {
            return false;
        }
    }
    let host = repo.host();
    let mut ev = json!({
        "type": "pullRequestOpened",
        "forgeId": forge_id.to_string(),
        "resource": repo.as_str(),
        "number": number,
        "action": if reopened { "reopened" } else { "opened" },
        "author": crate::mapping::wire_account(host, &author),
        "actor": crate::mapping::wire_account(host, &actor),
    });
    if let Some(d) = draft {
        ev["draft"] = json!(d);
    }
    if let Some(f) = from_fork {
        ev["fromFork"] = json!(f);
    }
    let me = Arc::clone(bridge);
    tokio::spawn(async move { report(&me, &ns.id, ev).await });
    true
}

async fn report(bridge: &Bridge, ns: &str, ev: serde_json::Value) {
    if let Err(e) = bridge.send_event(ns, ev, None).await {
        tracing::error!(error = %e, "could not report an event");
    }
}

async fn handle(bridge: &Arc<Bridge>, scope: &Scope, kind: ForgeEventKind) {
    match kind {
        ForgeEventKind::RepoCreated { repo, forge_id } => {
            let Some(ns) = namespace_in(bridge, scope, &repo) else {
                return;
            };
            let name = repo.repo_name().unwrap_or_default();
            if NAMESPACE_REPOS.contains(&name) || repo_in(bridge, &ns, forge_id).is_some() {
                // The bridge's own (it creates, then records) or part of the
                // binding.
                return;
            }
            // A repository the bridge is creating right now has no record
            // until its create returns; give it a moment before calling it
            // unmanaged.
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            // At a governed name, with another forge id: the name was
            // reused, and the repository governed there is detached first.
            report_unmanaged(bridge, &ns, &repo, forge_id).await;
        }
        ForgeEventKind::RepoDeleted { repo, forge_id } => {
            let Some(ns) = namespace_in(bridge, scope, &repo) else {
                return;
            };
            if NAMESPACE_REPOS.contains(&repo.repo_name().unwrap_or_default()) {
                return;
            }
            if !detach_from(bridge, &ns, forge_id) {
                return;
            }
            let ev = json!({ "type": "repoDeleted", "forgeId": forge_id.to_string(), "resource": repo.as_str() });
            report(bridge, &ns.id, ev).await;
        }
        ForgeEventKind::RepoRenamed { forge_id, from, to } => {
            let Some(ns) = namespace_in(bridge, scope, &to) else {
                return;
            };
            // A rename stays with its owner. One whose `from` lies outside
            // the namespace is not a rename the VTC may act on (event 0.2:
            // every resource in an event lies inside its namespace).
            if !ns.resource.contains(&from) {
                tracing::warn!(%from, %to, "ignoring a rename that crosses namespaces");
                return;
            }
            // Renamed onto a name the namespace still records for another
            // repository: that one is gone, and nothing of it passes on.
            if claimed_elsewhere(bridge, &ns, forge_id) {
                tracing::warn!(%from, %to, "ignoring a rename of a repository another namespace governs");
                return;
            }
            detach_reused_name(bridge, &ns.id, &to, forge_id);
            let ns_id = ns.id.clone();
            let _ = bridge.store.update::<RepoRecord, _>(
                Table::Repos,
                &repo_key(to.host(), forge_id),
                |r| {
                    Ok((
                        r.map(|mut r| {
                            if r.namespace == ns_id {
                                r.resource = to.clone();
                            }
                            r
                        }),
                        (),
                    ))
                },
            );
            let ev = json!({ "type": "repoRenamed", "forgeId": forge_id.to_string(), "from": from.as_str(), "to": to.as_str() });
            report(bridge, &ns.id, ev).await;
        }
        ForgeEventKind::RepoTransferred {
            forge_id,
            from_namespace,
            to,
        } => {
            // Only this owner's record of the repository counts, and only a
            // `from` in this owner's scope.
            let rec = repo_record(bridge, to.host(), forge_id).filter(|r| {
                scope.covers(&r.resource)
                    && namespace_record(bridge, &r.namespace)
                        .is_some_and(|n| scope.covers(&n.resource))
            });
            let from = rec.as_ref().map(|r| r.resource.clone()).or_else(|| {
                from_namespace
                    .as_ref()
                    .filter(|n| scope.covers(n))
                    .and_then(|n| n.join(to.repo_name().unwrap_or_default()).ok())
            });
            let from_ns = from.as_ref().and_then(|f| namespace_in(bridge, scope, f));
            match (from_ns, from) {
                // Out of a namespace this bridge serves — to another owner,
                // and so out of the namespace, wherever `to` is (a namespace
                // is one owner on one forge). The bridge stops governing it
                // and carries nothing across: if `to` is in another
                // namespace it serves, it arrives there unmanaged (event
                // 0.2: a transfer detaches; rights never move).
                (Some(from_ns), Some(from)) if from_ns.resource.contains(&from) => {
                    transferred_out(bridge, &from_ns, &from, &to, forge_id).await;
                }
                // Transferred *in* from outside every bound namespace: to
                // this namespace it is a repository the VTC did not create
                // or adopt, reported as such — never as `repoTransferred`,
                // whose `from` would lie outside it.
                // Another organisation's namespace may still record it
                // (its App's delivery has not come, or will not): confirmed
                // with GitHub before that side is detached.
                _ => {
                    if let Some(t) = namespace_in(bridge, scope, &to) {
                        confirm_transfer_in(bridge, &t, forge_id).await;
                        report_unmanaged(bridge, &t, &to, forge_id).await;
                    }
                }
            }
        }
        ForgeEventKind::CollaboratorChanged {
            repo,
            forge_id,
            account,
            ..
        } => {
            let Some(ns) = namespace_in(bridge, scope, &repo) else {
                return;
            };
            let Ok(ctx) = Ctx::load(bridge, &ns.id) else {
                return;
            };
            // What the account holds now, from the forge — not from the
            // delivery, which may be old.
            let role = match ctx.adapter.forge().inspect(&repo).await {
                Ok(state) => state
                    .collaborators
                    .iter()
                    .find(|c| c.account.id == account.id)
                    .map(|c| c.role.to_string()),
                Err(e) => {
                    tracing::warn!(%repo, error = %e, "could not read roles after a webhook");
                    return;
                }
            };
            let mut ev = json!({
                "type": "roleChanged",
                "forgeId": forge_id.to_string(),
                "resource": repo.as_str(),
                "account": crate::mapping::wire_account(repo.host(), &account),
            });
            if let Some(r) = role {
                ev["role"] = json!(r);
            }
            report(bridge, &ns.id, ev).await;
            // Then the complete drift for the repository.
            if repo_in(bridge, &ns, forge_id).is_some() {
                inspect_in(bridge, &ns, &repo).await;
            }
        }
        ForgeEventKind::ProtectionChanged {
            repo: Some(repo), ..
        } => {
            if let Some(ns) = namespace_in(bridge, scope, &repo) {
                inspect_in(bridge, &ns, &repo).await;
            }
        }
        ForgeEventKind::ProtectionChanged {
            repo: None,
            namespace,
            ..
        } => {
            // An owner-level rule (the org required workflow): every managed
            // repository may be affected.
            if let Some(ns) = namespace_in(bridge, scope, &namespace)
                && let Ok(ctx) = Ctx::load(bridge, &ns.id)
            {
                let lock = bridge.ns_lock(&ns.id);
                let _g = lock.lock().await;
                let mut r = Report::default();
                jobs::sweep(bridge, &ctx, false, &mut r).await;
            }
        }
        ForgeEventKind::InstallationChanged {
            namespace,
            installation_id,
            change,
        } => {
            let Some(ns) = namespace_in(bridge, scope, &namespace) else {
                return;
            };
            // The namespace's own installation, as recorded at the bind.
            let recorded = ns
                .binding
                .as_ref()
                .and_then(|b| b.namespace.installation_id);
            if recorded != Some(installation_id) {
                tracing::warn!(namespace = %ns.id, installation_id, ?recorded,
                    "ignoring an installation event for another installation");
                return;
            }
            match change {
                InstallationChange::Deleted | InstallationChange::Suspended => {
                    report(bridge, &ns.id, json!({ "type": "installationRemoved" })).await;
                }
                // The owner approved new permissions (or the installation
                // came back): the bridge-posted check may be possible now.
                // A change of guard shows up as drift on the next inspect,
                // which the VTC answers with a bootstrap.
                _ => bridge.probe_bridge_checks(&ns.id).await,
            }
        }
        other => tracing::debug!(event = ?other, "no event to report for this delivery"),
    }
}