polyc-tools 2026.8.3

The in-process tool core for polychrome agents: local executors (coding, web fetch, wallet, ...), the tool registry, and MCP composition. The networked connectors live in polyc-connectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
//! Capability classification for the built-in tool surface (`#592`).
//!
//! Maps each built-in tool to the [`polyc_capability::ToolProfile`] its
//! [`ToolSpec`] annotations plus its origin describe, and derives the
//! required-capability set the gate consults. Origin is the
//! registry-provenance half of classification and comes from the STATIC
//! shape of the built-in surface — which module owns the name — never from
//! anything a call or a connector can influence:
//!
//! - the coding tools run inside the egress-less conversation sandbox;
//! - the web/paid fetchers are brokered to model-controlled destinations;
//! - the own-conversation read / memory / wallet / peer / email-link families
//!   act on first-party state via the control plane
//!   (fixed, operator-owned destinations);
//! - the admin invite grants a third party access to the system, so it maps to
//!   [`ToolOrigin::AccessGrant`] and requires the never-granted
//!   `GrantAccess` capability — it always escalates to a human (`#700`);
//! - anything else is unknown and fails closed to the privileged set.
//!
//! [`unclassified_builtins`] is the fail-closed classification lint: a
//! built-in spec that lands in the privileged bucket is a build/startup
//! error, so an unannotated built-in surfaces to a developer instead of as a
//! spurious approval prompt to a person. Connector tools may still fail
//! closed at RUNTIME — that is the guarantee, not a bug.

use polyc_capability::{
    Capability, CapabilitySet, Ceremony, Requirement, ToolOrigin, ToolProfile,
    required_capabilities,
};
use polyc_llm::ToolSpec;

use crate::{
    ToolRegistry, ask_question, coding, conversation, demote, email_link, invite, list_admins,
    memory, paid_fetch, peer, provisional_persona, revoke, routine, unlink_identity, unlink_self,
    wallet, web,
};

/// The registry provenance of a built-in tool name, from the static shape of
/// the built-in surface. `None` for a name no built-in family owns — the
/// caller fails closed.
#[must_use]
pub fn builtin_origin(name: &str) -> Option<ToolOrigin> {
    if coding::owns(name) {
        return Some(ToolOrigin::LocalSandbox);
    }
    // `ask_question` (#1660) performs no read or write of its own — calling it
    // only ever pauses the turn for a human's answer, entirely inside the
    // turn loop's own question-pause phase; no bytes leave the conversation
    // and nothing outside it mutates. That is the same "confined to this
    // process's own turn" shape `LocalSandbox` already models for the coding
    // tools, so it shares the classification (and, since the spec is
    // `.read_only()`, requires only the minimal `LocalRead` capability below)
    // rather than needing a bespoke origin.
    if ask_question::ALL.contains(&name) {
        return Some(ToolOrigin::LocalSandbox);
    }
    if name == web::WEB_FETCH || name == paid_fetch::TOOL_NAME {
        return Some(ToolOrigin::Fetcher);
    }
    // The admin invite grants a third party access to the system, so it is
    // classified apart from the first-party family: it requires the
    // never-granted `GrantAccess` capability and therefore always escalates to
    // a human before anything is minted (`#700`).
    if invite::ALL.contains(&name) {
        return Some(ToolOrigin::AccessGrant);
    }
    // The admin de-admission (#713): the offboarding sibling of the admin
    // invite above, classified apart from the first-party family for the same
    // reason — it requires the never-granted `RevokeAccess` capability and
    // therefore always escalates to a human before anyone is removed.
    if revoke::ALL.contains(&name) {
        return Some(ToolOrigin::AccessRevoke);
    }
    // unlink_identity and delete_provisional_persona (`#1599`) reuse
    // `AccessRevoke` rather than mint a fourth never-granted marker: doing so
    // would need `Capability`/`CapabilitySet` widened from `u8` to `u16`
    // first (`ManageAdmin` above already sits on the last `u8` bit). Both
    // tools are access-severing in the same shape `revoke` is — one identity
    // instead of all of them, or a whole still-provisional persona instead of
    // a linked one — so sharing its never-granted capability is the correct
    // fit, not just an expedient one.
    if unlink_identity::ALL.contains(&name)
        || name == provisional_persona::DELETE_PROVISIONAL_PERSONA
    {
        return Some(ToolOrigin::AccessRevoke);
    }
    // The admin demote (#715): completes the admin-management set alongside
    // the invite/revoke pair above, classified apart from the first-party
    // family for the same reason — it requires the never-granted
    // `ManageAdmin` capability and therefore always escalates to a human
    // before anyone's admin role changes.
    if demote::ALL.contains(&name) {
        return Some(ToolOrigin::AdminManage);
    }
    if conversation::ALL.contains(&name)
        || list_admins::ALL.contains(&name)
        || wallet::ALL.contains(&name)
        || email_link::ALL.contains(&name)
        || memory::ALL.contains(&name)
        || routine::ALL.contains(&name)
        || unlink_self::ALL.contains(&name)
        || name == peer::PEER_CALL
        || name == provisional_persona::LIST_PROVISIONAL_PERSONAS
    {
        // `memory_write` (#1139) and `unlink_self` (post-incident consolidation
        // of `unlink_email`/`wallet_unlink`) sit here deliberately: each acts on
        // the caller's own first-party state via the control plane, so as a
        // non-read-only first-party tool it requires `MutateExternal` on top
        // of the fixed-connector read — and each spec's intrinsic
        // `needs_approval` gates every call besides.
        //
        // `list_provisional_personas` (`#1599`) sits here too, deliberately
        // apart from its `delete_provisional_persona` sibling above: it is
        // read-only (its spec carries `.read_only()`) and admin-gated at the
        // nav layer, but does NOT need a never-granted capability — an admin
        // asking "what provisional personas exist" is an ordinary report,
        // not an access-severing action that must always escalate to a
        // human.
        //
        // `list_admins` sits here for the same reason
        // `list_provisional_personas` does, and deliberately NOT beside its
        // `invite`/`revoke`/`demote` siblings above: it reads the admin
        // roster and changes nothing, so it must not require a
        // never-granted marker and force a fresh human approval every time
        // an admin asks who the admins are. The admin gate (and the "no
        // membership at all for a non-admin" guarantee) is enforced
        // control-plane-side in `list_admins_nav::execute`, exactly like
        // `wallet_roster`'s and `routine_list`'s own caller checks.
        //
        // `routine_list` (`#1494`) joins here the same way `wallet_roster`
        // does: a read-only, authorization-gated first-party tool over this
        // deployment's own `Routine` CRs. Who it answers, and with how much
        // (every routine for an admin, only your own otherwise, `#1872`), is
        // decided control-plane-side in `routine_nav::execute` along with the
        // "no routine data for a caller with none of their own" guarantee
        // (INV-RL1) — none of it modeled as a capability requirement here,
        // exactly like `wallet_roster`'s own gate.
        //
        // The `conversation` read family (`docs/reference/agent-read-surface.md`)
        // sits here and NOT in `management` below: all five read the caller's
        // own conversation record through the control plane, which is a
        // fixed-connector read, not the mutate-or-grant shape the management
        // envelope exists for. `memory_recall` is the deliberate exception —
        // it reaches a persona's memory, which spans conversations, so it
        // joins `memory::ALL` and the management envelope with the write.
        return Some(ToolOrigin::FirstParty);
    }
    None
}

