ppoppo-identity 0.31.0

Principal-identity vocabulary for the ppoppo ecosystem — the Ppnum/PpnumId pair, the EntityType, LifecycleState and OAuth Scope value-sets, and the admin predicate, shared by the token engine, both services and every SDK
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
//! OAuth scope vocabulary — every scope PAS mints, with the two attributes
//! that are load-bearing across the organ boundary. Private module;
//! [`Scope`], [`ScopeFacts`], [`ScopeTier`], [`ScopeEnforcer`] and
//! [`SCOPE_TABLE`] are re-exported at the crate root. **Why it lives here
//! rather than in `accounts-core`: see the crate docs, §`Scope`.**

use core::fmt;

/// Sensitivity tier of a scope — the **consent severity** its grant carries:
/// how much trust an app must have demonstrated, and how fresh the
/// authentication must be, before the grant is admitted. Not the read/write
/// verb of its operations, and not the row the operation writes.
///
/// **The predicate** (owner decision 2026-09-09; the derivation, the complete
/// 25-row audit and the declined alternatives live in `STS_AUTH_PPOPPO.md`
/// §7.4): a scope is `High` when the operation it authorizes changes the
/// **state or capability of a party other than the caller**; `Medium` when it
/// only reads, exposes PII, discloses a fact about the caller, or writes state
/// no other party's position depends on; `Low` when it is an identity or
/// session primitive.
///
/// | Tier | Examples | Rationale |
/// |---|---|---|
/// | `Low` | `openid`, `profile`, `session_version` | identity / session primitives |
/// | `Medium` | `email`, `chat.read`, `contact.read`, `chat.ack` | reads, PII exposure, or a write no other party's position depends on |
/// | `High` | `chat.send`, `chat.manage`, `myinfo.write` | changes another party's state or capability |
///
/// **Disclosure is not reach.** `chat.ack` writes, and its handler broadcasts a
/// channel-wide `WatermarkUpdate` naming the acker and the read position — so
/// the older ground for its tier ("it sends nothing") was false, and the tier
/// nevertheless holds. It stays `Medium` because a read receipt tells other
/// members something true about the caller while changing nothing they can do.
/// Classifying it `High` would force a notification client to demand the same
/// trust as a full chat client (`RFC_202607201948` D-4). Whether such a receipt
/// should be suppressible is a privacy question, tracked separately at
/// `RFC_202609092242`; it is not a tier question.
///
/// Load-bearing in two places that must agree, which is why it travels with
/// the scope rather than staying a PAS-private annotation: PAS's authorize
/// endpoint decides `prompt=login` from the max tier of a request, and the
/// `ppoppo-pcs-session` SDK's `Notify` tier is *defined* as the set that stays
/// at `Medium` — a const gate in that crate reads this cell.
///
/// Variants are declared ascending so the derived `Ord` is the privilege
/// order; [`rank`](Self::rank) is the same order in `const` context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ScopeTier {
    /// Identity / session primitives.
    Low,
    /// Reads, PII exposure, or a write no other party's position depends on.
    Medium,
    /// Changes the state or capability of a party other than the caller, or
    /// writes a label that renders as the caller's *identity* in other
    /// parties' surfaces (`STS_AUTH_PPOPPO` §7.4.1, identity-label clause).
    High,
}

impl ScopeTier {
    /// Privilege order as a number, for `const` comparison.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Low => 0,
            Self::Medium => 1,
            Self::High => 2,
        }
    }
}

