polyc_capability/lib.rs
1//! Capability taxonomy, derivation functions, and the pure gate decision
2//! engine (`#587`, `#591`).
3//!
4//! One tool call *requires* a set of [`Capability`]s (derived from its spec's
5//! MCP-style annotations plus its registry provenance) and is *granted* a set
6//! (derived from the agent's policy plus the conversation's provenance/taint
7//! state at that moment). [`decide`] compares them and returns the single
8//! [`GateOutcome`] for the call — the one decision path that replaces the
9//! previous OR of an argument-aware policy check, a sandbox-denial escalation,
10//! and a runtime "untrusted content + egress" override.
11//!
12//! The containment invariants live here as pure logic, testable exhaustively:
13//!
14//! - Untrusted content in context removes [`Capability::ArbitraryEgress`]
15//! **and** [`Capability::MutateExternal`] from the granted set — a message
16//! body or an issue title carries attacker-steered bytes out as surely as a
17//! fetch does.
18//! - A tool whose spec cannot be classified requires the full privileged set
19//! ([`CapabilitySet::all`]) — fail closed.
20//! - The model is monotonic: under a fixed policy, adding taint never adds a
21//! capability.
22//!
23//! Everything here is a pure function over its inputs. No gate wiring, no IO,
24//! no clock: the executor surface (`#592`) derives the inputs and the agent's
25//! per-call gate (`#593`) is a thin adapter over [`decide`].
26
27use polyc_llm::ToolSpec;
28
29// ── Capability + set ─────────────────────────────────────────────────────────
30
31/// One thing a tool call can do — the unit of the containment model.
32///
33/// The taxonomy is deliberately small and rarely changes. Adding a member
34/// means extending this enum and the two derivation functions
35/// ([`required_capabilities`], [`granted_capabilities`]); the decision engine
36/// ([`decide`]) operates on sets generically and never needs to change (a
37/// pinned test demonstrates this).
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39#[repr(u8)]
40pub enum Capability {
41 /// Read state confined to the conversation's sandbox (workspace files).
42 LocalRead = 1,
43 /// Mutate state confined to the conversation's sandbox (workspace writes,
44 /// sandboxed shell). Destructive *inside the box* is still local.
45 LocalWrite = 1 << 1,
46 /// Call an operator-registered connector endpoint (or a first-party
47 /// control-plane service) — a fixed destination the operator vouched for,
48 /// carrying only model-authored arguments. Taint never revokes this.
49 FixedConnectorRead = 1 << 2,
50 /// Send bytes to a model-controlled external destination — the built-in
51 /// web/paid fetchers. The classic exfiltration channel.
52 ArbitraryEgress = 1 << 3,
53 /// Perform a side effect outside the sandbox: mutate external state,
54 /// send a message, file an issue, spend money. An external mutation
55 /// carries model-authored bytes to destinations an attacker may read,
56 /// so it is an egress channel in effect even when the destination is
57 /// fixed.
58 MutateExternal = 1 << 4,
59 /// Grant a third party access to the system itself — the admin invite
60 /// (`#700`). Deliberately held OUT of [`Self::ALL`], so
61 /// it is never in [`CapabilitySet::all`], never in the default grant, and —
62 /// because [`Self::from_name`] only recognizes members of [`Self::ALL`] —
63 /// unnameable in operator config: no policy or wire input can ever seed it
64 /// into a granted set. A tool that requires it therefore always exceeds its
65 /// granted set and always escalates to a human, in every taint state and
66 /// policy mode. This is the structural mechanism behind "an access-grant is
67 /// never autonomous — a person always confirms the exact invitee".
68 GrantAccess = 1 << 5,
69 /// Remove a third party's access to the system itself — the admin
70 /// de-admission (`#713`), the offboarding sibling of [`Self::GrantAccess`].
71 /// Held OUT of [`Self::ALL`] for the identical reason: never in
72 /// [`CapabilitySet::all`], never in the default grant, and unnameable in
73 /// operator config ([`Self::from_name`] only recognizes [`Self::ALL`]
74 /// members), so a tool requiring it always exceeds its granted set and
75 /// always escalates to a human, in every taint state and policy mode. This
76 /// is the structural mechanism behind "a removal is never autonomous — a
77 /// person always confirms the exact person being removed".
78 RevokeAccess = 1 << 6,
79 /// Take away a persona's ADMIN ROLE — the `demote` tool (`#715`), and the
80 /// sibling that completes the admin-management set alongside
81 /// [`Self::GrantAccess`]/[`Self::RevokeAccess`]. Held OUT of [`Self::ALL`]
82 /// for the identical reason: never in [`CapabilitySet::all`], never in the
83 /// default grant, and unnameable in operator config ([`Self::from_name`]
84 /// only recognizes [`Self::ALL`] members), so a tool requiring it always
85 /// exceeds its granted set and always escalates to a human, in every
86 /// taint state and policy mode. This is the structural mechanism behind
87 /// "an admin's role is never removed autonomously — a person always
88 /// confirms exactly whose role is being taken away".
89 ///
90 /// This occupies the last bit `u8` can hold (`1 << 7`); the NEXT
91 /// never-granted marker added to this taxonomy needs `CapabilitySet` (and
92 /// this enum's `#[repr]`) widened from `u8` to `u16` first.
93 ManageAdmin = 1 << 7,
94}
95
96impl Capability {
97 /// Every *grantable* member of the taxonomy, in declaration order.
98 ///
99 /// [`Self::GrantAccess`] and [`Self::RevokeAccess`] are deliberately
100 /// absent: they are the never-granted markers (see their docs), so they
101 /// are excluded from [`CapabilitySet::all`], the default grant, name
102 /// parsing ([`Self::from_name`]), and set iteration — everything driven
103 /// off this array operates only over the grantable set.
104 pub const ALL: [Self; 5] = [
105 Self::LocalRead,
106 Self::LocalWrite,
107 Self::FixedConnectorRead,
108 Self::ArbitraryEgress,
109 Self::MutateExternal,
110 ];
111
112 /// Stable kebab-case name, used in signed approval coverage and telemetry.
113 /// Inverse of [`Self::from_name`].
114 #[must_use]
115 pub const fn as_str(self) -> &'static str {
116 match self {
117 Self::LocalRead => "local-read",
118 Self::LocalWrite => "local-write",
119 Self::FixedConnectorRead => "fixed-connector-read",
120 Self::ArbitraryEgress => "arbitrary-egress",
121 Self::MutateExternal => "mutate-external",
122 Self::GrantAccess => "grant-access",
123 Self::RevokeAccess => "revoke-access",
124 Self::ManageAdmin => "manage-admin",
125 }
126 }
127
128 /// Parse a stable kebab-case name; `None` for anything unrecognized so a
129 /// caller reading operator config fails toward granting nothing.
130 #[must_use]
131 pub fn from_name(name: &str) -> Option<Self> {
132 Self::ALL.into_iter().find(|c| c.as_str() == name)
133 }
134}
135
136/// A set of [`Capability`]s. Small, `Copy`, and closed under the usual set
137/// algebra — the decision engine works only through these operations.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
139pub struct CapabilitySet(u8);
140
141/// Scoping/audit name for the LLM provider's native web-search-grounding
142/// primitive (issue `#1226`).
143///
144/// A request-level flag the provider turns into its own built-in search tool
145/// entry mid-generation, never a model-invoked `tool_use` call. Lives here
146/// (rather than `polyc_tools`, where every other tool name lives) because
147/// both `polyc_agent` (the per-step gate that consults it) and `polyc_tools`
148/// (the `builtinTools` scoping check) need the same literal and neither crate
149/// may depend on the other.
150pub const NATIVE_SEARCH_GROUNDING: &str = "web_search_grounding";
151
152impl CapabilitySet {
153 /// The empty set.
154 pub const EMPTY: Self = Self(0);
155
156 /// The capabilities the provider's native web-search-grounding primitive
157 /// ([`NATIVE_SEARCH_GROUNDING`]) requires.
158 ///
159 /// The classic exfiltration channel, the same floor as the built-in web
160 /// fetchers (`web_fetch`, `paid_fetch`). Unlike every other tool, this
161 /// primitive is never a [`polyc_llm::ToolSpec`] the model calls
162 /// explicitly, so there is no per-call `tool_use` for the ordinary
163 /// classification path (`required_capabilities`) to inspect — the call
164 /// site that decides whether to turn grounding on for a step compares
165 /// this constant against [`granted_capabilities`] directly, via the same
166 /// [`decide`] every real tool call goes through.
167 #[must_use]
168 pub const fn native_search_grounding_requirements() -> Self {
169 Self::of(Capability::ArbitraryEgress)
170 }
171
172 /// The full privileged set — every member of the taxonomy. This is the
173 /// fail-closed requirement for an unclassifiable tool.
174 #[must_use]
175 pub const fn all() -> Self {
176 let mut bits = 0u8;
177 let mut i = 0;
178 while i < Capability::ALL.len() {
179 bits |= Capability::ALL[i] as u8;
180 i += 1;
181 }
182 Self(bits)
183 }
184
185 /// The set containing exactly `capability`.
186 #[must_use]
187 pub const fn of(capability: Capability) -> Self {
188 Self(capability as u8)
189 }
190
191 /// This set plus `capability`.
192 #[must_use]
193 pub const fn with(self, capability: Capability) -> Self {
194 Self(self.0 | capability as u8)
195 }
196
197 /// Whether `capability` is in this set.
198 #[must_use]
199 pub const fn contains(self, capability: Capability) -> bool {
200 self.0 & capability as u8 != 0
201 }
202
203 /// Whether this set has no members.
204 #[must_use]
205 pub const fn is_empty(self) -> bool {
206 self.0 == 0
207 }
208
209 /// Whether every member of this set is also in `other`.
210 #[must_use]
211 pub const fn is_subset_of(self, other: Self) -> bool {
212 self.0 & !other.0 == 0
213 }
214
215 /// Set union.
216 #[must_use]
217 pub const fn union(self, other: Self) -> Self {
218 Self(self.0 | other.0)
219 }
220
221 /// Set intersection.
222 #[must_use]
223 pub const fn intersection(self, other: Self) -> Self {
224 Self(self.0 & other.0)
225 }
226
227 /// Set difference: the members of this set that are not in `other`.
228 #[must_use]
229 pub const fn difference(self, other: Self) -> Self {
230 Self(self.0 & !other.0)
231 }
232
233 /// The members of this set, in [`Capability::ALL`] order.
234 pub fn iter(self) -> impl Iterator<Item = Capability> {
235 Capability::ALL
236 .into_iter()
237 .filter(move |c| self.contains(*c))
238 }
239
240 /// Build a set from stable kebab-case names, such as signed approval
241 /// coverage. Unrecognized names are NOT granted — they are returned
242 /// separately so the caller can
243 /// log them — which is the fail-closed direction: a typo in operator
244 /// config grants nothing rather than something unintended.
245 pub fn from_names<'a, I: IntoIterator<Item = &'a str>>(names: I) -> (Self, Vec<String>) {
246 let mut set = Self::EMPTY;
247 let mut unknown = Vec::new();
248 for name in names {
249 match Capability::from_name(name) {
250 Some(c) => set = set.with(c),
251 None => unknown.push(name.to_owned()),
252 }
253 }
254 (set, unknown)
255 }
256
257 /// The stable kebab-case names of this set's members, in
258 /// [`Capability::ALL`] order — the inverse of [`Self::from_names`].
259 #[must_use]
260 pub fn names(self) -> Vec<&'static str> {
261 self.iter().map(Capability::as_str).collect()
262 }
263}
264
265impl FromIterator<Capability> for CapabilitySet {
266 fn from_iter<I: IntoIterator<Item = Capability>>(iter: I) -> Self {
267 iter.into_iter().fold(Self::EMPTY, Self::with)
268 }
269}
270
271/// The capabilities that untrusted content in context revokes: both channels
272/// that carry model-authored bytes to destinations an attacker may read.
273///
274/// This is the single, tested home of the containment rule that used to be
275/// the "lethal trifecta override": [`Capability::ArbitraryEgress`] (a fetch to
276/// a model-chosen destination) **and** [`Capability::MutateExternal`] (a
277/// message body or issue field is an exfiltration channel the egress rule
278/// alone would miss).
279pub const TAINT_REVOKED: CapabilitySet =
280 CapabilitySet::of(Capability::ArbitraryEgress).with(Capability::MutateExternal);
281
282// ── Requirement derivation ────────────────────────────────────────────────────
283
284/// Where a tool comes from — the registry-provenance half of classification.
285///
286/// Trust scoping is the security-load-bearing part: taint-immune
287/// classification ([`Capability::FixedConnectorRead`]) is earned only by
288/// operator registration ([`ToolOrigin::RegisteredConnector`] /
289/// [`ToolOrigin::FirstParty`]) — never by a connector's self-declared
290/// annotation hints alone. This is what the MCP specification normatively
291/// requires: clients MUST treat tool annotations as untrusted unless the
292/// server is trusted.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum ToolOrigin {
295 /// A process-local built-in, such as a coding tool. This origin describes
296 /// local file authority. It does not prove operating-system network
297 /// isolation. `shell_exec` can use routes allowed by the pod policy today;
298 /// issue `#2508` owns alignment with this taxonomy and D6's route-removal
299 /// checklist.
300 LocalSandbox,
301 /// A built-in fetcher (the web/paid fetchers): brokered on the trusted
302 /// side to a model-controlled destination.
303 Fetcher,
304 /// A built-in that reads or acts on the caller's own first-party state via
305 /// the control plane (the history and wallet families): a fixed,
306 /// operator-owned destination.
307 FirstParty,
308 /// A built-in that grants a third party access to the system itself — the
309 /// admin invite (`#700`). Classified apart from [`Self::FirstParty`]
310 /// because it requires [`Capability::GrantAccess`], the never-granted
311 /// marker, so it always escalates to a human before anything is minted: the
312 /// agent can only ever PROPOSE an invite, never grant access on its own.
313 AccessGrant,
314 /// A built-in that removes a third party's access to the system itself —
315 /// the admin de-admission (`#713`), the offboarding sibling of
316 /// [`Self::AccessGrant`]. Requires [`Capability::RevokeAccess`], the
317 /// never-granted marker, so it always escalates to a human before anything
318 /// is removed: the agent can only ever PROPOSE a removal, never de-admit
319 /// anyone on its own.
320 AccessRevoke,
321 /// A built-in that takes away a persona's ADMIN ROLE — the `demote`
322 /// tool (`#715`), the sibling that completes the admin-management set
323 /// alongside [`Self::AccessGrant`]/[`Self::AccessRevoke`]. Requires
324 /// [`Capability::ManageAdmin`], the never-granted marker, so it always
325 /// escalates to a human before anyone's admin role changes: the agent
326 /// can only ever PROPOSE a demote, never remove anyone's admin role on
327 /// its own.
328 AdminManage,
329 /// A connector tool whose server the operator registered (registry
330 /// provenance, e.g. the `ToolService` registry). Its annotations are
331 /// load-bearing inputs because the operator vouched for the server.
332 RegisteredConnector,
333 /// Anything else: an unregistered server's self-declared tool, an unknown
334 /// name, an unannotated spec. Fails closed to the privileged set.
335 Unknown,
336}
337
338/// The classification inputs for one tool: its spec's MCP-style annotations
339/// plus its registry provenance.
340///
341/// Built by the executor surface (`#592`) — [`ToolProfile::for_spec`] reads
342/// the annotations off the spec, and the executor supplies the origin from
343/// what it knows about the tool's source.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct ToolProfile {
346 /// Registry provenance — see [`ToolOrigin`].
347 pub origin: ToolOrigin,
348 /// MCP `readOnlyHint`: the tool does not modify its environment.
349 pub read_only: bool,
350 /// MCP `destructiveHint`: the tool may perform irreversible or
351 /// side-effecting changes.
352 pub destructive: bool,
353 /// MCP `openWorldHint`: the tool's RESULT may carry content of
354 /// uncontrolled provenance. An ingestion-source property: it drives
355 /// taint, not the required set (a registered connector's open-world read
356 /// still dials only its fixed, operator-vouched endpoint).
357 pub open_world: bool,
358}
359
360impl ToolProfile {
361 /// Read the classification annotations off `spec`, with the
362 /// executor-supplied registry provenance.
363 #[must_use]
364 pub const fn for_spec(spec: &ToolSpec, origin: ToolOrigin) -> Self {
365 Self {
366 origin,
367 read_only: spec.read_only,
368 destructive: spec.destructive,
369 open_world: spec.open_world,
370 }
371 }
372}
373
374/// Derive the capabilities a tool call requires from its profile — the
375/// spec's existing annotations plus registry provenance. No new hand-written
376/// per-tool metadata.
377///
378/// The mapping (see the `#587` design):
379///
380/// - sandbox-confined built-in ⇒ local read (+ local write unless read-only —
381/// destructive *inside the box* is still local);
382/// - built-in fetcher ⇒ arbitrary egress (+ external mutation when
383/// destructive, e.g. a paying fetch);
384/// - first-party / operator-registered connector ⇒ fixed-connector read
385/// (+ external mutation unless read-only and non-destructive);
386/// - access-grant (the admin invite) ⇒ the never-granted
387/// [`Capability::GrantAccess`], so it always escalates to a human;
388/// - unknown / unclassifiable ⇒ the full privileged set, fail closed: an
389/// unknown tool never slips through un-gated.
390///
391/// `open_world` is deliberately not consulted: it marks an ingestion source
392/// (drives taint when the result enters context), not an outbound
393/// capability.
394#[must_use]
395pub const fn required_capabilities(profile: ToolProfile) -> CapabilitySet {
396 match profile.origin {
397 ToolOrigin::LocalSandbox => {
398 if profile.read_only {
399 CapabilitySet::of(Capability::LocalRead)
400 } else {
401 CapabilitySet::of(Capability::LocalRead).with(Capability::LocalWrite)
402 }
403 }
404 ToolOrigin::Fetcher => {
405 if profile.destructive {
406 CapabilitySet::of(Capability::ArbitraryEgress).with(Capability::MutateExternal)
407 } else {
408 CapabilitySet::of(Capability::ArbitraryEgress)
409 }
410 }
411 ToolOrigin::FirstParty | ToolOrigin::RegisteredConnector => {
412 if profile.read_only && !profile.destructive {
413 CapabilitySet::of(Capability::FixedConnectorRead)
414 } else {
415 CapabilitySet::of(Capability::FixedConnectorRead).with(Capability::MutateExternal)
416 }
417 }
418 // The admin invite: it requires only the never-granted
419 // `GrantAccess`, so the gate escalates it in EVERY taint state and
420 // policy mode. The annotations are not consulted — proposing an
421 // access-grant always needs a person, regardless of how the tool
422 // declares itself. The actual mint's first-party mutation is enforced
423 // control-plane-side, after approval, not modeled as the agent call's
424 // granted capability.
425 ToolOrigin::AccessGrant => CapabilitySet::of(Capability::GrantAccess),
426 // The admin de-admission (#713): the offboarding sibling of the admin
427 // invite above — same reasoning, same never-granted-marker mechanism.
428 ToolOrigin::AccessRevoke => CapabilitySet::of(Capability::RevokeAccess),
429 // The admin demote (#715): completes the admin-management set —
430 // same reasoning, same never-granted-marker mechanism.
431 ToolOrigin::AdminManage => CapabilitySet::of(Capability::ManageAdmin),
432 ToolOrigin::Unknown => CapabilitySet::all(),
433 }
434}
435
436/// Clamp a re-declared profile so a connector's runtime annotation change can
437/// only ever ADD required capabilities (`#598`).
438///
439/// A connector may re-declare its tools mid-conversation (list-changed). A
440/// re-declaration never removes a requirement and never earns taint-immunity
441/// at runtime: the merged profile keeps the *less* trusted value of each
442/// annotation (loses `read_only` if either side lost it, keeps `destructive`
443/// and `open_world` if either side had it). The origin is NOT an input from
444/// the re-declaration at all — registry provenance is an operator act the
445/// executor derives, never something a connector can assert about itself —
446/// so the merged profile keeps the origin the conversation started with.
447/// The result is pinned monotonic by test:
448/// `required_capabilities(monotonic_redeclaration(old, new))` is always a
449/// superset of `required_capabilities(old)`.
450#[must_use]
451pub const fn monotonic_redeclaration(old: ToolProfile, new: ToolProfile) -> ToolProfile {
452 ToolProfile {
453 origin: old.origin,
454 read_only: old.read_only && new.read_only,
455 destructive: old.destructive || new.destructive,
456 open_world: old.open_world || new.open_world,
457 }
458}
459
460// ── Deployment viability (#1415) ────────────────────────────────────────────────
461
462/// A browser-facing ceremony page a built-in mints a one-time link to.
463///
464/// Closed and small on purpose: only ceremonies that actually gate a
465/// chat-callable built-in belong here. `wallet-passkey-login` (the web app's
466/// own sign-in) is a real deployment ceremony too, but it backs no built-in
467/// tool call — it is a pure browser flow a person reaches directly, never
468/// something the model mints a link to — so adding it here would leave a
469/// [`Requirement`] variant no built-in ever resolves to, which the harness's
470/// dead-variant guard exists to catch.
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
472pub enum Ceremony {
473 /// The wallet-link card (`POLYCHROME_WALLET_LINK_URL`): mints the link a
474 /// caller signs to attach an external wallet, and the shared page the
475 /// spending-limit-update and hard-revoke ceremonies reuse.
476 WalletLink,
477 /// The email-verification magic-link page (`POLYCHROME_EMAIL_LINK_URL`):
478 /// mints the link a caller clicks to verify an email address.
479 EmailMagicLink,
480}
481
482/// A deployment prerequisite a built-in's calls depend on.
483///
484/// A closed, exhaustively matchable taxonomy of the STATIC, versioned facts a
485/// built-in family needs configured before any call of its own can do
486/// anything, sibling to [`ToolOrigin`] in the same "static shape of the
487/// built-in surface" sense. Carries only the fact, never remedy text: the
488/// copy a person reads about a missing prerequisite belongs to the surface
489/// that renders it (an approval card, a status tool), not to this taxonomy.
490///
491/// Extending the taxonomy means adding a variant here and teaching
492/// `polyc_tools::capability::builtin_requirements` (`crates/tools`) which
493/// built-ins need it, and [`DeploymentCapabilities::is_viable`] which
494/// deployment fact answers it — the harness's `builtin_surface_guard` fails
495/// closed if either side is left out (a requirement no built-in resolves to,
496/// or a built-in a requirement can't classify).
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
498pub enum Requirement {
499 /// A usable outbound mail relay (credentials/token valid, not merely a
500 /// relay URL set — a missing URL alone falls back to a hosted default).
501 /// `link_email` needs this to actually deliver a verification message.
502 MailRelay,
503 /// A configured browser-facing ceremony page — see [`Ceremony`].
504 CeremonyPage(Ceremony),
505 /// The outbound-payments proxy: a settlement currency and a way to sign
506 /// (a deployment env signer or a caller's own delegated wallet key).
507 /// `paid_fetch` needs this to ever send a payment.
508 PaymentsProxy,
509}
510
511impl Requirement {
512 /// Every concrete [`Requirement`] value, in declaration order — the
513 /// enumeration [`DeploymentCapabilities::viable_names`] and
514 /// [`Self::from_name`] iterate over, and the harness guard's
515 /// dead-variant check walks.
516 pub const ALL: [Self; 4] = [
517 Self::MailRelay,
518 Self::CeremonyPage(Ceremony::WalletLink),
519 Self::CeremonyPage(Ceremony::EmailMagicLink),
520 Self::PaymentsProxy,
521 ];
522
523 /// Stable kebab-case name, used on the wire
524 /// (`TurnInput.viable_requirements`) and as a telemetry label. Inverse of
525 /// [`Self::from_name`].
526 #[must_use]
527 pub const fn as_str(self) -> &'static str {
528 match self {
529 Self::MailRelay => "mail-relay",
530 Self::CeremonyPage(Ceremony::WalletLink) => "ceremony-page:wallet-link",
531 Self::CeremonyPage(Ceremony::EmailMagicLink) => "ceremony-page:email-magic-link",
532 Self::PaymentsProxy => "payments-proxy",
533 }
534 }
535
536 /// Parse a stable kebab-case name; `None` for anything unrecognized so a
537 /// caller reading the wire fails toward treating the requirement as
538 /// unmet rather than guessing.
539 #[must_use]
540 pub fn from_name(name: &str) -> Option<Self> {
541 Self::ALL.into_iter().find(|r| r.as_str() == name)
542 }
543}
544
545/// The deployment-configuration facts [`Requirement`]s are checked against.
546///
547/// Resolved ONCE at control-plane startup from the same `Option`/`Arc`
548/// configuration each ceremony/proxy already builds for its own use (never a
549/// second, independent env read that could drift from what the ceremony
550/// itself decided), mirroring `ConfiguredBackends` in the harness's
551/// `main.rs`: a struct of independent configuration facts, not states of one
552/// state machine — hence the flat bools below rather than a nested
553/// enum/state-machine shape.
554///
555/// Carried across the control-plane/harness wire as
556/// `TurnInput.viable_requirements` (the [`Requirement::as_str`] names this
557/// deployment satisfies) because the facts live in control-plane-only
558/// configuration (mail relay credentials, ceremony URLs, the payments
559/// signer) the harness sandbox cannot read for itself — the harness never
560/// resolves this struct locally; it reconstructs the viable subset with
561/// [`Self::from_names`] from the wire strings each turn.
562#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
563#[allow(clippy::struct_excessive_bools)] // four INDEPENDENT config facts (see doc above), not a state machine
564pub struct DeploymentCapabilities {
565 /// [`Requirement::MailRelay`] is met.
566 pub mail_relay: bool,
567 /// <code>[Requirement::CeremonyPage]([Ceremony::WalletLink])</code> is met.
568 pub wallet_link_ceremony: bool,
569 /// <code>[Requirement::CeremonyPage]([Ceremony::EmailMagicLink])</code> is met.
570 pub email_magic_link_ceremony: bool,
571 /// [`Requirement::PaymentsProxy`] is met.
572 pub payments_proxy: bool,
573}
574
575impl DeploymentCapabilities {
576 /// Every [`Requirement`] viable — the standalone/dev/test posture, and
577 /// the explicit choice a caller that genuinely does not care about
578 /// deployment viability (a test scoping only `builtin_allow`, the
579 /// in-process whole-conversation test transport) reaches for by name
580 /// instead of hand-listing every field `true`. NOT the type's
581 /// [`Default`] — [`Default`] stays fail-closed (nothing viable), so a
582 /// caller that forgets to thread the real wire-resolved value hides
583 /// every requirement-gated built-in instead of silently over-advertising
584 /// one whose deployment prerequisite is actually unmet.
585 #[must_use]
586 pub const fn all() -> Self {
587 Self {
588 mail_relay: true,
589 wallet_link_ceremony: true,
590 email_magic_link_ceremony: true,
591 payments_proxy: true,
592 }
593 }
594
595 /// Whether this deployment currently satisfies `requirement`.
596 #[must_use]
597 pub const fn is_viable(self, requirement: Requirement) -> bool {
598 match requirement {
599 Requirement::MailRelay => self.mail_relay,
600 Requirement::CeremonyPage(Ceremony::WalletLink) => self.wallet_link_ceremony,
601 Requirement::CeremonyPage(Ceremony::EmailMagicLink) => self.email_magic_link_ceremony,
602 Requirement::PaymentsProxy => self.payments_proxy,
603 }
604 }
605
606 /// Whether every member of `requirements` is viable — the join
607 /// `build_tool_executor` folds into `granted ∩ owned ∩ viable`. An empty
608 /// slice (a built-in with no deployment prerequisite) is always viable.
609 #[must_use]
610 pub fn all_viable(self, requirements: &[Requirement]) -> bool {
611 requirements.iter().all(|r| self.is_viable(*r))
612 }
613
614 /// The stable kebab-case names of every [`Requirement`] this deployment
615 /// satisfies, in [`Requirement::ALL`] order — what the control plane
616 /// puts on the wire. Inverse of [`Self::from_names`].
617 #[must_use]
618 pub fn viable_names(self) -> Vec<&'static str> {
619 Requirement::ALL
620 .into_iter()
621 .filter(|r| self.is_viable(*r))
622 .map(Requirement::as_str)
623 .collect()
624 }
625
626 /// Reconstruct from the wire's stable-name list (`TurnInput.viable_requirements`)
627 /// — the harness's side of [`Self::viable_names`]. An unrecognized name
628 /// (a newer control plane's requirement an older harness doesn't know)
629 /// is silently ignored rather than failing the turn: an unknown
630 /// requirement can never be satisfied by an older binary's `is_viable`
631 /// match anyway, so any built-in that needs it stays hidden either way.
632 #[must_use]
633 pub fn from_names<'a, I: IntoIterator<Item = &'a str>>(names: I) -> Self {
634 let mut caps = Self::default();
635 for name in names {
636 match Requirement::from_name(name) {
637 Some(Requirement::MailRelay) => caps.mail_relay = true,
638 Some(Requirement::CeremonyPage(Ceremony::WalletLink)) => {
639 caps.wallet_link_ceremony = true;
640 }
641 Some(Requirement::CeremonyPage(Ceremony::EmailMagicLink)) => {
642 caps.email_magic_link_ceremony = true;
643 }
644 Some(Requirement::PaymentsProxy) => caps.payments_proxy = true,
645 None => {}
646 }
647 }
648 caps
649 }
650}
651
652// ── Grant derivation ──────────────────────────────────────────────────────────
653
654/// Whether untrusted content is in the conversation's context at this gate
655/// decision.
656///
657/// The provenance (taint) input to grant derivation, computed from the
658/// durable seed OR the live transcript scan, never from the turn's own
659/// output.
660#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
661pub enum TaintState {
662 /// No untrusted content in context.
663 #[default]
664 Clean,
665 /// Untrusted content is in context: the granted set loses
666 /// [`TAINT_REVOKED`].
667 Tainted,
668}
669
670/// The agent's configured capability policy — the operator-controlled half of
671/// grant derivation.
672///
673/// The policy comes from cluster config (the Agent custom resource),
674/// unreachable from within a conversation or the request path.
675#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676pub struct GrantPolicy {
677 /// The capabilities the agent's policy grants on a clean context.
678 pub base: CapabilitySet,
679}
680
681impl Default for GrantPolicy {
682 /// Grant everything on a clean context.
683 fn default() -> Self {
684 Self {
685 base: CapabilitySet::all(),
686 }
687 }
688}
689
690/// Derive the capabilities granted to one gate decision from the agent's
691/// policy and the provenance state **at that moment**.
692///
693/// Recomputed per call, because taint can enter mid-turn and must revoke for
694/// the very next call.
695///
696/// The containment rule: taint present ⇒ [`TAINT_REVOKED`] (arbitrary egress
697/// AND external mutation) removed from the granted set. Monotonic under a fixed
698/// policy: adding taint never adds a capability (pinned by test).
699#[must_use]
700pub const fn granted_capabilities(policy: GrantPolicy, taint: TaintState) -> CapabilitySet {
701 match taint {
702 TaintState::Clean => policy.base,
703 TaintState::Tainted => policy.base.difference(TAINT_REVOKED),
704 }
705}
706
707// ── Decision engine ───────────────────────────────────────────────────────────
708
709/// An argument transform the argument-aware dispatch policy asked for, honored
710/// only when the call is otherwise allowed.
711#[derive(Debug, Clone, PartialEq, Eq, Default)]
712pub enum ArgTransform {
713 /// Run the call as proposed.
714 #[default]
715 None,
716 /// Run the call with these replacement arguments.
717 Rewrite(String),
718 /// Prepend this context as an internal-only note before the call runs.
719 InjectContext(String),
720}
721
722/// The per-call policy verdicts [`decide`] folds into the one outcome.
723///
724/// Carries the argument-aware dispatch decision plus the sandbox-escalation
725/// check, already evaluated against the call's arguments by the caller.
726#[derive(Debug, Clone, PartialEq, Eq, Default)]
727pub struct CallPolicy {
728 /// A hard policy veto with its reason: the call is blocked without a
729 /// human prompt and a human approval cannot satisfy it. Takes precedence
730 /// over everything else.
731 pub veto: Option<String>,
732 /// The argument-aware policy (or the tool's intrinsic gate) demands a
733 /// human decision for this call regardless of capabilities.
734 pub requires_human: bool,
735 /// The sandbox would deny this call before any side effect and the
736 /// deployment escalates such denials to a human instead of running into
737 /// the flat denial.
738 pub sandbox_escalation: bool,
739 /// The argument transform to honor when the call is allowed.
740 pub transform: ArgTransform,
741}
742
743/// The single unified gate result for one tool call — replaces both the
744/// argument-aware `ToolDecision` and the `needs_approval`/override booleans.
745#[derive(Debug, Clone, PartialEq, Eq)]
746pub enum GateOutcome {
747 /// Execute the call as proposed.
748 Allow,
749 /// Execute the call with rewritten arguments.
750 Modify(
751 /// The replacement arguments (JSON).
752 String,
753 ),
754 /// Prepend this context as an internal-only note, then execute.
755 InjectContext(
756 /// The note text.
757 String,
758 ),
759 /// Pause for a human decision.
760 Escalate {
761 /// Why, in plain language for the approval card. Empty for an
762 /// ordinary policy/sandbox gate (the edge renders its default
763 /// prompt); non-empty when capabilities are missing.
764 reason: String,
765 /// The required capabilities the call's granted set does not cover.
766 /// Empty when the escalation is a policy/sandbox gate rather than a
767 /// capability shortfall.
768 missing: CapabilitySet,
769 },
770 /// Block the call without a human prompt; the reason is surfaced to the
771 /// model as the tool result so it can adapt.
772 Deny(
773 /// The policy's reason.
774 String,
775 ),
776}
777
778impl GateOutcome {
779 /// Stable lowercase label for telemetry — one counter per gate outcome.
780 #[must_use]
781 pub const fn label(&self) -> &'static str {
782 match self {
783 Self::Allow => "allow",
784 Self::Modify(_) => "modify",
785 Self::InjectContext(_) => "inject_context",
786 Self::Escalate { .. } => "escalate",
787 Self::Deny(_) => "deny",
788 }
789 }
790}
791
792/// The one pure decision: compare what the call requires with what it is
793/// granted, under the argument-aware policy verdicts, and return the single
794/// [`GateOutcome`].
795///
796/// Precedence, pinned by test:
797///
798/// 1. hard policy veto ⇒ [`GateOutcome::Deny`];
799/// 2. required ⊄ granted ⇒ [`GateOutcome::Escalate`] carrying the missing
800/// set and a plain-language reason;
801/// 3. the policy demands a human (argument-aware gate or sandbox-denial
802/// escalation) ⇒ [`GateOutcome::Escalate`] with an empty missing set;
803/// 4. otherwise honor the argument transform or allow.
804///
805/// The engine is pure set algebra over the capability sets — it never
806/// matches on a specific [`Capability`], so extending the taxonomy requires
807/// no change here (pinned by test).
808#[must_use]
809pub fn decide(
810 required: CapabilitySet,
811 granted: CapabilitySet,
812 policy: &CallPolicy,
813 tool_name: &str,
814) -> GateOutcome {
815 if let Some(reason) = &policy.veto {
816 return GateOutcome::Deny(reason.clone());
817 }
818 let missing = required.difference(granted);
819 if !missing.is_empty() {
820 return GateOutcome::Escalate {
821 reason: escalation_reason(tool_name, missing),
822 missing,
823 };
824 }
825 if policy.requires_human || policy.sandbox_escalation {
826 return GateOutcome::Escalate {
827 reason: String::new(),
828 missing: CapabilitySet::EMPTY,
829 };
830 }
831 match &policy.transform {
832 ArgTransform::None => GateOutcome::Allow,
833 ArgTransform::Rewrite(args) => GateOutcome::Modify(args.clone()),
834 ArgTransform::InjectContext(note) => GateOutcome::InjectContext(note.clone()),
835 }
836}
837
838/// The plain-language reason for a missing-capability escalation, rendered
839/// verbatim on the approval card on every edge (one shared helper so the
840/// wording never differs by surface).
841///
842/// User-facing copy: no internal terms, active sentences, honest about risk
843/// without overclaiming. In the current model a capability is only ever
844/// missing because untrusted content entered the conversation (the base
845/// policy grants everything), so the copy names that cause; a future
846/// narrowed base policy reuses the same wording — the access is missing
847/// either way, and the approver's decision is the same.
848///
849/// The `MutateExternal`-missing arms in particular name a possibility being
850/// checked, not a fact about the call: the gate has no way to confirm a call
851/// is read-only here (an unannotated registered tool, or any unregistered
852/// tool falling back to [`CapabilitySet::all`], lands on this arm whether or
853/// not it ever changes anything), so the copy says the check runs before the
854/// tool "could" reach out or mutate, never that it will.
855#[must_use]
856pub fn escalation_reason(tool_name: &str, missing: CapabilitySet) -> String {
857 // The access-grant marker takes precedence: an invite always needs a person
858 // to confirm the exact invitee, in every conversation state, so the wording
859 // is about the grant itself, not about any content the conversation took in.
860 if missing.contains(Capability::GrantAccess) {
861 return format!(
862 "`{tool_name}` would give someone access to Polychrome, so a person needs to \
863 confirm exactly who's being invited before it goes ahead"
864 );
865 }
866 // The revoke-access marker takes the same precedence, for the same reason:
867 // removing someone's access always needs a person to confirm exactly who,
868 // in every conversation state.
869 if missing.contains(Capability::RevokeAccess) {
870 return format!(
871 "`{tool_name}` would remove someone's access to Polychrome, so a person needs to \
872 confirm exactly who's being removed before it goes ahead"
873 );
874 }
875 // The manage-admin marker takes the same precedence: taking away someone's
876 // admin role always needs a person to confirm exactly whose, in every
877 // conversation state.
878 if missing.contains(Capability::ManageAdmin) {
879 return format!(
880 "`{tool_name}` would take away someone's admin role, so a person needs to confirm \
881 exactly whose role is being removed before it goes ahead"
882 );
883 }
884 let reaches_out = missing.contains(Capability::ArbitraryEgress);
885 let mutates = missing.contains(Capability::MutateExternal);
886 match (reaches_out, mutates) {
887 // Missing `MutateExternal` does not mean `tool_name` mutates — see
888 // this function's doc comment for why.
889 (true, true) => format!(
890 "this conversation has taken in content from outside sources, so `{tool_name}` \
891 needs a quick human check before it could send anything out or change anything \
892 beyond this conversation"
893 ),
894 (true, false) => format!(
895 "this conversation has taken in content from outside sources, so `{tool_name}` \
896 needs a quick human check before it reaches an outside address"
897 ),
898 (false, true) => format!(
899 "this conversation has taken in content from outside sources, so `{tool_name}` \
900 needs a quick human check before it could change anything beyond this conversation"
901 ),
902 (false, false) => format!(
903 "`{tool_name}` needs more access than this conversation currently has, so a \
904 human check is needed first"
905 ),
906 }
907}
908
909#[cfg(test)]
910mod tests;