/// The deployment prerequisites a built-in NAME's calls depend on (`#1415`).
///
/// Derived from the same STATIC shape [`builtin_origin`] reads — which
/// module owns the name — never from anything a call or a connector can
/// influence. `&[]` for a built-in with no deployment prerequisite (every
/// sandbox-confined, fetcher, and read-only first-party built-in): it is
/// always advertised regardless of what [`polyc_capability::DeploymentCapabilities`]
/// says. `None` for a name no built-in family owns — the caller fails
/// closed, mirroring [`builtin_origin`]'s own `None` convention.
///
/// Only a mutation that MINTS something a deployment fact can leave
/// dangling carries a requirement — a read that merely reports on state
/// already minted (`wallet_status`, `wallet_history`, `wallet_roster`) needs
/// nothing from THIS deployment's ceremony/proxy config to answer truthfully,
/// so it stays advertised even when the matching mint is unconfigured.
#[must_use]
pub fn builtin_requirements(name: &str) -> Option<&'static [Requirement]> {
    // The wallet-link ceremony page mints (or reuses) `wallet_link`'s card —
    // and the TIP-1011 in-place spending-limit update shares that same page
    // (`crate::wallet::WALLET_UPDATE_LIMIT`'s control-plane sibling reuses
    // `POLYCHROME_WALLET_LINK_URL`). `wallet_set_policy` changes an
    // already-linked wallet's policy record directly — no ceremony page
    // involved — so it carries no requirement, like the read-only wallet
    // family below.
    if name == wallet::WALLET_LINK || name == wallet::WALLET_UPDATE_LIMIT {
        return Some(&[Requirement::CeremonyPage(Ceremony::WalletLink)]);
    }
    // The email magic-link ceremony mints AND mails the verification link:
    // it needs both the ceremony page configured and a usable relay to
    // actually deliver it.
    if name == email_link::LINK_EMAIL {
        return Some(&[
            Requirement::CeremonyPage(Ceremony::EmailMagicLink),
            Requirement::MailRelay,
        ]);
    }
    // `paid_fetch` needs the outbound-payments proxy to ever send a payment.
    if name == paid_fetch::TOOL_NAME {
        return Some(&[Requirement::PaymentsProxy]);
    }
    if wallet::ALL.contains(&name)
        || unlink_self::ALL.contains(&name)
        || coding::owns(name)
        || ask_question::ALL.contains(&name)
        || name == web::WEB_FETCH
        || invite::ALL.contains(&name)
        || revoke::ALL.contains(&name)
        || demote::ALL.contains(&name)
        || unlink_identity::ALL.contains(&name)
        || name == provisional_persona::DELETE_PROVISIONAL_PERSONA
        || name == provisional_persona::LIST_PROVISIONAL_PERSONAS
        || conversation::ALL.contains(&name)
        || list_admins::ALL.contains(&name)
        || memory::ALL.contains(&name)
        || routine::ALL.contains(&name)
        || name == peer::PEER_CALL
    {
        // Every other built-in this catalog knows about has no deployment
        // prerequisite: it either never leaves the sandbox, dials a fixed
        // operator-owned destination that needs no ceremony, or only reads
        // state a mint already produced.
        return Some(&[]);
    }
    None
}

/// The capabilities a built-in spec's calls require: its annotations plus the
/// static origin of its name.
///
/// A spec whose name no built-in family owns requires the full privileged
/// set (fail closed).
#[must_use]
pub fn required_for_spec(spec: &ToolSpec) -> CapabilitySet {
    if spec.name == "shell_exec" {
        return CapabilitySet::of(Capability::LocalRead)
            .with(Capability::LocalWrite)
            .with(Capability::ArbitraryEgress);
    }
    let origin = builtin_origin(&spec.name).unwrap_or(ToolOrigin::Unknown);
    required_capabilities(ToolProfile::for_spec(spec, origin))
}

/// The capabilities a built-in NAME requires, resolved against `specs` (the
/// advertised catalog).
///
/// A name with no spec in the catalog requires the full privileged set — an
/// unknown tool never slips through un-gated.
#[must_use]
pub fn required_for_builtin(name: &str, specs: &[ToolSpec]) -> CapabilitySet {
    specs
        .iter()
        .find(|s| s.name == name)
        .map_or_else(CapabilitySet::all, required_for_spec)
}