/// Which organ's request perimeter matches a scope at enforcement time — the
/// **organ** half of the `scopes` claim's K8 crossing
/// (`DIRECTION_COUPLING_PASPCS` §4 K8 / §6 I10).
///
/// PAS mints every scope in [`SCOPE_TABLE`], but it only *enforces* some of
/// them. The rest are minted for a different organ to match, and this cell
/// says which. Before it existed a new `chat.*` scope could ship in the
/// catalog, reach a consent screen, be granted, and then be matched by nobody
/// — I10's **silent drop**, which has no runtime signal.
///
/// With the vocabulary shared, the cell is enforced at compile time rather
/// than by a cross-crate test: `chat-core`'s const gates prove that every
/// [`Pcs`](Self::Pcs)-enforced scope backs a gate and every gate is keyed on
/// a `Pcs`-enforced scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScopeEnforcer {
    /// PAS itself: the OIDC/OAuth substrate scopes read at userinfo
    /// (`openid`, `profile`, `email`, `session_version`) **and** the
    /// `plims:*` resource scopes gated per-method on the `:3103` PLIMS ops
    /// face — a second PAS perimeter, not a second organ.
    Pas,
    /// PCS: matched by `SessionScopeLayer` (session faces) and the External
    /// API `ScopeLayer`.
    Pcs,
}

/// Every OAuth scope PAS advertises in discovery and admits at issuance.
///
/// One vocabulary for the four places that used to hold a copy: PAS's
/// `SUPPORTED_SCOPES` list, PAS's `plims:*` string consts, PCS's 15-member
/// `Scope` enum (three parallel lists: variants, `as_str`, `parse`), and the
/// bare string atoms in the SDK's scope tiers — welded together by three
/// dev-dependency tests that compiled the other organ's crate to compare
/// string lists. Now a scope the SDK requests *is* a scope PAS mints, by
/// type, and the organ-boundary inclusions are const gates.
///
/// The enum is retained rather than replaced by the table because exhaustive
/// `match` is load-bearing on the PCS side: an RPC keyed on a scope that
/// does not exist must fail to compile.
///
/// Membership is **server-first, always**: a new atom lands here (and in
/// PAS's policy row and the i18n bundle) before any client asks for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Scope {
    /// OIDC: the identity token itself.
    Openid,
    /// OIDC: name/picture/etc. via userinfo.
    Profile,
    /// OIDC: email via userinfo.
    Email,
    /// Substrate readout: userinfo includes the current `session_version`
    /// so an RP's sv-axis revocation gate can fall through on cache miss.
    SessionVersion,
    /// Read messages, channels, and their metadata.
    ChatRead,
    /// Advance the caller's **own** read watermark — a mutation held at
    /// [`ScopeTier::Medium`], see [`ScopeTier`].
    ChatAck,
    /// Send messages.
    ChatSend,
    /// Create channels, manage membership.
    ChatManage,
    /// Read contacts and sender profiles.
    ContactRead,
    /// Add / block / edit contacts.
    ContactWrite,
    /// React to messages.
    ReactionWrite,
    /// Read the caller's own info cards.
    MyinfoRead,
    /// Edit the caller's own info cards.
    MyinfoWrite,
    /// Set the caller's own self-declared chat display name.
    ///
    /// Named `myprofile.*` rather than `profile.*` because the OIDC
    /// [`Scope::Profile`] atom already occupies that word on the same consent
    /// screen while meaning something else entirely — PAS's claim set, which
    /// carries no name at all (`RFC_202609091230` D1). A separate family from
    /// [`Scope::MyinfoWrite`]: that one governs an AES-256-GCM vault of
    /// identity documents, and one consent row must not mean both.
    MyprofileWrite,
    /// List / inspect the caller's agents.
    AgentRead,
    /// Create / configure agents.
    AgentWrite,
    /// Read message templates.
    TemplateRead,
    /// Create / edit message templates.
    TemplateWrite,
    /// Grant / deny consent on the caller's behalf.
    ConsentManage,
    /// Read usage and processing statistics.
    StatsRead,
    /// PLIMS Developer Layer: list / get numbers and capabilities.
    PlimsNumbersRead,
    /// PLIMS Developer Layer: create / deactivate / configure numbers.
    PlimsNumbersWrite,
    /// PLIMS Developer Layer: list aliases.
    PlimsAliasesRead,
    /// PLIMS Developer Layer: create aliases.
    PlimsAliasesWrite,
    /// PLIMS Developer Layer: read masks (admin-approval opt-in).
    PlimsMasksRead,
    /// PLIMS Developer Layer: create masks (admin-approval opt-in).
    PlimsMasksWrite,
}