/// The management-family built-ins (`#1137`, plus `memory_write` per `#1139`
/// Decision A).
///
/// The canonical model both the harness's advertisement composition and the
/// control plane's execution re-check consume so the two sides cannot drift.
/// Spans the wallet and email-linking tools, the roster-admin trio (and the
/// read-only `list_admins` report over what
/// they change), and the deliberate memory write — every built-in
/// family the harness proxies through the control plane behind
/// `ControlPlaneToolProxy` (`build_tool_executor`) and that needs the
/// agent's resolved built-in grant (or the always-on core, `#637`) to
/// compose or execute at all. `Builtin` origin is not a blanket advertisement
/// right for these names (INV-C7/INV-C19): unlike the history-navigation
/// family and `peer_call`, which default ON absent a grant, a management
/// name composes and executes ONLY when the grant (or core) explicitly names
/// it — see [`crate::mcp_client::builtin_admits`] for the shared predicate
/// that enforces this. Both memory tools join the family rather than
/// defaulting on: a durable write into a persona's memory partition needs the
/// same explicit-envelope treatment as a wallet mutation or a roster change,
/// and `memory_recall` reads that same cross-conversation partition back, so
/// the opt-out posture the own-conversation read family gets would be wrong
/// for it.
pub mod management {
    use std::sync::LazyLock;

    use crate::{
        demote, email_link, invite, list_admins, memory, provisional_persona, revoke, routine,
        unlink_identity, unlink_self, wallet,
    };

    /// Every management built-in name.
    ///
    /// Spans the wallet family ([`crate::wallet::ALL`]), `link_email`
    /// ([`crate::email_link::ALL`]), the roster-admin trio
    /// `invite`/`revoke`/`demote` ([`crate::invite::ALL`],
    /// [`crate::revoke::ALL`], [`crate::demote::ALL`]) plus the read-only
    /// `list_admins` that reports on what those three change
    /// ([`crate::list_admins::ALL`]), the deliberate
    /// memory write `memory_write` and the `memory_recall` read
    /// ([`crate::memory::ALL`], `#1139` Decision A: a durable write requires
    /// the same explicit envelope as the other families, and a read that
    /// crosses conversations requires it for the same reason `list_admins`
    /// does), the provisional-persona cleanup pair
    /// `unlink_identity`/`delete_provisional_persona`/
    /// `list_provisional_personas` ([`crate::unlink_identity::ALL`],
    /// [`crate::provisional_persona::ALL`], `#1599`), the self-service
    /// `unlink_self` ([`crate::unlink_self::ALL`] — post-incident
    /// consolidation of the former `unlink_email`/`wallet_unlink`), and
    /// `routine_list` ([`crate::routine::ALL`], `#1494`: the
    /// authorization-gated routine inspection every lifecycle mutation
    /// depends on).
    ///
    /// Built lazily (not a `const` slice) because it concatenates several
    /// other families' `const` slices, which stable Rust cannot do at compile
    /// time without a proc macro; the concatenation runs once, on first use.
    pub static ALL: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
        wallet::ALL
            .iter()
            .chain(email_link::ALL)
            .chain(invite::ALL)
            .chain(revoke::ALL)
            .chain(demote::ALL)
            .chain(list_admins::ALL)
            .chain(memory::ALL)
            .chain(unlink_identity::ALL)
            .chain(unlink_self::ALL)
            .chain(provisional_persona::ALL)
            .chain(routine::ALL)
            .copied()
            .collect()
    });

    /// Whether `name` is one of the management-family built-ins ([`ALL`]).
    #[must_use]
    pub fn is_management_builtin(name: &str) -> bool {
        ALL.contains(&name)
    }

    /// Every management built-in spec.
    ///
    /// The one owner of the eleven-family `all_specs()` chain, so a
    /// composition site (the harness's `build_tool_executor`, this module's
    /// own classification-lint spec list) pulls the whole family from one
    /// call instead of hand-chaining the eleven underlying `all_specs()`
    /// functions itself and risking drift from [`ALL`].
    #[must_use]
    pub fn all_specs() -> Vec<polyc_llm::ToolSpec> {
        wallet::all_specs()
            .into_iter()
            .chain(email_link::all_specs())
            .chain(invite::all_specs())
            .chain(revoke::all_specs())
            .chain(demote::all_specs())
            .chain(list_admins::all_specs())
            .chain(memory::all_specs())
            .chain(unlink_identity::all_specs())
            .chain(unlink_self::all_specs())
            .chain(provisional_persona::all_specs())
            .chain(routine::all_specs())
            .collect()
    }
}

/// The fail-safe classification floor for a name the static catalog already
/// knows reaches model-controlled destinations.
///
/// OR-ed over whatever the owning executor claims (mirrors the
/// `is_egress_capable` floor in [`crate::CompositeRegistry`]): a brokering
/// wrapper that owns a fetcher but forgets to classify it cannot silently
/// shed the fetcher's requirements.
#[must_use]
pub fn floor_requirements(name: &str) -> CapabilitySet {
    if name == web::WEB_FETCH || name == paid_fetch::TOOL_NAME {
        let spec = if name == web::WEB_FETCH {
            web::fetch_spec()
        } else {
            paid_fetch::spec()
        };
        required_capabilities(ToolProfile::for_spec(&spec, ToolOrigin::Fetcher))
    } else if name == web::NATIVE_SEARCH_GROUNDING {
        native_search_grounding_requirements()
    } else {
        CapabilitySet::EMPTY
    }
}