/// One row of [`SCOPE_TABLE`] — the cross-organ attributes of one scope.
///
/// Attributes that belong to **one** owner stay with that owner and are
/// deliberately absent: `registerable` (which scopes a self-service
/// registrant may request — read only by PAS's `/oauth/apps` form) and the
/// consent-screen glyph (a PAS view concern) live in `accounts-core`'s policy
/// table, keyed by [`Scope`]. A shared table is not a dumping ground.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScopeFacts {
    /// The variant this row describes; makes the table↔enum wiring checkable
    /// at compile time.
    pub scope: Scope,
    /// Canonical wire string — the atom on the `scope` request parameter, in
    /// the `scopes` claim, and in the discovery document.
    pub wire: &'static str,
    /// See [`ScopeTier`].
    pub tier: ScopeTier,
    /// See [`ScopeEnforcer`].
    pub enforcer: ScopeEnforcer,
}

/// **The lookup table — SSOT of every cross-organ scope attribute.**
///
/// Ordered identically to [`Scope::ALL`] (const-gated below), and that order
/// is the order PAS's discovery document lists `scopes_supported` in.
pub const SCOPE_TABLE: [ScopeFacts; 26] = [
    // ── Low: identity / session primitives ──────────────────────────
    ScopeFacts {
        scope: Scope::Openid,
        wire: "openid",
        tier: ScopeTier::Low,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::Profile,
        wire: "profile",
        tier: ScopeTier::Low,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::Email,
        wire: "email",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::SessionVersion,
        wire: "session_version",
        tier: ScopeTier::Low,
        enforcer: ScopeEnforcer::Pas,
    },
    // ── PCS: the chat surface ────────────────────────────────────────
    ScopeFacts {
        scope: Scope::ChatRead,
        wire: "chat.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    // Medium despite being a write, and despite broadcasting: it discloses a fact
    // about the caller without moving anyone else's state. See `ScopeTier`.
    ScopeFacts {
        scope: Scope::ChatAck,
        wire: "chat.ack",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::ChatSend,
        wire: "chat.send",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::ChatManage,
        wire: "chat.manage",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::ContactRead,
        wire: "contact.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::ContactWrite,
        wire: "contact.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    // High, though a reaction looks small: it attaches a mark to *another party's*
    // message and is broadcast channel-wide, so it moves someone else's state. The
    // predicate, not the size of the write, decides. See `ScopeTier`.
    ScopeFacts {
        scope: Scope::ReactionWrite,
        wire: "reaction.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::MyinfoRead,
        wire: "myinfo.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::MyinfoWrite,
        wire: "myinfo.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    // High by the identity-label clause of `STS_AUTH_PPOPPO` §7.4.1, which is
    // the only copy of that predicate — do not restate its reasoning here.
    ScopeFacts {
        scope: Scope::MyprofileWrite,
        wire: "myprofile.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::AgentRead,
        wire: "agent.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::AgentWrite,
        wire: "agent.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::TemplateRead,
        wire: "template.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::TemplateWrite,
        wire: "template.write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::ConsentManage,
        wire: "consent.manage",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pcs,
    },
    ScopeFacts {
        scope: Scope::StatsRead,
        wire: "stats.read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pcs,
    },
    // ── PLIMS Developer Layer (G1 catalog) — a second PAS perimeter ──
    ScopeFacts {
        scope: Scope::PlimsNumbersRead,
        wire: "plims:numbers:read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::PlimsNumbersWrite,
        wire: "plims:numbers:write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::PlimsAliasesRead,
        wire: "plims:aliases:read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::PlimsAliasesWrite,
        wire: "plims:aliases:write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::PlimsMasksRead,
        wire: "plims:masks:read",
        tier: ScopeTier::Medium,
        enforcer: ScopeEnforcer::Pas,
    },
    ScopeFacts {
        scope: Scope::PlimsMasksWrite,
        wire: "plims:masks:write",
        tier: ScopeTier::High,
        enforcer: ScopeEnforcer::Pas,
    },
];

impl Scope {
    /// Every variant. Ordered as [`SCOPE_TABLE`].
    pub const ALL: [Scope; 26] = [
        Self::Openid,
        Self::Profile,
        Self::Email,
        Self::SessionVersion,
        Self::ChatRead,
        Self::ChatAck,
        Self::ChatSend,
        Self::ChatManage,
        Self::ContactRead,
        Self::ContactWrite,
        Self::ReactionWrite,
        Self::MyinfoRead,
        Self::MyinfoWrite,
        Self::MyprofileWrite,
        Self::AgentRead,
        Self::AgentWrite,
        Self::TemplateRead,
        Self::TemplateWrite,
        Self::ConsentManage,
        Self::StatsRead,
        Self::PlimsNumbersRead,
        Self::PlimsNumbersWrite,
        Self::PlimsAliasesRead,
        Self::PlimsAliasesWrite,
        Self::PlimsMasksRead,
        Self::PlimsMasksWrite,
    ];

    /// Every wire string, in [`ALL`](Self::ALL) order — the discovery
    /// document's `scopes_supported`, derived from the table at compile time
    /// so there is no second list to fall behind.
    pub const NAMES: [&'static str; 26] = {
        let mut names = [""; 26];
        let mut i = 0;
        while i < SCOPE_TABLE.len() {
            names[i] = SCOPE_TABLE[i].wire;
            i += 1;
        }
        names
    };

    /// Stable position in [`ALL`](Self::ALL) / [`SCOPE_TABLE`].
    ///
    /// The exhaustive `match` is the compile-time gate: a 27th variant fails
    /// to build here, so it cannot reach a catalog by defaulting.
    #[must_use]
    pub const fn index(self) -> usize {
        match self {
            Self::Openid => 0,
            Self::Profile => 1,
            Self::Email => 2,
            Self::SessionVersion => 3,
            Self::ChatRead => 4,
            Self::ChatAck => 5,
            Self::ChatSend => 6,
            Self::ChatManage => 7,
            Self::ContactRead => 8,
            Self::ContactWrite => 9,
            Self::ReactionWrite => 10,
            Self::MyinfoRead => 11,
            Self::MyinfoWrite => 12,
            Self::MyprofileWrite => 13,
            Self::AgentRead => 14,
            Self::AgentWrite => 15,
            Self::TemplateRead => 16,
            Self::TemplateWrite => 17,
            Self::ConsentManage => 18,
            Self::StatsRead => 19,
            Self::PlimsNumbersRead => 20,
            Self::PlimsNumbersWrite => 21,
            Self::PlimsAliasesRead => 22,
            Self::PlimsAliasesWrite => 23,
            Self::PlimsMasksRead => 24,
            Self::PlimsMasksWrite => 25,
        }
    }

    /// This scope's row. Every attribute accessor reads through it, so
    /// [`SCOPE_TABLE`] is the only place an attribute is stated.
    #[must_use]
    pub const fn facts(self) -> &'static ScopeFacts {
        &SCOPE_TABLE[self.index()]
    }

    /// Canonical wire string.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.facts().wire
    }

    /// See [`ScopeTier`].
    #[must_use]
    pub const fn tier(self) -> ScopeTier {
        self.facts().tier
    }

    /// See [`ScopeEnforcer`].
    #[must_use]
    pub const fn enforcer(self) -> ScopeEnforcer {
        self.facts().enforcer
    }

    /// Is this a PLIMS Developer Layer resource scope (`plims:*`)?
    ///
    /// The `client_credentials` grant routes a registered app to the
    /// dedicated PLIMS audience when it holds any of these. Stated as a
    /// variant set, not a prefix test on the wire string; a const gate below
    /// pins that the two agree.
    #[must_use]
    pub const fn is_plims(self) -> bool {
        matches!(
            self,
            Self::PlimsNumbersRead
                | Self::PlimsNumbersWrite
                | Self::PlimsAliasesRead
                | Self::PlimsAliasesWrite
                | Self::PlimsMasksRead
                | Self::PlimsMasksWrite
        )
    }

    /// Parse a wire string. Exact inverse of [`as_str`](Self::as_str);
    /// `None` for anything outside the vocabulary.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|scope| scope.as_str() == s)
    }

    /// The scopes a given organ's perimeter matches — one half of the K8
    /// crossing, derived from the table rather than restated.
    pub fn enforced_by(enforcer: ScopeEnforcer) -> impl Iterator<Item = Scope> {
        Self::ALL
            .into_iter()
            .filter(move |scope| scope.enforcer() == enforcer)
    }
}

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

// ── Compile-time gates ──────────────────────────────────────────────────
//
// `SCOPE_TABLE` and `ALL` are two orderings of one fact; the wire strings
// are a set; and `is_plims` is a variant list that must agree with the
// `plims:` namespace and the PAS enforcer. None of that is observable at
// runtime, so all of it is settled at build time.

const fn str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

const fn starts_with(s: &str, prefix: &str) -> bool {
    let (s, p) = (s.as_bytes(), prefix.as_bytes());
    if s.len() < p.len() {
        return false;
    }
    let mut i = 0;
    while i < p.len() {
        if s[i] != p[i] {
            return false;
        }
        i += 1;
    }
    true
}

const _: () = {
    assert!(SCOPE_TABLE.len() == Scope::ALL.len());
    assert!(Scope::NAMES.len() == Scope::ALL.len());

    let mut i = 0;
    while i < Scope::ALL.len() {
        // Row i describes variant i — a mis-ordered table cannot compile.
        assert!(SCOPE_TABLE[i].scope.index() == Scope::ALL[i].index());
        // `facts()` resolves each variant to its OWN row.
        assert!(Scope::ALL[i].facts().scope.index() == Scope::ALL[i].index());
        // `NAMES` is the table's wire column.
        assert!(str_eq(Scope::NAMES[i], SCOPE_TABLE[i].wire));

        // Wire strings are a set: no two rows may spell the same atom.
        let mut j = i + 1;
        while j < Scope::ALL.len() {
            assert!(
                !str_eq(SCOPE_TABLE[i].wire, SCOPE_TABLE[j].wire),
                "two scopes share a wire string"
            );
            j += 1;
        }

        // `is_plims` ⇔ the `plims:` namespace, and every PLIMS scope is a
        // PAS perimeter's to match.
        let s = Scope::ALL[i];
        assert!(
            s.is_plims() == starts_with(s.as_str(), "plims:"),
            "is_plims disagrees with the plims: namespace"
        );
        if s.is_plims() {
            assert!(
                matches!(s.enforcer(), ScopeEnforcer::Pas),
                "a plims:* scope is gated on the :3103 face, which is PAS"
            );
        }
        i += 1;
    }

    // The tier ladder as a number matches the derive order.
    assert!(ScopeTier::Low.rank() < ScopeTier::Medium.rank());
    assert!(ScopeTier::Medium.rank() < ScopeTier::High.rank());

    // D-4 tripwire (`RFC_202607201948`): `chat.ack` mutates, so the reflex
    // is to file it with the write scopes. It must stay strictly below them
    // — it discloses a fact about the caller without moving anyone else's
    // state, and the SDK's Notify family is built on that. See `ScopeTier`.
    assert!(Scope::ChatAck.tier().rank() < Scope::ChatSend.tier().rank());
    assert!(Scope::ChatAck.tier().rank() < Scope::ChatManage.tier().rank());
    // The other visible write, for contrast: a reaction marks *another
    // party's* message, so the same predicate puts it at `High`.
    assert!(Scope::ChatAck.tier().rank() < Scope::ReactionWrite.tier().rank());
};