/// The capabilities the provider's native web-search-grounding primitive
/// requires (issue `#1226`).
///
/// Unlike every other built-in, this is never advertised as a [`ToolSpec`] —
/// the provider decides mid-generation whether to ground, so there is no
/// `tool_use` call for the harness to intercept and classify via
/// [`required_for_builtin`].
///
/// Thin re-export of [`polyc_capability::CapabilitySet::native_search_grounding_requirements`]
/// — the ONE definition lives in the shared foundation crate, since
/// `polyc_agent`'s per-step gate needs the identical value and cannot depend
/// on this crate (the reverse dependency already exists).
#[must_use]
pub const fn native_search_grounding_requirements() -> CapabilitySet {
    CapabilitySet::native_search_grounding_requirements()
}

/// Every built-in spec family the deployment can advertise: the registry's
/// coding + fetcher surface (with payments forced on so `paid_fetch` is
/// covered) plus the control-plane-executed own-conversation read /
/// management / peer families the harness proxies advertise.
/// `management::all_specs()` already carries the deliberate memory write and
/// `memory_recall` (both live in [`crate::memory::ALL`]) — they are not chained
/// separately here.
fn all_builtin_specs() -> Vec<ToolSpec> {
    let mut specs = ToolRegistry::specs_with_payments(true);
    specs.extend(conversation::all_specs());
    specs.extend(management::all_specs());
    specs.push(peer::spec(&["peer".to_owned()]));
    specs
}

/// The fail-closed classification lint (`#592`): the names of built-in specs
/// that classify into the privileged bucket.
///
/// Non-empty means a built-in is missing the annotations or the origin
/// mapping its classification needs — a developer error that must fail
/// CI/startup, not surface as a spurious approval prompt.
#[must_use]
pub fn unclassified_builtins() -> Vec<String> {
    all_builtin_specs()
        .iter()
        .filter(|s| required_for_spec(s) == CapabilitySet::all())
        .map(|s| s.name.clone())
        .collect()
}

/// Startup half of the classification lint: panics when any built-in spec
/// fails to classify.
///
/// Called once at process start by the harness and the control plane, so a
/// misannotated built-in kills the deploy loudly instead of degrading every
/// conversation with fail-closed prompts.
///
/// # Panics
///
/// Panics when [`unclassified_builtins`] is non-empty.
pub fn assert_builtins_classified() {
    let unclassified = unclassified_builtins();
    assert!(
        unclassified.is_empty(),
        "built-in tools failed capability classification (add annotations or \
         extend polyc_tools::capability::builtin_origin): {unclassified:?}"
    );
}

/// The fail-closed requirement-resolution lint (`#1415`): the names of
/// built-in specs [`builtin_requirements`] cannot resolve (returns `None`
/// for).
///
/// Non-empty means a built-in gained a spec without a matching arm in
/// [`builtin_requirements`] — a developer error that must fail CI/startup,
/// exactly like [`unclassified_builtins`] does for capability classification.
#[must_use]
pub fn unresolved_builtin_requirements() -> Vec<String> {
    all_builtin_specs()
        .iter()
        .filter(|s| builtin_requirements(&s.name).is_none())
        .map(|s| s.name.clone())
        .collect()
}

/// Startup half of the requirement-resolution lint: panics when any built-in
/// spec's deployment prerequisites fail to resolve.
///
/// Called once at process start alongside [`assert_builtins_classified`], so
/// an unclassified built-in's deployment prerequisites kill the deploy
/// loudly instead of silently advertising the tool unconditionally.
///
/// # Panics
///
/// Panics when [`unresolved_builtin_requirements`] is non-empty.
pub fn assert_builtin_requirements_resolved() {
    let unresolved = unresolved_builtin_requirements();
    assert!(
        unresolved.is_empty(),
        "built-in tools failed deployment-requirement resolution (extend \
         polyc_tools::capability::builtin_requirements): {unresolved:?}"
    );
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use polyc_capability::Capability;
    use serde_json::json;

    use super::*;

    const fn set(caps: &[Capability]) -> CapabilitySet {
        let mut s = CapabilitySet::EMPTY;
        let mut i = 0;
        while i < caps.len() {
            s = s.with(caps[i]);
            i += 1;
        }
        s
    }

    /// `#1702`: no built-in spec may be BOTH `approval_required` and
    /// `cacheable_approval`, over the whole catalog.
    ///
    /// `polyc_tools::peer` already asserted this for `peer_call` alone; the
    /// property is catalog-wide, so it is pinned here where
    /// [`all_builtin_specs`] can see every family at once.
    ///
    /// Two independent things depend on the disjointness:
    ///
    /// - `polyc_agent`'s `session_approves` only ever auto-executes a
    ///   `cacheable_approval` tool on a remembered session grant, so a tool
    ///   that were both would be gated AND satisfiable without a per-call
    ///   approval.
    /// - The control plane's `call_is_approved` re-verifies a brokered gated
    ///   call against a signed approval bound to that call's `request_id`. A
    ///   session grant is issued in an EARLIER turn and honored later under a
    ///   different tool-call id, so it can never match — a gated-and-cacheable
    ///   tool would have its legitimate session-approved calls refused.
    #[test]
    fn no_builtin_is_both_approval_required_and_cacheable() {
        let both: Vec<String> = all_builtin_specs()
            .iter()
            .filter(|s| s.needs_approval && s.cacheable_approval)
            .map(|s| s.name.clone())
            .collect();
        assert!(
            both.is_empty(),
            "these built-ins are both approval_required and cacheable_approval: {both:?}. The \
             control plane's trusted-side approval recheck (#1702) matches a brokered gated call \
             against an approval bound to that call's own tool-call id, and a remembered session \
             grant carries a DIFFERENT id from an earlier turn — so a tool that is both would \
             have its legitimate session-approved calls refused. Teach the recheck about session \
             grants before making any gated tool cacheable."
        );
    }

    // #592 acceptance: derivation per annotation combination, over the REAL
    // built-in specs.
    #[test]
    fn builtin_derivation_matches_the_capability_table() {
        let specs = all_builtin_specs();
        // Read-only sandbox tools.
        for name in ["file_read", "grep", "glob"] {
            assert_eq!(
                required_for_builtin(name, &specs),
                set(&[Capability::LocalRead]),
                "{name}"
            );
        }
        // File mutations remain local to the sandbox.
        for name in ["file_write", "file_edit"] {
            assert_eq!(
                required_for_builtin(name, &specs),
                set(&[Capability::LocalRead, Capability::LocalWrite]),
                "{name}"
            );
        }
        assert_eq!(
            required_for_builtin("shell_exec", &specs),
            set(&[
                Capability::LocalRead,
                Capability::LocalWrite,
                Capability::ArbitraryEgress,
            ])
        );
        // The open-world fetcher.
        assert_eq!(
            required_for_builtin("web_fetch", &specs),
            set(&[Capability::ArbitraryEgress])
        );
        // The paying fetcher: egress + external mutation (it spends money).
        assert_eq!(
            required_for_builtin("paid_fetch", &specs),
            set(&[Capability::ArbitraryEgress, Capability::MutateExternal])
        );
        // First-party read-only families: fixed-connector read, which taint
        // never revokes — the structural form of the old carve-out lists.
        // `conversation_read_tool_result` lands here too despite being
        // `open_world`: that annotation marks an INGESTION source and is
        // deliberately not consulted by `required_capabilities`.
        for name in conversation::ALL {
            assert_eq!(
                required_for_builtin(name, &specs),
                set(&[Capability::FixedConnectorRead]),
                "{name}"
            );
        }
        // `memory_recall` reads a persona's own memory through the control
        // plane — the same fixed-connector read, even though its GRANT is
        // management-gated (that is an advertisement right, not a capability).
        assert_eq!(
            required_for_builtin(memory::MEMORY_RECALL, &specs),
            set(&[Capability::FixedConnectorRead])
        );
        for name in [
            "wallet_status",
            "wallet_history",
            "wallet_roster",
            // Issue #1494: routine_list is a read-only, authorization-gated
            // first-party tool over this deployment's own `Routine` CRs —
            // classified identically to `wallet_roster`. #1872 widened who it
            // answers (an owner as well as an admin), never what it reaches.
            routine::ROUTINE_LIST,
        ] {
            assert_eq!(
                required_for_builtin(name, &specs),
                set(&[Capability::FixedConnectorRead]),
                "{name}"
            );
        }
        // First-party mutating tools: the fixed dial plus external mutation.
        for name in [
            "wallet_link",
            "wallet_set_policy",
            // Issue #1159: the TIP-1011 in-place spending-limit-update
            // ceremony's self-service tool — same first-party-mutating
            // shape as `wallet_link`.
            "wallet_update_limit",
            "peer_call",
            // Issue #962: mints a persona-side link ceremony and sends mail —
            // a mutation, classified identically to the other first-party
            // mutating tools above (never the fail-closed privileged set).
            "link_email",
            // Post-incident consolidation of `unlink_email`/`wallet_unlink`:
            // removes the caller's own linked email or wallet by `target`,
            // classified the same way its predecessors were.
            unlink_self::TOOL_NAME,
            // Issue #1139: the deliberate memory write appends to the
            // caller's own persona-memory partition — a first-party mutation,
            // and additionally gated by its spec's intrinsic `needs_approval`.
            "memory_write",
            // #1497: `routine_create` writes a new `Routine` CR — a
            // first-party mutation classified identically to `memory_write`,
            // and likewise additionally gated by its spec's intrinsic
            // `needs_approval` (every call always pauses for a human,
            // INV-RL2).
            routine::ROUTINE_CREATE,
        ] {
            assert_eq!(
                required_for_builtin(name, &specs),
                set(&[Capability::FixedConnectorRead, Capability::MutateExternal]),
                "{name}"
            );
        }
        // A name with no spec fails closed to the privileged set.
        assert_eq!(
            required_for_builtin("no_such_tool", &specs),
            CapabilitySet::all()
        );
        // A spec whose name no family owns fails closed too.
        let stray = ToolSpec::new("mystery", "d", json!({})).read_only();
        assert_eq!(required_for_spec(&stray), CapabilitySet::all());
    }

    // #700: the real admin invite tool requires the never-granted
    // `GrantAccess`, so the gate escalates it in EVERY taint state — a clean
    // conversation included. This is the wiring-level assertion that FAILS
    // under #699's classification (invite as a first-party mutation, allowed on
    // a clean context) and PASSES now.
    #[test]
    fn invite_requires_grant_access_and_always_escalates() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required = required_for_builtin(invite::TOOL_NAME, &specs);
        assert_eq!(
            required,
            set(&[Capability::GrantAccess]),
            "the invite tool requires only the never-granted access-grant marker"
        );
        // Escalates in both taint states under the runtime default policy — the
        // one policy the gate actually constructs.
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(GrantPolicy::default(), taint);
            let out = decide(required, granted, &CallPolicy::default(), invite::TOOL_NAME);
            assert!(
                matches!(out, GateOutcome::Escalate { .. }),
                "invite must escalate under {taint:?}, got {out:?}"
            );
        }
    }

    // #713: the real admin revoke tool requires the never-granted
    // `RevokeAccess`, so the gate escalates it in EVERY taint state — a clean
    // conversation included. The offboarding mirror of
    // `invite_requires_grant_access_and_always_escalates`.
    #[test]
    fn revoke_requires_revoke_access_and_always_escalates() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required = required_for_builtin(revoke::TOOL_NAME, &specs);
        assert_eq!(
            required,
            set(&[Capability::RevokeAccess]),
            "the revoke tool requires only the never-granted revoke-access marker"
        );
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(GrantPolicy::default(), taint);
            let out = decide(required, granted, &CallPolicy::default(), revoke::TOOL_NAME);
            assert!(
                matches!(out, GateOutcome::Escalate { .. }),
                "revoke must escalate under {taint:?}, got {out:?}"
            );
        }
    }

    // #715: the real admin demote tool requires the never-granted
    // `ManageAdmin`, so it escalates in every taint state — a clean
    // conversation included. The admin-management-completing mirror of
    // `revoke_requires_revoke_access_and_always_escalates`.
    #[test]
    fn demote_requires_manage_admin_and_always_escalates() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required = required_for_builtin(demote::TOOL_NAME, &specs);
        assert_eq!(
            required,
            set(&[Capability::ManageAdmin]),
            "the demote tool requires only the never-granted manage-admin marker"
        );
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(GrantPolicy::default(), taint);
            let out = decide(required, granted, &CallPolicy::default(), demote::TOOL_NAME);
            assert!(
                matches!(out, GateOutcome::Escalate { .. }),
                "demote must escalate under {taint:?}, got {out:?}"
            );
        }
    }

    // #1599: `unlink_identity` reuses `revoke`'s never-granted `RevokeAccess`
    // marker (a fourth marker would need `Capability`/`CapabilitySet` widened
    // from `u8` to `u16` first), so it escalates in EVERY taint state exactly
    // like `revoke` does.
    #[test]
    fn unlink_identity_requires_revoke_access_and_always_escalates() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required = required_for_builtin(unlink_identity::TOOL_NAME, &specs);
        assert_eq!(
            required,
            set(&[Capability::RevokeAccess]),
            "unlink_identity requires only the never-granted revoke-access marker"
        );
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(GrantPolicy::default(), taint);
            let out = decide(
                required,
                granted,
                &CallPolicy::default(),
                unlink_identity::TOOL_NAME,
            );
            assert!(
                matches!(out, GateOutcome::Escalate { .. }),
                "unlink_identity must escalate under {taint:?}, got {out:?}"
            );
        }
    }

    // #1599: `delete_provisional_persona` reuses the same marker as `revoke`
    // for the same reason `unlink_identity` does above — it is access-severing
    // in the same shape, just scoped to a still-provisional target.
    #[test]
    fn delete_provisional_persona_requires_revoke_access_and_always_escalates() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required =
            required_for_builtin(provisional_persona::DELETE_PROVISIONAL_PERSONA, &specs);
        assert_eq!(
            required,
            set(&[Capability::RevokeAccess]),
            "delete_provisional_persona requires only the never-granted revoke-access marker"
        );
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(GrantPolicy::default(), taint);
            let out = decide(
                required,
                granted,
                &CallPolicy::default(),
                provisional_persona::DELETE_PROVISIONAL_PERSONA,
            );
            assert!(
                matches!(out, GateOutcome::Escalate { .. }),
                "delete_provisional_persona must escalate under {taint:?}, got {out:?}"
            );
        }
    }

    // #1599: `list_provisional_personas` is read-only and does NOT carry a
    // never-granted marker — unlike its `delete_provisional_persona` sibling,
    // an admin with the resolved management grant (or the always-on core)
    // can call it without a fresh human approval each time.
    #[test]
    fn list_provisional_personas_does_not_always_escalate() {
        use polyc_capability::{
            CallPolicy, GateOutcome, GrantPolicy, TaintState, decide, granted_capabilities,
        };
        let specs = all_builtin_specs();
        let required = required_for_builtin(provisional_persona::LIST_PROVISIONAL_PERSONAS, &specs);
        assert!(
            !required.contains(Capability::RevokeAccess)
                && !required.contains(Capability::GrantAccess)
                && !required.contains(Capability::ManageAdmin),
            "list_provisional_personas must not require a never-granted marker: {required:?}"
        );
        // With the management grant resolved (clean taint), it composes and
        // executes rather than escalating.
        let granted = granted_capabilities(GrantPolicy::default(), TaintState::Clean);
        let out = decide(
            required,
            granted,
            &CallPolicy::default(),
            provisional_persona::LIST_PROVISIONAL_PERSONAS,
        );
        assert!(
            !matches!(out, GateOutcome::Escalate { .. }),
            "list_provisional_personas should not always escalate, got {out:?}"
        );
    }

    // #592 acceptance: the CI half of the classification lint — every
    // built-in spec classifies out of the privileged bucket. If this fails, a
    // built-in gained a spec without annotations or an origin mapping.
    #[test]
    fn every_builtin_spec_classifies_out_of_the_privileged_bucket() {
        assert_eq!(unclassified_builtins(), Vec::<String>::new());
        assert_builtins_classified();
    }

    #[test]
    fn floor_pins_the_fetchers_regardless_of_owner_claims() {
        assert_eq!(
            floor_requirements("web_fetch"),
            set(&[Capability::ArbitraryEgress])
        );
        assert_eq!(
            floor_requirements("paid_fetch"),
            set(&[Capability::ArbitraryEgress, Capability::MutateExternal])
        );
        assert_eq!(floor_requirements("file_read"), CapabilitySet::EMPTY);
        assert_eq!(floor_requirements(""), CapabilitySet::EMPTY);
    }

    // #1660: ask_question classifies as a minimal-capability local-sandbox
    // built-in — it never reads or mutates anything outside the turn loop's
    // own pause/resume path, so it must never require the fail-closed
    // privileged set, and (being read-only) requires only `LocalRead`.
    #[test]
    fn ask_question_classifies_as_local_sandbox_with_minimal_capability() {
        assert_eq!(
            builtin_origin(ask_question::TOOL_NAME),
            Some(ToolOrigin::LocalSandbox)
        );
        assert_eq!(
            required_for_spec(&ask_question::spec()),
            set(&[Capability::LocalRead]),
            "a read-only local-sandbox tool requires only LocalRead, never the \
             fail-closed privileged set"
        );
    }

    // #1226: the native web-search-grounding primitive isn't a ToolSpec, so it
    // can't classify through `required_for_builtin` like every other name —
    // this pins its requirement directly, and that `floor_requirements` agrees.
    #[test]
    fn native_search_grounding_requires_arbitrary_egress() {
        assert_eq!(
            native_search_grounding_requirements(),
            set(&[Capability::ArbitraryEgress])
        );
        assert_eq!(
            floor_requirements(web::NATIVE_SEARCH_GROUNDING),
            set(&[Capability::ArbitraryEgress])
        );
    }

    // #1137 (extended by `#1139` Decision A, `#1599`, and `#1494`): the
    // canonical management-family list spans exactly the eleven families the
    // harness proxies through the control plane, and nothing outside them.
    #[test]
    fn management_all_spans_exactly_the_eleven_proxied_families() {
        // Independent hand-written expectation (review finding on #1137):
        // re-chaining the same families' `ALL` slices here (as the positive
        // half used to) can't catch drift — that expression is
        // BYTE-IDENTICAL to `management::ALL`'s own definition, so adding,
        // removing, or renaming a family or tool moves both sides together
        // and the test still passes. Spelling out the literal names instead
        // means a real change to `management::ALL` breaks this test.
        let mut expected = vec![
            "demote",
            // #1599: the disposable-test-identity cleanup pair — a narrower
            // `revoke` (one identity, not the whole persona) and its
            // provisional-only tombstone sibling.
            "delete_provisional_persona",
            "invite",
            "link_email",
            // The read-only report over what invite/revoke/demote change.
            // Management-family (explicit envelope, never default-on) even
            // though it only reads, because the roster it reads is the same
            // first-party state those three mutate.
            list_admins::TOOL_NAME,
            "list_provisional_personas",
            // #1139 Decision A: a durable write into a persona's memory
            // partition is a management-family mutation, not a default-on
            // read ⇒ explicit envelope, same as the families below.
            "memory_write",
            // The recall read joins its own family's envelope rather than the
            // default-on `conversation` family: persona memory spans
            // conversations, so whether an agent may read it back is a grant
            // decision, exactly as `list_admins` is for the roster.
            memory::MEMORY_RECALL,
            "revoke",
            // #1494: the authorization-gated routine inspection every routine
            // lifecycle mutation depends on (INV-RL4's minting side) — joins
            // the management family rather than defaulting on, the same
            // treatment `wallet_roster` gets.
            routine::ROUTINE_LIST,
            // #1497: the tracer-bullet create verb — joins the same family,
            // the same way `memory_write` does, as a first-party mutation
            // rather than a never-granted-capability escalation (its OWN
            // spec's intrinsic `needs_approval` is what always pauses it).
            routine::ROUTINE_CREATE,
            // #1495: the mutation trio — pause/resume are deliberately
            // UNGATED (no `needs_approval`, immediate effect); `delete`
            // mirrors `routine_create`'s always-approval-gated posture. All
            // three are first-party mutations over this deployment's own
            // `Routine` CRs, admin- and observation-handle-gated at
            // execution, same as `routine_create`/`routine_list`.
            routine::ROUTINE_PAUSE,
            routine::ROUTINE_RESUME,
            routine::ROUTINE_DELETE,
            // #1498: the sixth verb — an admin's one-shot test fire, gated
            // and approval-confirmed the same way `routine_delete` is, but a
            // DISPATCH rather than a CR mutation.
            routine::ROUTINE_FIRE,
            // #1805: the seventh verb — mints a caller-owned copy of an
            // existing routine's schedule and prompt, approval-confirmed the
            // same way `routine_create` is (a duplicate is a brand-new CR,
            // exactly as durable to create as the original was).
            routine::ROUTINE_DUPLICATE,
            // #1806: the eighth verb — flips a routine's sharing between
            // public and private after creation. Unlike the mutation trio,
            // OWNER-only (admin status never substitutes): whether to open a
            // routine's definition to other members is the owner's call.
            // Approval-gated and observation-handle-gated the same way
            // `routine_create`/`routine_delete`/`routine_fire` are.
            routine::ROUTINE_SET_SCOPE,
            // POLY-32: mint a grant from a recorded fire denial, end a
            // standing grant, and run a routine's setup dispatch again as a
            // repeatable "run now, attended" operation. Owner-gated the same
            // way `routine_fire`/`routine_set_scope` are.
            routine::ROUTINE_ALLOW_DENIAL,
            routine::ROUTINE_REVOKE_GRANT,
            routine::ROUTINE_REFIRE_ATTENDED,
            // #1599: admin-gated, targets any persona's identity — distinct
            // from the self-service `unlink_self` below.
            "unlink_identity",
            // Consolidated self-service unlink (post-incident fix): removes
            // the caller's OWN linked email or wallet by `target`, replacing
            // the former separate `unlink_email`/`wallet_unlink` tools.
            unlink_self::TOOL_NAME,
            "wallet_history",
            // PRD #1039 / TIP-1022: a read like the other wallet tools above, but
            // part of the wallet family, which is management-gated as a whole
            // (unlike the always-on `history` family) — so it joins them here too.
            "wallet_deposit_address",
            "wallet_link",
            "wallet_roster",
            "wallet_set_policy",
            "wallet_status",
            "wallet_update_limit",
        ];
        expected.sort_unstable();
        let mut actual: Vec<&str> = management::ALL.iter().copied().collect();
        actual.sort_unstable();
        assert_eq!(
            actual, expected,
            "management::ALL must span exactly these 28 names across the eleven \
             proxied families (wallet, email_link, invite, revoke, demote, \
             list_admins, memory, unlink_identity, unlink_self, \
             provisional_persona, routine) — no more, no less"
        );
        for name in [
            "shell_exec",
            "file_read",
            "web_fetch",
            "paid_fetch",
            "peer_call",
        ]
        .into_iter()
        .chain(conversation::ALL.iter().copied())
        {
            assert!(
                !management::is_management_builtin(name),
                "{name} is not a management built-in — the coding core, fetchers, \
                 the own-conversation read family, and peer delegation default \
                 on and are not grant-gated the same way"
            );
        }
    }

    /// The own-conversation read family defaults ON, exactly like `peer_call`.
    ///
    /// The management envelope exists for tools that mutate first-party state
    /// or grant/revoke access; these five read, and read only the conversation
    /// the caller is already in. Pinned against the shared admission predicate
    /// both the harness's advertisement composition and the control plane's
    /// execution re-check consult, because a name that silently landed in
    /// `management` would compose only for a turn whose grant named it — which
    /// is how this surface's earlier silent-unreachability regressions looked
    /// from the outside.
    #[test]
    fn the_own_conversation_read_family_defaults_on() {
        for name in conversation::ALL {
            assert!(
                !management::is_management_builtin(name),
                "{name} must not be a management built-in"
            );
            assert!(
                crate::mcp_client::builtin_admits(name, None, &[]),
                "{name} must compose for a turn that carried no grant resolution"
            );
            assert!(
                crate::mcp_client::builtin_admits(name, Some(&[(*name).to_owned()]), &[]),
                "{name} must compose when a grant names it explicitly"
            );
            assert!(
                !crate::mcp_client::builtin_admits(name, Some(&["something_else".to_owned()]), &[]),
                "{name} must still honor an explicit allowlist that omits it"
            );
        }
    }

    /// `memory_recall` is the deliberate INVERSE of the family above: it never
    /// defaults on.
    ///
    /// A recall reaches a persona's memory partition, which spans every
    /// conversation that persona has had — so unlike the own-conversation
    /// reads, whether an agent may read it back at all is a grant decision.
    /// Membership in `memory::ALL` is what puts it in `management::ALL`, and
    /// `builtin_admits` is what turns that into "an unset `builtinTools`
    /// admits nothing". Pinned here rather than left to the chain, because the
    /// failure is silent in the safe direction only once: dropping the name
    /// from `memory::ALL` would make an ungranted agent silently able to read
    /// a person's notes.
    #[test]
    fn memory_recall_never_defaults_on() {
        assert!(
            management::is_management_builtin(memory::MEMORY_RECALL),
            "recall must sit in the management envelope, not the default-on read family"
        );
        assert!(
            !crate::mcp_client::builtin_admits(memory::MEMORY_RECALL, None, &[]),
            "a turn that carried no grant resolution must not compose memory_recall"
        );
        assert!(
            crate::mcp_client::builtin_admits(
                memory::MEMORY_RECALL,
                Some(&[memory::MEMORY_RECALL.to_owned()]),
                &[]
            ),
            "an explicit grant is what makes it exist for an agent"
        );
        assert_eq!(
            builtin_origin(memory::MEMORY_RECALL),
            Some(ToolOrigin::FirstParty),
            "a read of the caller's own memory through the control plane"
        );
        assert_eq!(
            builtin_requirements(memory::MEMORY_RECALL),
            Some(&[][..]),
            "a read of already-recorded notes needs nothing from this deployment's config"
        );
    }

    // #1415 acceptance: every real built-in spec resolves a requirement list
    // (possibly empty) — the CI half of the fail-closed lint.
    #[test]
    fn every_builtin_spec_resolves_its_requirements() {
        assert_eq!(unresolved_builtin_requirements(), Vec::<String>::new());
        assert_builtin_requirements_resolved();
    }

    // #1415: the tools this repo's #1412 incident named — `wallet_link`,
    // `link_email`, `paid_fetch` — carry the exact deployment prerequisite
    // the design doc pins them to.
    #[test]
    fn builtin_requirements_matches_the_1412_incident_tools() {
        assert_eq!(
            builtin_requirements(wallet::WALLET_LINK),
            Some(&[Requirement::CeremonyPage(Ceremony::WalletLink)][..])
        );
        assert_eq!(
            builtin_requirements(wallet::WALLET_UPDATE_LIMIT),
            Some(&[Requirement::CeremonyPage(Ceremony::WalletLink)][..]),
            "shares the same deployed ceremony page as wallet_link"
        );
        assert_eq!(
            builtin_requirements(email_link::LINK_EMAIL),
            Some(
                &[
                    Requirement::CeremonyPage(Ceremony::EmailMagicLink),
                    Requirement::MailRelay
                ][..]
            )
        );
        assert_eq!(
            builtin_requirements(paid_fetch::TOOL_NAME),
            Some(&[Requirement::PaymentsProxy][..])
        );
    }

    // #1415: a read-only report over already-minted state carries no
    // requirement — it stays advertised even when the matching mint is
    // unconfigured, mirroring how `wallet_status`/`list_admins` already stay
    // advertised regardless of the management grant shape.
    #[test]
    fn read_only_reports_carry_no_requirement() {
        for name in [
            wallet::WALLET_STATUS,
            wallet::WALLET_HISTORY,
            wallet::WALLET_ROSTER,
            wallet::WALLET_DEPOSIT_ADDRESS,
            wallet::WALLET_SET_POLICY,
        ] {
            assert_eq!(
                builtin_requirements(name),
                Some(&[][..]),
                "{name} must carry no deployment requirement"
            );
        }
    }

    // #1415 fail-closed: a name no built-in family owns resolves to `None`,
    // mirroring `builtin_origin`'s own unknown-name convention.
    #[test]
    fn builtin_requirements_fails_closed_on_an_unknown_name() {
        assert_eq!(builtin_requirements("no_such_tool"), None);
    }
}