#[cfg(test)]
// Outer, not the usual inner `#![allow(..)]`: see `lib.rs`'s test module.
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn parse_is_the_inverse_of_as_str() {
        for s in Scope::ALL {
            assert_eq!(Scope::parse(s.as_str()), Some(s));
        }
        assert_eq!(Scope::parse(""), None);
        assert_eq!(Scope::parse("unknown"), None);
        assert_eq!(Scope::parse("chat.readonly"), None);
        assert_eq!(Scope::parse("CHAT.READ"), None);
    }

    #[test]
    fn names_are_the_discovery_order() {
        assert_eq!(Scope::NAMES[0], "openid");
        // Anchored to the *tail*, not to a literal index: a scope inserted in
        // its family group renumbers every row after it, and an index literal
        // here would then pin the wrong end of the list while still passing.
        assert_eq!(Scope::NAMES.last(), Some(&"plims:masks:write"));
        let via_all: Vec<&str> = Scope::ALL.iter().map(|s| s.as_str()).collect();
        assert_eq!(via_all, Scope::NAMES);
    }

    /// The PAS-enforced half, pinned to a hand-written oracle.
    ///
    /// The organ-boundary inclusions are const gates in `chat-core`; what
    /// those cannot see is a **mislabel** the other way — a new `chat.*` scope
    /// marked `Pas` by mistake is one PCS will never match and nothing else
    /// will flag. So this half is pinned here, deliberately NOT derived from
    /// the table it checks.
    #[test]
    fn pas_enforced_half_is_pinned() {
        const EXPECTED: &[&str] = &[
            "openid",
            "profile",
            "email",
            "session_version",
            "plims:numbers:read",
            "plims:numbers:write",
            "plims:aliases:read",
            "plims:aliases:write",
            "plims:masks:read",
            "plims:masks:write",
        ];
        let got: Vec<&str> = Scope::enforced_by(ScopeEnforcer::Pas)
            .map(Scope::as_str)
            .collect();
        assert_eq!(
            got, EXPECTED,
            "the PAS-enforced half of the catalog drifted. If the new scope really \
             is PAS's to enforce, add it here; if PCS matches it, mark it \
             `ScopeEnforcer::Pcs` and key a PCS gate on it."
        );
    }

    #[test]
    fn both_halves_partition_the_vocabulary() {
        let pas = Scope::enforced_by(ScopeEnforcer::Pas).count();
        let pcs = Scope::enforced_by(ScopeEnforcer::Pcs).count();
        assert!(pas > 0 && pcs > 0);
        assert_eq!(pas + pcs, Scope::ALL.len());
    }

    #[test]
    fn tiers_classify_as_documented() {
        for s in [Scope::Openid, Scope::Profile, Scope::SessionVersion] {
            assert_eq!(s.tier(), ScopeTier::Low, "{s}");
        }
        for s in [
            Scope::Email,
            Scope::ChatRead,
            Scope::ChatAck,
            Scope::ContactRead,
            Scope::MyinfoRead,
            Scope::AgentRead,
            Scope::TemplateRead,
            Scope::StatsRead,
            Scope::PlimsNumbersRead,
            Scope::PlimsAliasesRead,
            Scope::PlimsMasksRead,
        ] {
            assert_eq!(s.tier(), ScopeTier::Medium, "{s}");
        }
        for s in [
            Scope::ChatSend,
            Scope::ChatManage,
            Scope::ContactWrite,
            Scope::ReactionWrite,
            Scope::MyinfoWrite,
            Scope::AgentWrite,
            Scope::TemplateWrite,
            Scope::ConsentManage,
            Scope::PlimsNumbersWrite,
            Scope::PlimsAliasesWrite,
            Scope::PlimsMasksWrite,
        ] {
            assert_eq!(s.tier(), ScopeTier::High, "{s}");
        }
        assert!(ScopeTier::Low < ScopeTier::Medium && ScopeTier::Medium < ScopeTier::High);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn tier_serde_is_the_variant_name() {
        assert_eq!(
            serde_json::to_string(&ScopeTier::Medium).unwrap(),
            "\"Medium\""
        );
        assert_eq!(
            serde_json::from_str::<ScopeTier>("\"High\"").unwrap(),
            ScopeTier::High
        );
    }
}