Skip to main content

dekopon_broker/
lib.rs

1//! ```compile_fail
2//! use dekopon_broker::AuthenticatedContext;
3//! use serde::de::DeserializeOwned;
4//!
5//! fn require_deserializable<T: DeserializeOwned>() {}
6//!
7//! fn main() {
8//!     require_deserializable::<AuthenticatedContext>();
9//! }
10//! ```
11
12#![forbid(unsafe_code)]
13#![cfg_attr(test, allow(clippy::unwrap_used))]
14#![cfg_attr(
15    test,
16    allow(
17        clippy::disallowed_methods,
18        clippy::disallowed_types,
19        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
20    )
21)]
22use std::{
23    collections::{BTreeMap, BTreeSet},
24    fmt,
25    future::Future,
26    ops::ControlFlow,
27    sync::Arc,
28    time::Instant,
29};
30
31mod continuity;
32
33pub use continuity::{
34    CandidateReport, ContinuityCandidate, ContinuityDigest, ContinuityDigestError,
35    ContinuityMigration, ContinuityReport, HostLimitFields, HostLimitOverrides, MemoryOverrides,
36    OperationalOverrides, StorageOverrides,
37};
38use continuity::{ContinuityState, OperationalSnapshot};
39
40use async_trait::async_trait;
41use dekopon_broker_host::{
42    BoundCredential, BrokerHostError, BrokerProviderRegistry, CommandRunOutcome, HttpCallEvidence,
43    ProviderCapability,
44};
45pub use dekopon_broker_protocol::{
46    Attestation, AvailableCapability, ChatMemorySurface, ChatScopeClaim, ChatTransportKind,
47    Conversation, ConversationKind, ConversationKindMatch, ConversationMatch,
48    ConversationMatchProblem, DeliveredAnswer, DeliveredTurnRequest, DeliveryIdentity,
49    InvocationRequest, Trigger,
50};
51use dekopon_capability::{
52    AuthorizationError, ChatSlot, ChatSlotValues, DecisionReference, EffectKind, Evidence,
53    ExecutionConstraints, HttpConstraints, HttpConstraintsError, InvocationOutcome,
54    InvocationResult, ProposedInvocation, SecretUseGrant, StorageAccess, StorageConstraints,
55    StorageInterface, StorageRetention, StorageScope, broker::AuthorizationGate,
56};
57use dekopon_core::{
58    Actor, AgentId, AttestedSubject, CapabilityId, InvocationId, PrincipalId, PrincipalKind,
59    ProviderFailureDetail, ProviderId, Redacted, RiskLevel, SecretBytes, SecretDrn, SecretSinkKind,
60    SecretUseProposal, Subject, SubjectKind, SubjectScope, TraceId, error_chain,
61};
62pub use dekopon_policy::{AGENT_PROMPT_ACTION, PolicyBuildError, PolicyEngine, PolicyWorld};
63use dekopon_policy::{
64    PolicyContext, PolicyConversation, PolicyDecision, PolicyRequest, PolicyTarget, SecretSelection,
65};
66use dekopon_storage_host::{
67    ContinuityPolicy, MemoryContinuity, RetentionPolicies, StorageEvidence,
68    StorageGrantPreparation, StorageGrantRequest, StorageScopeCommitment,
69};
70use serde::{Deserialize, Serialize};
71use sha2::{Digest as _, Sha256};
72use thiserror::Error;
73use tracing::Instrument as _;
74
75const MAX_POLICY_SCOPE_ENTRIES: usize = 64;
76const POLICY_STACK_BYTES: usize = 2 * 1024 * 1024;
77pub const MAX_SECRET_BINDINGS: usize = 1024;
78const EVIDENCE_HASH_DOMAIN: &[u8] = b"dekopon-evidence-v1\0";
79const POLICY_EVIDENCE_MEDIA_TYPE: &str = "application/vnd.dekopon.policy-decision+json";
80const HTTP_EVIDENCE_MEDIA_TYPE: &str = "application/vnd.dekopon.http-evidence+json";
81const STORAGE_EVIDENCE_MEDIA_TYPE: &str = "application/vnd.dekopon.storage-evidence+json";
82
83const UNROUTED_RECORD_CAPABILITY: &str = "memory.chat.record";
84const MEMORY_MIN_TURN_LINE_BYTES: u64 = 241;
85const MEMORY_PROVIDER_INPUT_OVERHEAD_BYTES: u64 = 4 * 1024;
86const MEMORY_QUERY_JSON_EXPANSION: u64 = 6;
87const MEMORY_WORKING_SET_OVERHEAD_BYTES: u64 = 4 * 1024 * 1024;
88const MEMORY_MIN_RESULT_BYTES: u64 = 30;
89const MEMORY_LOGICAL_FILES: u64 = 1;
90const MEMORY_RECORD_FIXED_HOST_CALLS: u64 = 3;
91const MEMORY_FUEL_BASE: u64 = 10_000_000;
92const MEMORY_FUEL_PER_WORK_BYTE: u64 = 256;
93const MEMORY_READ_CHUNK_BYTES: u64 = 256 * 1024;
94
95#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
96#[serde(deny_unknown_fields, rename_all = "camelCase")]
97pub struct ChatMemoryConfig {
98    #[serde(default)]
99    pub continuity_policy: ContinuityPolicy,
100    pub enabled_agents: Vec<AgentId>,
101    pub max_lookback_turns: u32,
102    pub max_recent_turns: u32,
103    pub max_search_results: u32,
104    pub max_query_bytes: u64,
105    pub max_result_bytes: u64,
106    pub max_turn_bytes: u64,
107    pub compaction_target_bytes: u64,
108    pub compaction_threshold_bytes: u64,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub continuity_migration: Option<ContinuityMigration>,
111}
112
113impl ChatMemoryConfig {
114    pub fn validate(
115        &self,
116        storage: &dekopon_storage_host::StorageLimits,
117    ) -> Result<(), BrokerBuildError> {
118        let positive = [
119            u64::from(self.max_lookback_turns),
120            u64::from(self.max_recent_turns),
121            u64::from(self.max_search_results),
122            self.max_query_bytes,
123            self.max_result_bytes,
124            self.max_turn_bytes,
125            self.compaction_target_bytes,
126            self.compaction_threshold_bytes,
127        ];
128        let unique_agents = self.enabled_agents.iter().collect::<BTreeSet<_>>();
129        if self.enabled_agents.is_empty()
130            || unique_agents.len() != self.enabled_agents.len()
131            || positive.contains(&0)
132            || self.max_recent_turns > self.max_lookback_turns
133            || self.max_search_results > self.max_lookback_turns
134            || self.compaction_target_bytes >= self.compaction_threshold_bytes
135            || self.compaction_threshold_bytes > storage.max_file_bytes
136            || self.max_turn_bytes < MEMORY_MIN_TURN_LINE_BYTES
137            || self.max_result_bytes < MEMORY_MIN_RESULT_BYTES
138            || self
139                .continuity_migration
140                .as_ref()
141                .is_some_and(|migration| !migration.valid())
142        {
143            return Err(BrokerBuildError::InvalidChatMemory);
144        }
145        let retained = u64::from(self.max_lookback_turns)
146            .checked_mul(self.max_turn_bytes)
147            .ok_or(BrokerBuildError::InvalidChatMemory)?;
148        // read-file charges a full CHUNK even on a partial final call.
149        let read_budget = round_up(self.compaction_threshold_bytes, MEMORY_READ_CHUNK_BYTES)?;
150        let host_calls = read_budget
151            .checked_div(MEMORY_READ_CHUNK_BYTES)
152            .and_then(|value| value.checked_add(MEMORY_RECORD_FIXED_HOST_CALLS))
153            .ok_or(BrokerBuildError::InvalidChatMemory)?;
154        let write_budget = self
155            .compaction_target_bytes
156            .checked_add(self.max_turn_bytes)
157            .ok_or(BrokerBuildError::InvalidChatMemory)?;
158        let threshold_with_append = self
159            .compaction_threshold_bytes
160            .checked_add(self.max_turn_bytes)
161            .ok_or(BrokerBuildError::InvalidChatMemory)?;
162        let namespace_headroom = threshold_with_append
163            .checked_add(32 * 4_096)
164            .ok_or(BrokerBuildError::InvalidChatMemory)?;
165        if retained > self.compaction_target_bytes
166            || MEMORY_READ_CHUNK_BYTES > storage.max_read_bytes_per_call
167            || self.max_turn_bytes > storage.max_write_bytes_per_call
168            || self.compaction_target_bytes > storage.max_write_bytes_per_call
169            || threshold_with_append > storage.max_file_bytes
170            || read_budget > storage.max_read_bytes_per_invocation
171            || write_budget > storage.max_write_bytes_per_invocation
172            || host_calls > storage.max_host_calls_per_invocation
173            || storage.max_files_per_namespace < MEMORY_LOGICAL_FILES
174            || namespace_headroom > storage.max_namespace_bytes
175            || self.max_query_bytes > 256 * 1024
176            || self.max_result_bytes > 1024 * 1024
177        {
178            return Err(BrokerBuildError::InvalidChatMemory);
179        }
180        Ok(())
181    }
182
183    fn maximum_provider_input_bytes(&self) -> Result<u64, BrokerBuildError> {
184        let record = self
185            .max_turn_bytes
186            .checked_add(MEMORY_PROVIDER_INPUT_OVERHEAD_BYTES)
187            .ok_or(BrokerBuildError::InvalidChatMemory)?;
188        let search = self
189            .max_query_bytes
190            .checked_mul(MEMORY_QUERY_JSON_EXPANSION)
191            .and_then(|value| value.checked_add(MEMORY_PROVIDER_INPUT_OVERHEAD_BYTES))
192            .ok_or(BrokerBuildError::InvalidChatMemory)?;
193        Ok(record.max(search))
194    }
195
196    fn maximum_provider_working_set_bytes(&self) -> Result<u64, BrokerBuildError> {
197        self.compaction_threshold_bytes
198            .checked_mul(2)
199            .and_then(|bytes| bytes.checked_add(self.compaction_target_bytes.checked_mul(2)?))
200            .and_then(|bytes| bytes.checked_add(self.max_turn_bytes))
201            .and_then(|bytes| bytes.checked_add(self.max_result_bytes))
202            .and_then(|bytes| bytes.checked_add(MEMORY_WORKING_SET_OVERHEAD_BYTES))
203            .ok_or(BrokerBuildError::InvalidChatMemory)
204    }
205
206    fn minimum_provider_fuel(&self) -> Result<u64, BrokerBuildError> {
207        let record_work = self
208            .compaction_threshold_bytes
209            .checked_add(self.compaction_target_bytes)
210            .and_then(|value| value.checked_add(self.max_turn_bytes))
211            .ok_or(BrokerBuildError::InvalidChatMemory)?;
212        let search_work = self
213            .compaction_threshold_bytes
214            .checked_add(self.max_query_bytes)
215            .and_then(|value| value.checked_add(self.max_result_bytes))
216            .ok_or(BrokerBuildError::InvalidChatMemory)?;
217        record_work
218            .max(search_work)
219            .checked_mul(MEMORY_FUEL_PER_WORK_BYTE)
220            .and_then(|value| value.checked_add(MEMORY_FUEL_BASE))
221            .ok_or(BrokerBuildError::InvalidChatMemory)
222    }
223
224    pub fn validate_host_limits(
225        &self,
226        host: &dekopon_broker_host::BrokerHostLimits,
227    ) -> Result<(), BrokerBuildError> {
228        let max_input = u64::try_from(host.max_input_bytes).unwrap_or(u64::MAX);
229        let max_memory = u64::try_from(host.max_memory_bytes).unwrap_or(u64::MAX);
230        if self.maximum_provider_input_bytes()? > max_input
231            || self.maximum_provider_working_set_bytes()? > max_memory
232            || self.minimum_provider_fuel()? > host.fuel
233        {
234            return Err(BrokerBuildError::InvalidChatMemory);
235        }
236        Ok(())
237    }
238
239    #[must_use]
240    pub fn enabled_for(&self, agent: &AgentId) -> bool {
241        self.enabled_agents.contains(agent)
242    }
243}
244
245fn round_up(value: u64, multiple: u64) -> Result<u64, BrokerBuildError> {
246    value
247        .checked_add(multiple.saturating_sub(1))
248        .map(|value| value / multiple * multiple)
249        .ok_or(BrokerBuildError::InvalidChatMemory)
250}
251
252pub const DEFAULT_MAX_CONSTRAINT_SETS: usize = 1_024;
253
254#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
255#[serde(rename_all = "camelCase")]
256pub struct AuthenticatedContext {
257    principal: PrincipalId,
258    actor: Actor,
259    #[serde(skip_serializing_if = "Option::is_none")]
260    via: Option<PrincipalId>,
261    #[serde(skip_serializing_if = "Option::is_none")]
262    attested_subject: Option<Subject>,
263    #[serde(skip_serializing_if = "Option::is_none")]
264    chat_scope: Option<ChatScopeClaim>,
265    #[serde(skip_serializing_if = "Option::is_none")]
266    space: Option<PrincipalId>,
267}
268
269impl AuthenticatedContext {
270    pub fn space_binding(&self) -> Option<dekopon_core::SpaceBinding> {
271        let principal = self.space.as_ref()?;
272        let scope = self.chat_scope()?;
273        let agent = match self.actor() {
274            Actor::Agent { agent } => agent,
275            Actor::Human { .. } | Actor::Service { .. } => return None,
276        };
277        Some(dekopon_core::SpaceBinding {
278            key: dekopon_core::SpaceKey {
279                agent: agent.clone(),
280                transport: scope.transport.to_string().into(),
281                workspace: scope.conversation.container.clone().map(Into::into),
282                channel: scope.conversation.id.clone().into(),
283            },
284            principal: principal.clone(),
285        })
286    }
287
288    pub fn new(principal: PrincipalId, actor: Actor) -> Result<Self, ContextError> {
289        Self::build(principal, actor, None, None, None)
290    }
291
292    pub fn attested(
293        principal: PrincipalId,
294        actor: Actor,
295        via: PrincipalId,
296        subject: Subject,
297    ) -> Result<Self, ContextError> {
298        Self::build(principal, actor, Some(via), Some(subject), None)
299    }
300
301    pub fn attested_chat(
302        principal: PrincipalId,
303        actor: Actor,
304        via: PrincipalId,
305        subject: Subject,
306        scope: ChatScopeClaim,
307    ) -> Result<Self, ContextError> {
308        Self::build(principal, actor, Some(via), Some(subject), Some(scope))
309    }
310
311    fn build(
312        principal: PrincipalId,
313        actor: Actor,
314        via: Option<PrincipalId>,
315        attested_subject: Option<Subject>,
316        chat_scope: Option<ChatScopeClaim>,
317    ) -> Result<Self, ContextError> {
318        let actor_principal = match &actor {
319            Actor::Human { principal } | Actor::Service { principal } => Some(principal),
320            Actor::Agent { .. } => None,
321        };
322        if actor_principal.is_some_and(|actor_principal| actor_principal != &principal) {
323            return Err(ContextError::PrincipalMismatch);
324        }
325        Ok(Self {
326            principal,
327            actor,
328            via,
329            attested_subject,
330            chat_scope,
331            space: None,
332        })
333    }
334
335    #[must_use]
336    fn with_refused_subject(&self, subject: Subject) -> Self {
337        Self {
338            principal: self.principal.clone(),
339            actor: self.actor.clone(),
340            via: None,
341            attested_subject: Some(subject),
342            chat_scope: None,
343            space: None,
344        }
345    }
346
347    #[must_use]
348    pub fn principal(&self) -> &PrincipalId {
349        &self.principal
350    }
351
352    #[must_use]
353    pub fn actor(&self) -> &Actor {
354        &self.actor
355    }
356
357    #[must_use]
358    pub fn via(&self) -> Option<&PrincipalId> {
359        self.via.as_ref()
360    }
361
362    #[must_use]
363    pub fn attested_subject(&self) -> Option<&Subject> {
364        self.attested_subject.as_ref()
365    }
366
367    #[must_use]
368    pub fn chat_scope(&self) -> Option<&ChatScopeClaim> {
369        self.chat_scope.as_ref()
370    }
371}
372
373#[derive(Clone, Debug, Eq, Error, PartialEq)]
374pub enum ContextError {
375    #[error("authenticated principal does not match the human or service actor")]
376    PrincipalMismatch,
377}
378
379#[derive(Debug)]
380pub struct AssetInvocationResult {
381    pub result: InvocationResult,
382    pub assets: dekopon_broker_host::asset::AssetOutputs,
383}
384
385#[derive(
386    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
387)]
388#[serde(rename_all = "camelCase")]
389pub enum CapabilityRoute {
390    #[default]
391    Generic,
392    ChatMemoryRecord,
393    ChatMemoryRecent,
394    ChatMemorySearch,
395}
396
397impl CapabilityRoute {
398    pub(crate) const CHAT_MEMORY: [Self; 3] = [
399        Self::ChatMemoryRecord,
400        Self::ChatMemoryRecent,
401        Self::ChatMemorySearch,
402    ];
403
404    #[must_use]
405    pub const fn is_generic(&self) -> bool {
406        matches!(self, Self::Generic)
407    }
408
409    #[must_use]
410    pub const fn is_chat_memory(self) -> bool {
411        !self.is_generic()
412    }
413
414    #[must_use]
415    pub const fn is_chat_memory_retrieval(self) -> bool {
416        matches!(self, Self::ChatMemoryRecent | Self::ChatMemorySearch)
417    }
418
419    const fn chat_memory_access(self) -> Option<StorageAccess> {
420        match self {
421            Self::Generic => None,
422            Self::ChatMemoryRecord => Some(StorageAccess::ReadWrite),
423            Self::ChatMemoryRecent | Self::ChatMemorySearch => Some(StorageAccess::ReadOnly),
424        }
425    }
426
427    #[must_use]
428    pub const fn as_str(self) -> &'static str {
429        match self {
430            Self::Generic => "generic",
431            Self::ChatMemoryRecord => "chatMemoryRecord",
432            Self::ChatMemoryRecent => "chatMemoryRecent",
433            Self::ChatMemorySearch => "chatMemorySearch",
434        }
435    }
436}
437
438impl fmt::Display for CapabilityRoute {
439    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
440        formatter.write_str(self.as_str())
441    }
442}
443
444#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
445#[serde(deny_unknown_fields, rename_all = "camelCase")]
446pub struct ConstraintSet {
447    #[serde(
448        default,
449        skip_serializing_if = "Option::is_none",
450        deserialize_with = "deserialize_default_secret_use"
451    )]
452    pub default_secret_use: Option<DefaultSecretUse>,
453    #[serde(default, skip_serializing_if = "CapabilityRoute::is_generic")]
454    pub route: CapabilityRoute,
455    pub provider: ProviderId,
456    pub effect: EffectKind,
457    pub risk: RiskLevel,
458    pub constraints: ExecutionConstraints,
459}
460
461#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
462#[serde(deny_unknown_fields, rename_all = "camelCase")]
463pub struct DefaultSecretUse {
464    pub drn: SecretDrn,
465    pub sink: DefaultSecretSink,
466}
467
468#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
469#[serde(rename_all = "camelCase")]
470pub enum DefaultSecretSink {
471    HttpBearer,
472    HttpBasic,
473    HttpBot,
474}
475
476impl DefaultSecretSink {
477    #[must_use]
478    pub const fn sink(self) -> SecretSinkKind {
479        match self {
480            Self::HttpBearer => SecretSinkKind::HttpBearer,
481            Self::HttpBasic => SecretSinkKind::HttpBasic,
482            Self::HttpBot => SecretSinkKind::HttpBot,
483        }
484    }
485}
486
487fn deserialize_default_secret_use<'de, D>(
488    deserializer: D,
489) -> Result<Option<DefaultSecretUse>, D::Error>
490where
491    D: serde::Deserializer<'de>,
492{
493    DefaultSecretUse::deserialize(deserializer).map(Some)
494}
495
496#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
497pub enum Leniency {
498    #[default]
499    Strict,
500    Tolerant,
501}
502
503#[derive(Clone, Debug, Eq, PartialEq)]
504pub enum StartupWarning {
505    UnroutedConstraintSet { capability: CapabilityId },
506    UnconstrainedCapability { capability: CapabilityId },
507    UnreachableCapability { capability: CapabilityId },
508}
509
510impl StartupWarning {
511    #[must_use]
512    pub const fn reason(&self) -> &'static str {
513        match self {
514            Self::UnroutedConstraintSet { .. } => "unrouted-constraint-set",
515            Self::UnconstrainedCapability { .. } => "unconstrained-capability",
516            Self::UnreachableCapability { .. } => "unreachable-capability",
517        }
518    }
519
520    #[must_use]
521    pub const fn capability(&self) -> &CapabilityId {
522        match self {
523            Self::UnroutedConstraintSet { capability }
524            | Self::UnconstrainedCapability { capability }
525            | Self::UnreachableCapability { capability } => capability,
526        }
527    }
528}
529
530impl fmt::Display for StartupWarning {
531    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
532        match self {
533            Self::UnroutedConstraintSet { capability } => write!(
534                formatter,
535                "constraint set for {capability} names no loaded provider route; it was ignored"
536            ),
537            Self::UnconstrainedCapability { capability } => write!(
538                formatter,
539                "policy could permit {capability}, which has no constraint set; every invocation \
540                 of it will be denied unconstrained-capability"
541            ),
542            Self::UnreachableCapability { capability } => write!(
543                formatter,
544                "constraint set for {capability} is named by no permit policy, directly or \
545                 through an action group; every invocation of it will be denied"
546            ),
547        }
548    }
549}
550
551#[derive(Clone, Debug, Default, Eq, PartialEq)]
552pub struct ConstraintCatalog {
553    sets: BTreeMap<CapabilityId, ConstraintSet>,
554    agent_secrets: BTreeMap<AgentId, BTreeMap<SecretDrn, SecretDrn>>,
555}
556
557impl ConstraintCatalog {
558    #[must_use]
559    pub fn empty() -> Self {
560        Self::default()
561    }
562
563    pub fn new(
564        entries: impl IntoIterator<Item = (CapabilityId, ConstraintSet)>,
565    ) -> Result<Self, BrokerBuildError> {
566        let mut sets = BTreeMap::new();
567        for (capability, set) in entries {
568            if sets.insert(capability.clone(), set).is_some() {
569                return Err(BrokerBuildError::DuplicateConstraintSet { capability });
570            }
571        }
572        Ok(Self {
573            sets,
574            agent_secrets: BTreeMap::new(),
575        })
576    }
577
578    #[must_use]
579    pub fn with_agent_secrets(
580        mut self,
581        swaps: BTreeMap<AgentId, BTreeMap<SecretDrn, SecretDrn>>,
582    ) -> Self {
583        self.agent_secrets = swaps;
584        self
585    }
586
587    #[must_use]
588    pub fn effective_default<'a>(
589        &'a self,
590        set: &'a ConstraintSet,
591        actor: &Actor,
592    ) -> Option<(&'a SecretDrn, SecretSinkKind)> {
593        let default = set.default_secret_use.as_ref()?;
594        let swapped = match actor {
595            Actor::Agent { agent } => self
596                .agent_secrets
597                .get(agent)
598                .and_then(|swaps| swaps.get(&default.drn)),
599            Actor::Human { .. } | Actor::Service { .. } => None,
600        };
601        Some((swapped.unwrap_or(&default.drn), default.sink.sink()))
602    }
603
604    fn selectable_defaults<'a>(&'a self, set: &'a ConstraintSet) -> BTreeSet<&'a SecretDrn> {
605        let Some(default) = set.default_secret_use.as_ref() else {
606            return BTreeSet::new();
607        };
608        std::iter::once(&default.drn)
609            .chain(
610                self.agent_secrets
611                    .values()
612                    .filter_map(|swaps| swaps.get(&default.drn)),
613            )
614            .collect()
615    }
616
617    pub fn retain_routed(&mut self, registry: &BrokerProviderRegistry) -> Vec<CapabilityId> {
618        let routed = registry
619            .capabilities()
620            .map(|(_, capability)| capability.id.clone())
621            .collect::<BTreeSet<_>>();
622        let dropped = self
623            .sets
624            .keys()
625            .filter(|capability| !routed.contains(*capability))
626            .cloned()
627            .collect::<Vec<_>>();
628        for capability in &dropped {
629            self.sets.remove(capability);
630        }
631        dropped
632    }
633
634    #[must_use]
635    pub fn get(&self, capability: &CapabilityId) -> Option<&ConstraintSet> {
636        self.sets.get(capability)
637    }
638
639    pub fn iter(&self) -> impl Iterator<Item = (&CapabilityId, &ConstraintSet)> {
640        self.sets.iter()
641    }
642
643    fn routed(&self, route: CapabilityRoute) -> Option<(&CapabilityId, &ConstraintSet)> {
644        self.sets.iter().find(|(_, set)| set.route == route)
645    }
646
647    fn chat_memory_provider(&self) -> Option<&ProviderId> {
648        self.sets
649            .values()
650            .find(|set| set.route.is_chat_memory())
651            .map(|set| &set.provider)
652    }
653
654    #[must_use]
655    pub fn len(&self) -> usize {
656        self.sets.len()
657    }
658
659    #[must_use]
660    pub fn is_empty(&self) -> bool {
661        self.sets.is_empty()
662    }
663
664    fn validate(
665        &self,
666        registry: &BrokerProviderRegistry,
667        maximum: usize,
668    ) -> Result<(), BrokerBuildError> {
669        if self.sets.len() > maximum {
670            return Err(BrokerBuildError::TooManyConstraintSets {
671                count: self.sets.len(),
672                maximum,
673            });
674        }
675        self.validate_routes()?;
676        self.validate_storage_namespaces()?;
677        self.retention_policies()?;
678        for (capability_id, set) in &self.sets {
679            validate_set_constraints(set)?;
680            registry
681                .validate_constraints(&set.constraints)
682                .map_err(|source| BrokerBuildError::HostConstraint { source })?;
683            let (provider, capability) = registry
684                .capabilities()
685                .find(|(_, capability)| &capability.id == capability_id)
686                .ok_or_else(|| BrokerBuildError::UnknownCapability {
687                    capability: capability_id.clone(),
688                })?;
689            validate_trusted_metadata(capability_id, set, provider, capability)?;
690        }
691        Ok(())
692    }
693
694    fn retention_policies(&self) -> Result<RetentionPolicies, BrokerBuildError> {
695        let mut policies = RetentionPolicies::new();
696        for set in self.sets.values() {
697            let Some(storage) = &set.constraints.storage else {
698                continue;
699            };
700            if let StorageRetention::IdleTtl(ttl) = storage.retention
701                && (ttl.as_millis() == 0 || ttl.as_millis() > u128::from(u64::MAX))
702            {
703                return Err(BrokerBuildError::InvalidStorageRetention);
704            }
705            let namespace = storage.namespace.as_ref().unwrap_or(&set.provider).clone();
706            let key = (namespace, storage.scope);
707            if let Some(previous) = policies.insert(key.clone(), storage.retention)
708                && previous != storage.retention
709            {
710                return Err(BrokerBuildError::ConflictingStorageRetention {
711                    namespace: key.0,
712                    scope: key.1,
713                });
714            }
715        }
716        Ok(policies)
717    }
718
719    fn validate_storage_namespaces(&self) -> Result<(), BrokerBuildError> {
720        let mut conflicts = Vec::new();
721        let mut members = BTreeMap::<&ProviderId, Vec<(&CapabilityId, &StorageConstraints)>>::new();
722        for (capability, set) in &self.sets {
723            let Some(storage) = &set.constraints.storage else {
724                continue;
725            };
726            if storage.scope != StorageScope::Agent {
727                if let Some(namespace) = &storage.namespace {
728                    conflicts.push(NamespaceConflict::NotAgentScope {
729                        capability: capability.clone(),
730                        namespace: namespace.clone(),
731                        scope: storage.scope,
732                    });
733                }
734                continue;
735            }
736            members
737                .entry(storage.namespace.as_ref().unwrap_or(&set.provider))
738                .or_default()
739                .push((capability, storage));
740        }
741        for (namespace, sets) in members {
742            if sets.iter().all(|(_, storage)| storage.namespace.is_none()) {
743                continue;
744            }
745            let interfaces = sets
746                .iter()
747                .map(|(_, storage)| storage.interface)
748                .collect::<BTreeSet<_>>();
749            if interfaces.len() > 1 {
750                conflicts.push(NamespaceConflict::Mismatch {
751                    namespace: namespace.clone(),
752                    capabilities: sets
753                        .iter()
754                        .map(|(capability, storage)| ((*capability).clone(), storage.interface))
755                        .collect(),
756                });
757            }
758        }
759        if conflicts.is_empty() {
760            Ok(())
761        } else {
762            Err(BrokerBuildError::ConflictingStorageNamespaces { conflicts })
763        }
764    }
765
766    fn validate_routes(&self) -> Result<(), BrokerBuildError> {
767        let mut conflicts = Vec::new();
768        for route in CapabilityRoute::CHAT_MEMORY {
769            let claimants = self
770                .sets
771                .iter()
772                .filter(|(_, set)| set.route == route)
773                .map(|(capability, _)| capability.clone())
774                .collect::<Vec<_>>();
775            if claimants.len() > 1 {
776                conflicts.push(RouteConflict::DuplicateRole {
777                    route,
778                    capabilities: claimants,
779                });
780            }
781        }
782        let providers = self
783            .sets
784            .values()
785            .filter(|set| set.route.is_chat_memory())
786            .map(|set| set.provider.clone())
787            .collect::<BTreeSet<_>>();
788        if providers.len() > 1 {
789            conflicts.push(RouteConflict::SplitProvider {
790                providers: providers.into_iter().collect(),
791            });
792        }
793        for (capability, set) in &self.sets {
794            let Some(access) = set.route.chat_memory_access() else {
795                continue;
796            };
797            let declared = set.constraints.storage.as_ref().filter(|storage| {
798                storage.interface == StorageInterface::Jsonl
799                    && storage.scope == StorageScope::PrivateConversation
800                    && storage.access == access
801            });
802            if declared.is_none() {
803                conflicts.push(RouteConflict::MissingChatStorage {
804                    capability: capability.clone(),
805                    route: set.route,
806                    access,
807                });
808            }
809        }
810        if conflicts.is_empty() {
811            Ok(())
812        } else {
813            Err(BrokerBuildError::ConflictingRoutes { conflicts })
814        }
815    }
816}
817
818#[derive(Clone, Debug, Eq, PartialEq)]
819pub struct SecretUseBinding {
820    pub binding_id: String,
821    pub secret: SecretDrn,
822    pub capabilities: BTreeSet<CapabilityId>,
823    pub sink: SecretSinkKind,
824    pub basic_username: Option<String>,
825    pub allowed_hosts: Vec<String>,
826    pub allowed_methods: Vec<String>,
827    pub allowed_paths: Vec<dekopon_capability::HttpPathRule>,
828    pub allow_query: bool,
829    pub max_injections: u32,
830}
831
832impl SecretUseBinding {
833    pub fn validate(&self) -> Result<(), dekopon_capability::SecretUseGrantError> {
834        self.grant().validate()
835    }
836
837    fn grant(&self) -> SecretUseGrant {
838        SecretUseGrant {
839            secret: self.secret.clone(),
840            sink: self.sink,
841            basic_username: self.basic_username.clone(),
842            allowed_hosts: self.allowed_hosts.clone(),
843            allowed_methods: self.allowed_methods.clone(),
844            allowed_paths: self.allowed_paths.clone(),
845            allow_query: self.allow_query,
846            max_injections: self.max_injections,
847            binding_id: self.binding_id.clone(),
848            map_revision: None,
849        }
850    }
851
852    fn proposal(&self) -> SecretUseProposal {
853        match self.sink {
854            SecretSinkKind::HttpBearer => SecretUseProposal::HttpBearer {
855                secret: self.secret.clone(),
856            },
857            SecretSinkKind::HttpBasic => SecretUseProposal::HttpBasic {
858                secret: self.secret.clone(),
859                username: self
860                    .basic_username
861                    .clone()
862                    .expect("validated Basic binding always carries a username"),
863            },
864            SecretSinkKind::HttpBot => SecretUseProposal::HttpBot {
865                secret: self.secret.clone(),
866            },
867        }
868    }
869
870    fn matches(&self, capability: &CapabilityId, proposal: &SecretUseProposal) -> bool {
871        self.capabilities.contains(capability)
872            && &self.secret == proposal.secret()
873            && self.sink == proposal.sink()
874            && self.basic_username.as_deref() == proposal.username()
875    }
876}
877
878#[derive(Clone)]
879pub struct SecretMaterial {
880    bytes: SecretBytes,
881    chatgpt_account: Option<Redacted<String>>,
882}
883
884impl SecretMaterial {
885    #[must_use]
886    pub fn new(bytes: Vec<u8>) -> Self {
887        Self {
888            bytes: SecretBytes::new(bytes),
889            chatgpt_account: None,
890        }
891    }
892
893    #[must_use]
894    pub fn with_chatgpt_account(mut self, account: Redacted<String>) -> Self {
895        self.chatgpt_account = Some(account);
896        self
897    }
898}
899
900impl fmt::Debug for SecretMaterial {
901    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
902        formatter.write_str("SecretMaterial([REDACTED])")
903    }
904}
905
906#[async_trait]
907pub trait SecretResolver: Send + Sync + fmt::Debug {
908    async fn resolve(&self, secret: &SecretDrn) -> Result<SecretMaterial, SecretResolutionError>;
909}
910
911#[derive(Clone, Debug, Error, Eq, PartialEq)]
912#[error("secret source resolution failed ({category})")]
913pub struct SecretResolutionError {
914    pub category: &'static str,
915}
916
917#[derive(Debug)]
918struct EmptySecretResolver;
919
920#[async_trait]
921impl SecretResolver for EmptySecretResolver {
922    async fn resolve(&self, _secret: &SecretDrn) -> Result<SecretMaterial, SecretResolutionError> {
923        Err(SecretResolutionError {
924            category: "missing",
925        })
926    }
927}
928
929pub struct SecretCatalog {
930    bindings: Vec<SecretUseBinding>,
931    resolver: Arc<dyn SecretResolver>,
932    authority_revision: Option<String>,
933}
934
935impl fmt::Debug for SecretCatalog {
936    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
937        formatter
938            .debug_struct("SecretCatalog")
939            .field("bindings", &self.bindings.len())
940            .field("resolver", &"[BROKER-PRIVATE]")
941            .field("authority_revision", &self.authority_revision)
942            .finish()
943    }
944}
945
946impl Default for SecretCatalog {
947    fn default() -> Self {
948        Self {
949            bindings: Vec::new(),
950            resolver: Arc::new(EmptySecretResolver),
951            authority_revision: None,
952        }
953    }
954}
955
956impl SecretCatalog {
957    #[must_use]
958    pub fn empty() -> Self {
959        Self::default()
960    }
961
962    pub fn new(
963        bindings: Vec<SecretUseBinding>,
964        resolver: Arc<dyn SecretResolver>,
965    ) -> Result<Self, BrokerBuildError> {
966        if bindings.len() > MAX_SECRET_BINDINGS {
967            return Err(BrokerBuildError::TooManySecretBindings {
968                count: bindings.len(),
969                maximum: MAX_SECRET_BINDINGS,
970            });
971        }
972        let mut ids = BTreeSet::new();
973        let mut tuples = BTreeSet::new();
974        for binding in &bindings {
975            if binding.capabilities.is_empty() {
976                return Err(BrokerBuildError::SecretBindingWithoutCapability {
977                    binding: binding.binding_id.clone(),
978                });
979            }
980            binding.grant().validate().map_err(|source| {
981                BrokerBuildError::InvalidSecretBinding {
982                    binding: binding.binding_id.clone(),
983                    source,
984                }
985            })?;
986            if !ids.insert(binding.binding_id.clone()) {
987                return Err(BrokerBuildError::DuplicateSecretBinding {
988                    binding: binding.binding_id.clone(),
989                });
990            }
991            for capability in &binding.capabilities {
992                let tuple = (
993                    binding.secret.clone(),
994                    capability.clone(),
995                    binding.sink,
996                    binding.basic_username.clone(),
997                );
998                if !tuples.insert(tuple) {
999                    return Err(BrokerBuildError::ConflictingSecretBinding {
1000                        secret: binding.secret.clone(),
1001                        capability: capability.clone(),
1002                    });
1003                }
1004            }
1005        }
1006        Ok(Self {
1007            bindings,
1008            resolver,
1009            authority_revision: None,
1010        })
1011    }
1012
1013    pub fn unresolved(bindings: Vec<SecretUseBinding>) -> Result<Self, BrokerBuildError> {
1014        Self::new(bindings, Arc::new(EmptySecretResolver))
1015    }
1016
1017    pub fn drns(&self) -> impl Iterator<Item = &SecretDrn> {
1018        self.bindings.iter().map(|binding| &binding.secret)
1019    }
1020
1021    pub fn with_authority_revision(mut self, revision: String) -> Result<Self, BrokerBuildError> {
1022        if revision.is_empty()
1023            || revision.len() > 128
1024            || revision.trim() != revision
1025            || revision.bytes().any(|byte| byte.is_ascii_control())
1026        {
1027            return Err(BrokerBuildError::InvalidSecretMapRevision);
1028        }
1029        self.authority_revision = Some(revision);
1030        Ok(self)
1031    }
1032
1033    fn grant(&self, binding: &SecretUseBinding) -> SecretUseGrant {
1034        let mut grant = binding.grant();
1035        grant.map_revision = self.authority_revision.clone();
1036        grant
1037    }
1038
1039    fn authority_revision(&self) -> Option<&str> {
1040        self.authority_revision.as_deref()
1041    }
1042
1043    fn authority_bindings(&self) -> Vec<&SecretUseBinding> {
1044        let mut bindings = self.bindings.iter().collect::<Vec<_>>();
1045        bindings.sort_by(|left, right| left.binding_id.cmp(&right.binding_id));
1046        bindings
1047    }
1048
1049    fn validate(&self, constraints: &ConstraintCatalog) -> Result<(), BrokerBuildError> {
1050        for binding in &self.bindings {
1051            for capability in &binding.capabilities {
1052                let set = constraints.get(capability).ok_or_else(|| {
1053                    BrokerBuildError::SecretBindingUnknownCapability {
1054                        binding: binding.binding_id.clone(),
1055                        capability: capability.clone(),
1056                    }
1057                })?;
1058                let http = set.constraints.http.as_ref().ok_or_else(|| {
1059                    BrokerBuildError::SecretBindingWithoutHttp {
1060                        binding: binding.binding_id.clone(),
1061                    }
1062                })?;
1063                if binding.max_injections > http.max_requests
1064                    || binding
1065                        .allowed_hosts
1066                        .iter()
1067                        .any(|host| !http.allowed_hosts.contains(host))
1068                    || binding
1069                        .allowed_methods
1070                        .iter()
1071                        .any(|method| !http.allowed_methods.contains(method))
1072                {
1073                    return Err(BrokerBuildError::SecretBindingExceedsCapability {
1074                        binding: binding.binding_id.clone(),
1075                    });
1076                }
1077            }
1078        }
1079        for (capability, set) in constraints.iter() {
1080            let Some(default) = &set.default_secret_use else {
1081                continue;
1082            };
1083            for secret in constraints.selectable_defaults(set) {
1084                let count = self
1085                    .bindings
1086                    .iter()
1087                    .filter(|binding| {
1088                        binding.capabilities.contains(capability)
1089                            && &binding.secret == secret
1090                            && binding.sink == default.sink.sink()
1091                    })
1092                    .count();
1093                if count != 1 {
1094                    return Err(BrokerBuildError::DefaultSecretBindings {
1095                        capability: capability.clone(),
1096                        secret: secret.clone(),
1097                        sink: default.sink.sink(),
1098                        count,
1099                    });
1100                }
1101            }
1102        }
1103        Ok(())
1104    }
1105
1106    fn default_binding(
1107        &self,
1108        capability: &CapabilityId,
1109        secret: &SecretDrn,
1110        sink: SecretSinkKind,
1111    ) -> Option<&SecretUseBinding> {
1112        self.bindings.iter().find(|binding| {
1113            binding.capabilities.contains(capability)
1114                && &binding.secret == secret
1115                && binding.sink == sink
1116        })
1117    }
1118
1119    fn binding(
1120        &self,
1121        capability: &CapabilityId,
1122        proposal: &SecretUseProposal,
1123    ) -> Option<&SecretUseBinding> {
1124        self.bindings
1125            .iter()
1126            .find(|binding| binding.matches(capability, proposal))
1127    }
1128}
1129
1130#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1131#[serde(deny_unknown_fields, rename_all = "camelCase")]
1132pub struct AttestorGrant {
1133    #[serde(default, skip_serializing_if = "Option::is_none")]
1134    pub namespaces: Option<Vec<SubjectScope>>,
1135}
1136
1137impl AttestorGrant {
1138    pub fn validate(&self) -> Result<(), BrokerBuildError> {
1139        match &self.namespaces {
1140            Some(namespaces)
1141                if namespaces.is_empty() || namespaces.len() > MAX_POLICY_SCOPE_ENTRIES =>
1142            {
1143                Err(BrokerBuildError::InvalidAttestorScope {
1144                    scope: namespaces.len().to_string(),
1145                })
1146            }
1147            Some(_) | None => Ok(()),
1148        }
1149    }
1150
1151    #[must_use]
1152    pub fn permits(&self, subjects: &AttestedSubject) -> bool {
1153        subjects.forms().all(|subject| {
1154            self.namespaces
1155                .as_ref()
1156                .is_none_or(|scopes| scopes.iter().any(|scope| scope.covers(subject)))
1157        })
1158    }
1159}
1160
1161#[derive(Debug, Default)]
1162pub struct IdentityDirectory {
1163    mappings: BTreeMap<Subject, PrincipalId>,
1164}
1165
1166impl IdentityDirectory {
1167    #[must_use]
1168    pub fn empty() -> Self {
1169        Self::default()
1170    }
1171
1172    pub fn new(
1173        entries: impl IntoIterator<Item = (Subject, PrincipalId)>,
1174    ) -> Result<Self, BrokerBuildError> {
1175        let mut mappings = BTreeMap::new();
1176        for (subject, principal) in entries {
1177            if mappings.contains_key(&subject) {
1178                return Err(BrokerBuildError::DuplicateSubjectMapping {
1179                    subject: subject.canonical(),
1180                });
1181            }
1182            mappings.insert(subject, principal);
1183        }
1184        Ok(Self { mappings })
1185    }
1186
1187    #[must_use]
1188    pub fn resolve(&self, subject: &Subject) -> Option<&PrincipalId> {
1189        self.mappings.get(subject)
1190    }
1191
1192    fn mappings(&self) -> impl ExactSizeIterator<Item = (&Subject, &PrincipalId)> {
1193        self.mappings.iter()
1194    }
1195
1196    pub fn resolve_attested(
1197        &self,
1198        subjects: &AttestedSubject,
1199    ) -> Result<Option<&PrincipalId>, SplitSubject> {
1200        let name = self.resolve(subjects.name());
1201        let id = subjects.id_form().and_then(|id| self.resolve(id));
1202        match (name, id) {
1203            (Some(name_principal), Some(id_principal)) if name_principal != id_principal => {
1204                Err(SplitSubject {
1205                    name_principal: name_principal.clone(),
1206                    id_principal: id_principal.clone(),
1207                })
1208            }
1209            (Some(principal), _) | (None, Some(principal)) => Ok(Some(principal)),
1210            (None, None) => Ok(None),
1211        }
1212    }
1213
1214    #[must_use]
1215    pub fn principal_kind(&self, principal: &PrincipalId) -> PrincipalKind {
1216        self.mappings
1217            .iter()
1218            .find_map(|(subject, mapped)| (mapped == principal).then(|| subject.principal_kind()))
1219            .unwrap_or(PrincipalKind::Service)
1220    }
1221
1222    pub fn principals(&self) -> impl Iterator<Item = &PrincipalId> {
1223        self.mappings.values()
1224    }
1225}
1226
1227#[derive(Debug)]
1228pub struct SplitSubject {
1229    name_principal: PrincipalId,
1230    id_principal: PrincipalId,
1231}
1232
1233#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1234#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
1235pub struct BrokerLimits {
1236    pub max_constraint_sets: usize,
1237}
1238
1239impl Default for BrokerLimits {
1240    fn default() -> Self {
1241        Self {
1242            max_constraint_sets: DEFAULT_MAX_CONSTRAINT_SETS,
1243        }
1244    }
1245}
1246
1247fn space_subject(scope: &ChatScopeClaim) -> Option<Subject> {
1248    match scope.conversation.kind {
1249        ConversationKind::Channel | ConversationKind::Thread => {}
1250        ConversationKind::DirectMessage | ConversationKind::GroupDirectMessage => return None,
1251    }
1252    let kind = match scope.kind {
1253        ChatTransportKind::Fauxlack => SubjectKind::FauxlackChannel,
1254        ChatTransportKind::Slack => SubjectKind::SlackChannel,
1255        ChatTransportKind::Discord => SubjectKind::DiscordChannel,
1256        ChatTransportKind::Telegram
1257        | ChatTransportKind::Whatsapp
1258        | ChatTransportKind::Github
1259        | ChatTransportKind::Local => return None,
1260    };
1261    let container = scope.conversation.container.as_deref()?;
1262    Subject::new(kind, container, &scope.conversation.id).ok()
1263}
1264
1265fn policy_contexts(
1266    context: &PolicyContext,
1267    github: Option<&dekopon_core::github::GithubBatch>,
1268) -> Result<Vec<(PolicyContext, Option<GithubDenial>)>, GithubDenial> {
1269    let Some(batch) = github else {
1270        return Ok(vec![(context.clone(), None)]);
1271    };
1272    let mut contexts = Vec::new();
1273    for event in batch.events() {
1274        let full = serde_json::to_value(event).map_err(|source| {
1275            tracing::warn!(event="broker_policy_context_failed",error=%source,"broker.policy.context.failed");
1276            GithubDenial {
1277                phase: GithubDenier::Facts,
1278                delivery: event.delivery.clone(),
1279            }
1280        })?;
1281        let mut stripped = full.clone();
1282        if let Some(record) = stripped.as_object_mut() {
1283            record.remove("authorSet");
1284        }
1285        for (value, phase) in [
1286            (stripped, GithubDenier::Facts),
1287            (full, GithubDenier::AuthorSet),
1288        ] {
1289            let mut pass = context.clone();
1290            pass.github = Some(value);
1291            contexts.push((
1292                pass,
1293                Some(GithubDenial {
1294                    phase,
1295                    delivery: event.delivery.clone(),
1296                }),
1297            ));
1298        }
1299    }
1300    Ok(contexts)
1301}
1302
1303fn policy_context(context: &AuthenticatedContext) -> PolicyContext {
1304    PolicyContext {
1305        via: context.via().map(|via| via.as_str().to_owned()),
1306        subject: context.attested_subject().map(Subject::canonical),
1307        agent: match context.actor() {
1308            Actor::Agent { agent } => Some(agent.as_str().to_owned()),
1309            Actor::Human { .. } | Actor::Service { .. } => None,
1310        },
1311        transport_kind: context.chat_scope().map(|scope| scope.kind.to_string()),
1312        transport: context
1313            .chat_scope()
1314            .map(|scope| scope.transport.to_string()),
1315        started_by: turn_started_by(context).map(|started| started.as_str().to_owned()),
1316        trigger: context
1317            .chat_scope()
1318            .map(|scope| scope.trigger.as_str().to_owned()),
1319        github: None,
1320        conversation: context.chat_scope().map(|scope| PolicyConversation {
1321            kind: scope.conversation.kind.as_str().to_owned(),
1322            container: scope.conversation.container.clone(),
1323            id: scope.conversation.id.clone(),
1324            thread: scope.conversation.thread.clone(),
1325        }),
1326    }
1327}
1328
1329#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1330#[serde(rename_all = "camelCase")]
1331enum TurnStartedBy {
1332    Person,
1333    Message,
1334    Wake,
1335    Job,
1336    Probe,
1337}
1338
1339impl TurnStartedBy {
1340    const fn as_str(self) -> &'static str {
1341        match self {
1342            Self::Person => "person",
1343            Self::Message => "message",
1344            Self::Wake => "wake",
1345            Self::Job => "job",
1346            Self::Probe => "probe",
1347        }
1348    }
1349}
1350
1351fn turn_started_by(context: &AuthenticatedContext) -> Option<TurnStartedBy> {
1352    context.chat_scope().map(|scope| match scope.trigger {
1353        Trigger::Message
1354            if context
1355                .attested_subject()
1356                .is_some_and(|subject| subject.principal_kind() == PrincipalKind::Person) =>
1357        {
1358            TurnStartedBy::Person
1359        }
1360        Trigger::Message => TurnStartedBy::Message,
1361        Trigger::Wake => TurnStartedBy::Wake,
1362        Trigger::Job => TurnStartedBy::Job,
1363        Trigger::Probe => TurnStartedBy::Probe,
1364    })
1365}
1366
1367fn probe_permits(context: &AuthenticatedContext, effect: EffectKind) -> bool {
1368    context
1369        .chat_scope()
1370        .is_none_or(|scope| scope.trigger != Trigger::Probe)
1371        || probe_admits(effect)
1372}
1373
1374const fn probe_admits(effect: EffectKind) -> bool {
1375    match effect {
1376        EffectKind::ReadOnly => true,
1377        EffectKind::LocalWrite | EffectKind::ExternalWrite => false,
1378    }
1379}
1380
1381fn validate_trusted_metadata(
1382    capability_id: &CapabilityId,
1383    set: &ConstraintSet,
1384    provider: &ProviderId,
1385    capability: &ProviderCapability,
1386) -> Result<(), BrokerBuildError> {
1387    if &set.provider != provider {
1388        return Err(BrokerBuildError::ProviderMismatch {
1389            capability: capability_id.clone(),
1390            expected: set.provider.clone(),
1391            actual: provider.clone(),
1392        });
1393    }
1394    for (field, matches) in [
1395        ("effect", set.effect == capability.effect),
1396        ("risk", set.risk == capability.risk),
1397    ] {
1398        if !matches {
1399            return Err(BrokerBuildError::CapabilityMetadataMismatch {
1400                capability: capability_id.clone(),
1401                field,
1402            });
1403        }
1404    }
1405    Ok(())
1406}
1407
1408fn validate_set_constraints(set: &ConstraintSet) -> Result<(), BrokerBuildError> {
1409    let constraints = &set.constraints;
1410    if constraints.timeout_ms == 0
1411        || constraints.secret_use.is_some()
1412        || (constraints.http.is_some() && constraints.storage.is_some())
1413    {
1414        return Err(BrokerBuildError::InvalidPolicyConstraints);
1415    }
1416    if let Some(storage) = &constraints.storage {
1417        let valid_effect = matches!(
1418            (storage.access, set.effect),
1419            (StorageAccess::ReadOnly, EffectKind::ReadOnly)
1420                | (StorageAccess::ReadWrite, EffectKind::LocalWrite)
1421        );
1422        if !valid_effect || set.effect == EffectKind::ExternalWrite {
1423            return Err(BrokerBuildError::InvalidPolicyConstraints);
1424        }
1425    }
1426    if let Some(asset) = &constraints.asset
1427        && ((asset.send && set.effect != EffectKind::ExternalWrite)
1428            || ((asset.attach || asset.remove) && set.effect == EffectKind::ReadOnly))
1429    {
1430        return Err(BrokerBuildError::InvalidPolicyConstraints);
1431    }
1432    let Some(http) = &constraints.http else {
1433        return Ok(());
1434    };
1435    http.validate()
1436        .map_err(|source| BrokerBuildError::InvalidHttpConstraints { source })?;
1437    Ok(())
1438}
1439
1440const MEMORY_PROMPT_NOTE: &str = "`memory recent` and `memory search` retrieve older turns of \
1441this chat. Do not claim to remember anything you have not retrieved.";
1442
1443#[derive(Clone, Debug, Eq, PartialEq)]
1444pub enum RouteConflict {
1445    DuplicateRole {
1446        route: CapabilityRoute,
1447        capabilities: Vec<CapabilityId>,
1448    },
1449    SplitProvider {
1450        providers: Vec<ProviderId>,
1451    },
1452    MissingChatStorage {
1453        capability: CapabilityId,
1454        route: CapabilityRoute,
1455        access: StorageAccess,
1456    },
1457}
1458
1459#[derive(Clone, Debug, Eq, PartialEq)]
1460pub enum NamespaceConflict {
1461    NotAgentScope {
1462        capability: CapabilityId,
1463        namespace: ProviderId,
1464        scope: StorageScope,
1465    },
1466    Mismatch {
1467        namespace: ProviderId,
1468        capabilities: Vec<(CapabilityId, StorageInterface)>,
1469    },
1470}
1471
1472impl fmt::Display for NamespaceConflict {
1473    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1474        match self {
1475            Self::NotAgentScope {
1476                capability,
1477                namespace,
1478                scope,
1479            } => write!(
1480                formatter,
1481                "capability {capability} names storage namespace {namespace} at scope {scope:?}; \
1482                 only agent scope may name a namespace"
1483            ),
1484            Self::Mismatch {
1485                namespace,
1486                capabilities,
1487            } => {
1488                write!(formatter, "storage namespace {namespace} is shared by")?;
1489                for (capability, interface) in capabilities {
1490                    write!(formatter, " {capability} ({interface:?})")?;
1491                }
1492                write!(
1493                    formatter,
1494                    "; every agent-scope capability in one namespace declares one interface"
1495                )
1496            }
1497        }
1498    }
1499}
1500
1501impl fmt::Display for RouteConflict {
1502    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1503        match self {
1504            Self::DuplicateRole {
1505                route,
1506                capabilities,
1507            } => {
1508                write!(formatter, "route {route} is claimed by")?;
1509                for capability in capabilities {
1510                    write!(formatter, " {capability}")?;
1511                }
1512                write!(
1513                    formatter,
1514                    "; exactly one constraint set may declare each chat-memory role"
1515                )
1516            }
1517            Self::SplitProvider { providers } => {
1518                write!(formatter, "chat-memory routes name providers")?;
1519                for provider in providers {
1520                    write!(formatter, " {provider}")?;
1521                }
1522                write!(formatter, "; one provider must own the whole surface")
1523            }
1524            Self::MissingChatStorage {
1525                capability,
1526                route,
1527                access,
1528            } => write!(
1529                formatter,
1530                "capability {capability} declares route {route} without jsonl chat storage at \
1531                 {access:?} access"
1532            ),
1533        }
1534    }
1535}
1536
1537#[derive(Debug, Error)]
1538pub enum BrokerBuildError {
1539    #[error("broker limit {field} must be greater than zero")]
1540    ZeroLimit { field: &'static str },
1541    #[error("operating system entropy is unavailable for the broker boot nonce")]
1542    BootEntropy {
1543        #[source]
1544        source: std::io::Error,
1545    },
1546    #[error("configuration contains {count} constraint sets; broker maximum is {maximum}")]
1547    TooManyConstraintSets { count: usize, maximum: usize },
1548    #[error("policy permits capability {capability}, which has no constraint set")]
1549    UnconstrainedCapability { capability: CapabilityId },
1550    #[error("configuration duplicates a constraint set for capability {capability}")]
1551    DuplicateConstraintSet { capability: CapabilityId },
1552    #[error("constraint set capability {capability} has no loaded provider route")]
1553    UnknownCapability { capability: CapabilityId },
1554    #[error(
1555        "constraint set expected provider {expected} for {capability}, but route selects {actual}"
1556    )]
1557    ProviderMismatch {
1558        capability: CapabilityId,
1559        expected: ProviderId,
1560        actual: ProviderId,
1561    },
1562    #[error("constraint set metadata {field} does not match loaded capability {capability}")]
1563    CapabilityMetadataMismatch {
1564        capability: CapabilityId,
1565        field: &'static str,
1566    },
1567    #[error("execution constraints are incomplete or overbroad")]
1568    InvalidPolicyConstraints,
1569    #[error("storage idle TTL must be a positive whole number of milliseconds fitting in u64")]
1570    InvalidStorageRetention,
1571    #[error("storage retention conflicts for namespace {namespace} and scope {scope:?}")]
1572    ConflictingStorageRetention {
1573        namespace: ProviderId,
1574        scope: StorageScope,
1575    },
1576    #[error("http execution constraints are invalid")]
1577    InvalidHttpConstraints {
1578        #[source]
1579        source: HttpConstraintsError,
1580    },
1581    #[error("execution constraints exceed component host ceilings")]
1582    HostConstraint {
1583        #[source]
1584        source: BrokerHostError,
1585    },
1586    #[error(
1587        "capability {capability} defaults to {secret} ({sink}), which needs exactly one binding \
1588         for that capability and sink; the map has {count}"
1589    )]
1590    DefaultSecretBindings {
1591        capability: CapabilityId,
1592        secret: SecretDrn,
1593        sink: SecretSinkKind,
1594        count: usize,
1595    },
1596    #[error("secret binding {binding} names no capability")]
1597    SecretBindingWithoutCapability { binding: String },
1598    #[error("configuration contains {count} secret bindings; broker maximum is {maximum}")]
1599    TooManySecretBindings { count: usize, maximum: usize },
1600    #[error("private secret map revision is invalid")]
1601    InvalidSecretMapRevision,
1602    #[error("secret binding {binding:?} is invalid")]
1603    InvalidSecretBinding {
1604        binding: String,
1605        #[source]
1606        source: dekopon_capability::SecretUseGrantError,
1607    },
1608    #[error("secret binding identifier {binding:?} is duplicated")]
1609    DuplicateSecretBinding { binding: String },
1610    #[error("secret {secret} has conflicting bindings for capability {capability}")]
1611    ConflictingSecretBinding {
1612        secret: SecretDrn,
1613        capability: CapabilityId,
1614    },
1615    #[error("secret binding {binding:?} names capability {capability} with no constraint set")]
1616    SecretBindingUnknownCapability {
1617        binding: String,
1618        capability: CapabilityId,
1619    },
1620    #[error("secret binding {binding:?} names a capability with no HTTP authority")]
1621    SecretBindingWithoutHttp { binding: String },
1622    #[error("secret binding {binding:?} exceeds its capability HTTP constraints")]
1623    SecretBindingExceedsCapability { binding: String },
1624    #[error("attestor namespace scope {scope:?} is not a canonical subject prefix")]
1625    InvalidAttestorScope { scope: String },
1626    #[error("chat-memory bounds do not compose with provider/storage ceilings")]
1627    InvalidChatMemory,
1628    #[error(
1629        "chatMemory is configured but no constraint set declares route: {}; the surface is all \
1630         three roles — chatMemoryRecord, chatMemoryRecent, chatMemorySearch — with exactly one \
1631         constraint set declaring each and all of them naming one provider",
1632        roles.iter().map(|role| role.as_str()).collect::<Vec<_>>().join(", ")
1633    )]
1634    UnroutedChatMemory { roles: Vec<CapabilityRoute> },
1635    #[error("constraint sets declare {} conflicting capability route(s): {}", conflicts.len(),
1636        conflicts.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
1637    ConflictingRoutes { conflicts: Vec<RouteConflict> },
1638    #[error("constraint sets declare {} conflicting storage namespace(s): {}", conflicts.len(),
1639        conflicts.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
1640    ConflictingStorageNamespaces { conflicts: Vec<NamespaceConflict> },
1641    #[error("identity mapping duplicates subject {subject:?}")]
1642    DuplicateSubjectMapping { subject: String },
1643}
1644
1645#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1646#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
1647pub enum AuditEvent {
1648    Decision {
1649        authority: Box<DecisionAuthority>,
1650        invocation: InvocationId,
1651        trace: TraceId,
1652        #[serde(default, skip_serializing_if = "Option::is_none")]
1653        principal: Option<PrincipalId>,
1654        #[serde(default, skip_serializing_if = "Option::is_none")]
1655        actor: Option<Actor>,
1656        #[serde(default, skip_serializing_if = "Option::is_none")]
1657        via: Option<PrincipalId>,
1658        #[serde(default, skip_serializing_if = "Option::is_none")]
1659        attested_subject: Option<Subject>,
1660        capability: CapabilityId,
1661        #[serde(default, skip_serializing_if = "Option::is_none")]
1662        secret: Option<SecretDrn>,
1663        #[serde(default, skip_serializing_if = "Option::is_none")]
1664        secret_sink: Option<SecretSinkKind>,
1665        #[serde(skip_serializing_if = "Option::is_none")]
1666        provider: Option<ProviderId>,
1667        #[serde(default, skip_serializing_if = "Option::is_none")]
1668        authorized_by: Option<PrincipalId>,
1669        decision_id: String,
1670        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1671        policy_ids: Vec<String>,
1672        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1673        policy_error_ids: Vec<String>,
1674        #[serde(default, skip_serializing_if = "Option::is_none")]
1675        policy_errors_present: Option<bool>,
1676        #[serde(default)]
1677        decision_point: String,
1678        #[serde(default, skip_serializing_if = "Option::is_none")]
1679        policy_digest: Option<String>,
1680        allowed: bool,
1681        #[serde(skip_serializing_if = "Option::is_none")]
1682        reason: Option<String>,
1683        decision_digest: String,
1684        #[serde(default, skip_serializing_if = "Option::is_none")]
1685        storage_scope_commitment: Option<StorageScopeCommitment>,
1686        #[serde(default, skip_serializing_if = "Option::is_none")]
1687        storage: Option<StorageEvidence>,
1688    },
1689    Execution {
1690        invocation: InvocationId,
1691        trace: TraceId,
1692        #[serde(default, skip_serializing_if = "Option::is_none")]
1693        principal: Option<PrincipalId>,
1694        #[serde(default, skip_serializing_if = "Option::is_none")]
1695        actor: Option<Actor>,
1696        #[serde(default, skip_serializing_if = "Option::is_none")]
1697        via: Option<PrincipalId>,
1698        #[serde(default, skip_serializing_if = "Option::is_none")]
1699        attested_subject: Option<Subject>,
1700        capability: CapabilityId,
1701        #[serde(default, skip_serializing_if = "Option::is_none")]
1702        secret: Option<SecretDrn>,
1703        #[serde(default, skip_serializing_if = "Option::is_none")]
1704        secret_sink: Option<SecretSinkKind>,
1705        #[serde(default, skip_serializing_if = "Option::is_none")]
1706        provider: Option<ProviderId>,
1707        #[serde(default, skip_serializing_if = "Option::is_none")]
1708        authorized_by: Option<PrincipalId>,
1709        decision_id: String,
1710        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1711        policy_ids: Vec<String>,
1712        #[serde(default, skip_serializing_if = "Option::is_none")]
1713        policy_digest: Option<String>,
1714        #[serde(default, skip_serializing_if = "Option::is_none")]
1715        provider_artifact_sha256: Option<String>,
1716        effect: EffectKind,
1717        risk: RiskLevel,
1718        outcome: InvocationOutcome,
1719        #[serde(skip_serializing_if = "Option::is_none")]
1720        exit_status: Option<std::num::NonZeroU8>,
1721        duration_ms: u64,
1722        #[serde(skip_serializing_if = "Option::is_none")]
1723        error: Option<String>,
1724        #[serde(default, skip_serializing_if = "Option::is_none")]
1725        error_detail: Option<ProviderFailureDetail>,
1726        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1727        http_calls: Vec<HttpCallEvidence>,
1728        #[serde(default, skip_serializing_if = "Option::is_none")]
1729        storage_scope_commitment: Option<StorageScopeCommitment>,
1730        #[serde(default, skip_serializing_if = "Option::is_none")]
1731        storage: Option<StorageEvidence>,
1732    },
1733}
1734
1735pub trait AuditLog: Send + Sync + 'static {
1736    fn append(&self, event: AuditEvent) -> impl Future<Output = Result<(), AuditError>> + Send;
1737}
1738
1739#[derive(Debug)]
1740pub struct InMemoryAuditLog {
1741    maximum: usize,
1742    state: parking_lot::Mutex<Vec<AuditEvent>>,
1743}
1744
1745impl InMemoryAuditLog {
1746    pub fn new(maximum: usize) -> Result<Self, AuditConfigurationError> {
1747        if maximum == 0 {
1748            return Err(AuditConfigurationError::ZeroMaximum);
1749        }
1750        Ok(Self {
1751            maximum,
1752            state: parking_lot::Mutex::new(Vec::new()),
1753        })
1754    }
1755
1756    pub fn records(&self) -> Vec<AuditEvent> {
1757        self.state.lock().clone()
1758    }
1759}
1760
1761impl AuditLog for InMemoryAuditLog {
1762    async fn append(&self, event: AuditEvent) -> Result<(), AuditError> {
1763        let mut records = self.state.lock();
1764        if records.len() >= self.maximum {
1765            return Err(AuditError::Full {
1766                maximum: self.maximum,
1767            });
1768        }
1769        records.push(event);
1770        Ok(())
1771    }
1772}
1773
1774#[derive(Clone, Copy, Debug, Default)]
1775pub struct TraceOnlyAuditLog;
1776
1777impl AuditLog for TraceOnlyAuditLog {
1778    async fn append(&self, _event: AuditEvent) -> Result<(), AuditError> {
1779        Ok(())
1780    }
1781}
1782
1783#[derive(Clone, Debug, Eq, Error, PartialEq)]
1784pub enum AuditConfigurationError {
1785    #[error("audit record maximum must be greater than zero")]
1786    ZeroMaximum,
1787}
1788
1789#[derive(Debug, Error)]
1790pub enum AuditError {
1791    #[error("audit log reached its {maximum}-record bound")]
1792    Full { maximum: usize },
1793}
1794
1795impl AuditError {
1796    #[must_use]
1797    pub const fn category(&self) -> &'static str {
1798        match self {
1799            Self::Full { .. } => "full",
1800        }
1801    }
1802}
1803
1804#[derive(Debug)]
1805pub struct Broker<A> {
1806    registry: BrokerProviderRegistry,
1807    policy: Arc<PolicyEngine>,
1808    policy_digest: String,
1809    constraints: ConstraintCatalog,
1810    secrets: SecretCatalog,
1811    identities: IdentityDirectory,
1812    broker_principal: PrincipalId,
1813    gate: AuthorizationGate,
1814    audit: Arc<A>,
1815    chat_memory: Option<ChatMemoryConfig>,
1816    continuity: Option<ContinuityState>,
1817    console_smoke_nonce: [u8; 16],
1818}
1819
1820impl<A> Broker<A>
1821where
1822    A: AuditLog,
1823{
1824    #[allow(
1825        clippy::too_many_arguments,
1826        reason = "each trusted input is a separate owner-controlled store; bundling them into one \
1827                  struct would let a caller assemble policy, constraints and identity \
1828                  mapping from mismatched sources without the type system noticing"
1829    )]
1830    pub fn new(
1831        registry: BrokerProviderRegistry,
1832        broker_principal: PrincipalId,
1833        policy: PolicyEngine,
1834        constraints: ConstraintCatalog,
1835        identities: IdentityDirectory,
1836        audit: Arc<A>,
1837        limits: BrokerLimits,
1838    ) -> Result<Self, BrokerBuildError> {
1839        Self::start(
1840            registry,
1841            broker_principal,
1842            policy,
1843            constraints,
1844            identities,
1845            audit,
1846            limits,
1847            Leniency::Strict,
1848        )
1849        .map(|(broker, _)| broker)
1850    }
1851
1852    #[allow(
1853        clippy::too_many_arguments,
1854        reason = "each trusted input is a separate owner-controlled store; bundling them into one \
1855                  struct would let a caller assemble policy, constraints and identity \
1856                  mapping from mismatched sources without the type system noticing"
1857    )]
1858    pub fn start(
1859        registry: BrokerProviderRegistry,
1860        broker_principal: PrincipalId,
1861        policy: PolicyEngine,
1862        constraints: ConstraintCatalog,
1863        identities: IdentityDirectory,
1864        audit: Arc<A>,
1865        limits: BrokerLimits,
1866        leniency: Leniency,
1867    ) -> Result<(Self, Vec<StartupWarning>), BrokerBuildError> {
1868        let mut constraints = constraints;
1869        let mut warnings = Vec::new();
1870        if limits.max_constraint_sets == 0 {
1871            return Err(BrokerBuildError::ZeroLimit {
1872                field: "max_constraint_sets",
1873            });
1874        }
1875        if leniency == Leniency::Tolerant {
1876            // Unrouted constraint sets must be dropped before validate runs, since validate cannot
1877            // prove a set with no route either way.
1878            for capability in constraints.retain_routed(&registry) {
1879                warnings.push(StartupWarning::UnroutedConstraintSet { capability });
1880            }
1881        }
1882        constraints.validate(&registry, limits.max_constraint_sets)?;
1883        for capability in constraints.sets.keys() {
1884            if !policy.names_in_a_permit(capability) {
1885                warnings.push(StartupWarning::UnreachableCapability {
1886                    capability: capability.clone(),
1887                });
1888            }
1889        }
1890        for capability in policy.referenced_capabilities() {
1891            if constraints.get(capability).is_none() {
1892                match leniency {
1893                    Leniency::Strict => {
1894                        return Err(BrokerBuildError::UnconstrainedCapability {
1895                            capability: capability.clone(),
1896                        });
1897                    }
1898                    Leniency::Tolerant => {
1899                        warnings.push(StartupWarning::UnconstrainedCapability {
1900                            capability: capability.clone(),
1901                        });
1902                    }
1903                }
1904            }
1905        }
1906        let mut console_smoke_nonce = [0; 16];
1907        getrandom::fill(&mut console_smoke_nonce).map_err(|source| {
1908            BrokerBuildError::BootEntropy {
1909                source: std::io::Error::other(source),
1910            }
1911        })?;
1912        Ok((
1913            Self {
1914                registry,
1915                policy_digest: policy.digest().to_owned(),
1916                policy: Arc::new(policy),
1917                constraints,
1918                secrets: SecretCatalog::empty(),
1919                identities,
1920                broker_principal,
1921                gate: AuthorizationGate::new(),
1922                audit,
1923                chat_memory: None,
1924                continuity: None,
1925                console_smoke_nonce,
1926            },
1927            warnings,
1928        ))
1929    }
1930
1931    pub fn with_secret_catalog(mut self, secrets: SecretCatalog) -> Result<Self, BrokerBuildError> {
1932        secrets.validate(&self.constraints)?;
1933        self.secrets = secrets;
1934        Ok(self)
1935    }
1936
1937    #[must_use]
1938    pub fn policy_digest(&self) -> &str {
1939        &self.policy_digest
1940    }
1941
1942    #[must_use]
1943    pub fn storage_retention_policies(&self) -> RetentionPolicies {
1944        self.constraints
1945            .retention_policies()
1946            .expect("validated storage retention policy")
1947    }
1948
1949    pub fn with_chat_memory(mut self, config: ChatMemoryConfig) -> Result<Self, BrokerBuildError> {
1950        let storage_host = self
1951            .registry
1952            .storage_host()
1953            .ok_or(BrokerBuildError::InvalidChatMemory)?;
1954        config.validate(storage_host.limits())?;
1955        config.validate_host_limits(self.registry.host_limits())?;
1956        let expected = [
1957            (
1958                CapabilityRoute::ChatMemoryRecord,
1959                EffectKind::LocalWrite,
1960                RiskLevel::Medium,
1961            ),
1962            (
1963                CapabilityRoute::ChatMemoryRecent,
1964                EffectKind::ReadOnly,
1965                RiskLevel::High,
1966            ),
1967            (
1968                CapabilityRoute::ChatMemorySearch,
1969                EffectKind::ReadOnly,
1970                RiskLevel::High,
1971            ),
1972        ];
1973        // This unrouted-role check must run before the shape-check loop below, whose expect call
1974        // would panic if a role stayed unrouted.
1975        let unrouted = expected
1976            .iter()
1977            .map(|(route, ..)| *route)
1978            .filter(|route| self.constraints.routed(*route).is_none())
1979            .collect::<Vec<_>>();
1980        if !unrouted.is_empty() {
1981            return Err(BrokerBuildError::UnroutedChatMemory { roles: unrouted });
1982        }
1983        let mut routed = BTreeSet::new();
1984        for (route, effect, risk) in expected {
1985            let (capability, set) = self
1986                .constraints
1987                .routed(route)
1988                .expect("every chat-memory role was proved routed above");
1989            routed.insert(capability.as_str());
1990            if set.effect != effect
1991                || set.risk != risk
1992                || set.default_secret_use.is_some()
1993                || set.constraints.http.is_some()
1994            {
1995                return Err(BrokerBuildError::InvalidChatMemory);
1996            }
1997        }
1998        // The routed provider must own exactly these three capabilities and no more, since a fourth
1999        // route on that same component would be reachable under the storage authority the memory
2000        // surface grants it.
2001        let provider = self
2002            .constraints
2003            .chat_memory_provider()
2004            .ok_or(BrokerBuildError::InvalidChatMemory)?;
2005        let memory_provider = self
2006            .registry
2007            .manifests()
2008            .find(|manifest| &manifest.id == provider)
2009            .ok_or(BrokerBuildError::InvalidChatMemory)?;
2010        let declared = memory_provider
2011            .capabilities
2012            .iter()
2013            .map(|capability| capability.id.as_str())
2014            .collect::<BTreeSet<_>>();
2015        if declared != routed {
2016            return Err(BrokerBuildError::InvalidChatMemory);
2017        }
2018        self.chat_memory = Some(config);
2019        #[allow(
2020            clippy::map_err_ignore,
2021            reason = "the only failure is a missing storage host, which this method refused above"
2022        )]
2023        let current = self
2024            .current_operational()
2025            .map_err(|_| BrokerBuildError::InvalidChatMemory)?;
2026        let migration = self
2027            .chat_memory
2028            .as_ref()
2029            .and_then(|memory| memory.continuity_migration.clone());
2030        self.continuity = Some(self.continuity_state(&current, migration.as_ref()));
2031        Ok(self)
2032    }
2033
2034    fn capability_uses_storage(&self, capability: &CapabilityId) -> bool {
2035        self.constraints
2036            .get(capability)
2037            .is_some_and(|set| set.constraints.storage.is_some() || set.route.is_chat_memory())
2038    }
2039
2040    pub fn authorize_invocation(
2041        &self,
2042        context: &AuthenticatedContext,
2043        capability: &CapabilityId,
2044    ) -> Result<CapabilityDecision, Refusal> {
2045        // This check is the actual enforcement under Leniency::Tolerant, not just defense in
2046        // depth; never weaken it into an assertion or fold it into the policy decision, or an
2047        // unrouted but policy-anticipated capability would stop being denied.
2048        let Some(set) = self.constraints.get(capability).cloned() else {
2049            return Err(unevaluated_refusal("unconstrained-capability"));
2050        };
2051        if !probe_permits(context, set.effect) {
2052            return Err(unevaluated_refusal("probe-write"));
2053        }
2054        if set.constraints.storage.is_some() && context.chat_scope().is_none() {
2055            return Err(unevaluated_refusal("chat-scope-required"));
2056        }
2057        if !storage_scope_permits(context, &set) {
2058            return Err(unevaluated_refusal("policy-denied"));
2059        }
2060        let slots = render_chat_slots(set.constraints.http.as_ref(), context.chat_scope())
2061            .map_err(unevaluated_refusal)?;
2062        let decision = self.authorize_capability(context, capability, &set, None);
2063        if !decision.allowed {
2064            let reason = denial_reason(&decision, "policy-denied");
2065            return Err(Refusal {
2066                evaluation: Some(Box::new(PolicyEvaluation {
2067                    errors_present: decision.policy.errors_present,
2068                    cause: decision.policy.refusal,
2069                    space: decision.space,
2070                    github_denial: decision.github_denial,
2071                })),
2072                ..determined_refusal(reason, decision.policy.determining_policy_ids)
2073            });
2074        }
2075        Ok(CapabilityDecision {
2076            set,
2077            policy_ids: decision.policy.determining_policy_ids,
2078            slots,
2079            space: decision.space,
2080            errors_present: decision.policy.errors_present,
2081        })
2082    }
2083
2084    pub fn secret_use_or_default(
2085        &self,
2086        actor: &Actor,
2087        capability: &CapabilityId,
2088        proposed: Option<SecretUseProposal>,
2089    ) -> Result<Option<SecretUseProposal>, Refusal> {
2090        if proposed.is_some() {
2091            return Ok(proposed);
2092        }
2093        let Some(set) = self.constraints.get(capability) else {
2094            return Ok(None);
2095        };
2096        let Some((secret, sink)) = self.constraints.effective_default(set, actor) else {
2097            return Ok(None);
2098        };
2099        self.secrets
2100            .default_binding(capability, secret, sink)
2101            .map(|binding| Some(binding.proposal()))
2102            .ok_or_else(|| unevaluated_refusal("secret-denied"))
2103    }
2104
2105    fn effective_default_proposal(
2106        &self,
2107        actor: &Actor,
2108        capability: &CapabilityId,
2109    ) -> Option<SecretUseProposal> {
2110        let set = self.constraints.get(capability)?;
2111        let (secret, sink) = self.constraints.effective_default(set, actor)?;
2112        self.secrets
2113            .default_binding(capability, secret, sink)
2114            .map(SecretUseBinding::proposal)
2115    }
2116
2117    fn selection(
2118        &self,
2119        actor: &Actor,
2120        capability: &CapabilityId,
2121        proposal: &SecretUseProposal,
2122    ) -> SecretSelection {
2123        if self.effective_default_proposal(actor, capability).as_ref() == Some(proposal) {
2124            SecretSelection::Default
2125        } else {
2126            SecretSelection::Proposed
2127        }
2128    }
2129
2130    pub fn bind_secret_use(
2131        &self,
2132        context: &AuthenticatedContext,
2133        capability: &CapabilityId,
2134        decision: &mut CapabilityDecision,
2135        secret_use: Option<&SecretUseProposal>,
2136    ) -> Result<(), Refusal> {
2137        let Some(secret_use) = secret_use else {
2138            decision.set.constraints.secret_use = None;
2139            return Ok(());
2140        };
2141        let Some(binding) = self.secrets.binding(capability, secret_use) else {
2142            return Err(determined_refusal(
2143                "secret-denied",
2144                decision.policy_ids.clone(),
2145            ));
2146        };
2147        let selection = self.selection(context.actor(), capability, secret_use);
2148        let span = tracing::Span::current();
2149        span.record("secret", secret_use.secret().as_str());
2150        span.record("secret.selection", selection.as_str());
2151        let secret_decision =
2152            self.authorize_secret_use(context, capability, &decision.set, secret_use, selection);
2153        let secret_allowed = secret_decision.allowed;
2154        let secret_errors = secret_decision.errors_present;
2155        decision.errors_present |= secret_errors;
2156        merge_space_decision(&mut decision.space, secret_decision.space);
2157        decision
2158            .policy_ids
2159            .extend(secret_decision.policy.determining_policy_ids);
2160        decision.policy_ids.sort();
2161        decision.policy_ids.dedup();
2162        if !secret_allowed {
2163            return Err(Refusal {
2164                evaluation: Some(Box::new(PolicyEvaluation {
2165                    errors_present: secret_errors,
2166                    cause: None,
2167                    space: decision.space.clone(),
2168                    github_denial: secret_decision.github_denial,
2169                })),
2170                ..determined_refusal("secret-denied", decision.policy_ids.clone())
2171            });
2172        }
2173        decision.set.constraints.secret_use = Some(self.secrets.grant(binding));
2174        Ok(())
2175    }
2176
2177    fn authorize_capability(
2178        &self,
2179        context: &AuthenticatedContext,
2180        capability: &CapabilityId,
2181        set: &ConstraintSet,
2182        facts: Option<dekopon_policy::HttpRequestFacts>,
2183    ) -> EvaluatedDecision {
2184        let request = PolicyRequest {
2185            principal: context.principal().clone(),
2186            target: PolicyTarget::Capability {
2187                capability: capability.clone(),
2188                provider: set.provider.clone(),
2189                effect: set.effect,
2190                risk: set.risk,
2191            },
2192            context: policy_context(context),
2193        };
2194        Self::evaluate(
2195            &self.policy,
2196            request,
2197            facts,
2198            context.space.as_ref(),
2199            context.chat_scope().and_then(|scope| scope.github.as_ref()),
2200        )
2201    }
2202
2203    fn evaluate(
2204        policy: &PolicyEngine,
2205        request: PolicyRequest,
2206        facts: Option<dekopon_policy::HttpRequestFacts>,
2207        space: Option<&PrincipalId>,
2208        github: Option<&dekopon_core::github::GithubBatch>,
2209    ) -> EvaluatedDecision {
2210        let evaluate = |request, facts| match facts {
2211            Some(facts) => policy.authorize_http(request, facts),
2212            None => policy.authorize(request),
2213        };
2214        let contexts = match policy_contexts(&request.context, github) {
2215            Ok(contexts) => contexts,
2216            Err(denial) => {
2217                return EvaluatedDecision {
2218                    policy: PolicyDecision {
2219                        errors_present: true,
2220                        refusal: Some("github-context".to_owned()),
2221                        ..PolicyDecision::default()
2222                    },
2223                    space: None,
2224                    github_denial: Some(denial),
2225                };
2226            }
2227        };
2228        let mut result = EvaluatedDecision {
2229            policy: PolicyDecision {
2230                allowed: true,
2231                ..PolicyDecision::default()
2232            },
2233            space: None,
2234            github_denial: None,
2235        };
2236        for (context, coordinate) in contexts {
2237            let request = PolicyRequest {
2238                context,
2239                ..request.clone()
2240            };
2241            let asker = evaluate(request.clone(), facts.clone());
2242            let mut pass = EvaluatedDecision {
2243                policy: asker,
2244                space: None,
2245                github_denial: None,
2246            };
2247            if let Some(id) = space.filter(|id| **id == request.principal) {
2248                pass.space = Some(SpaceDecision {
2249                    id: id.clone(),
2250                    asker_allowed: None,
2251                    allowed: Some(pass.policy.allowed),
2252                    policy_ids: pass.policy.determining_policy_ids.clone(),
2253                    denied_by: None,
2254                });
2255            } else if let Some(id) = space {
2256                let mut verdict = evaluate(
2257                    PolicyRequest {
2258                        principal: id.clone(),
2259                        ..request
2260                    },
2261                    facts.clone(),
2262                );
2263                pass.space = Some(SpaceDecision {
2264                    id: id.clone(),
2265                    asker_allowed: Some(pass.policy.allowed),
2266                    allowed: Some(verdict.allowed),
2267                    policy_ids: std::mem::take(&mut verdict.determining_policy_ids),
2268                    denied_by: denying_principal(pass.policy.allowed, verdict.allowed),
2269                });
2270                merge_policy_decision(&mut pass.policy, verdict);
2271            }
2272            if !pass.policy.allowed && result.github_denial.is_none() {
2273                result.github_denial = coordinate;
2274            }
2275            merge_policy_decision(&mut result.policy, pass.policy);
2276            merge_space_decision(&mut result.space, pass.space);
2277        }
2278        result
2279    }
2280
2281    fn authorize_secret_use(
2282        &self,
2283        context: &AuthenticatedContext,
2284        capability: &CapabilityId,
2285        set: &ConstraintSet,
2286        proposal: &SecretUseProposal,
2287        selection: SecretSelection,
2288    ) -> EvaluatedDecision {
2289        Self::evaluate(
2290            &self.policy,
2291            PolicyRequest {
2292                principal: context.principal().clone(),
2293                target: PolicyTarget::SecretUse {
2294                    secret: proposal.secret().clone(),
2295                    capability: capability.clone(),
2296                    provider: set.provider.clone(),
2297                    sink: proposal.sink(),
2298                    selection,
2299                },
2300                context: policy_context(context),
2301            },
2302            None,
2303            context.space.as_ref(),
2304            context.chat_scope().and_then(|scope| scope.github.as_ref()),
2305        )
2306    }
2307
2308    fn authorize_agent_prompt(
2309        &self,
2310        context: &AuthenticatedContext,
2311        agent: &AgentId,
2312    ) -> EvaluatedDecision {
2313        Self::evaluate(
2314            &self.policy,
2315            PolicyRequest {
2316                principal: context.principal().clone(),
2317                target: PolicyTarget::AgentPrompt {
2318                    agent: agent.clone(),
2319                },
2320                context: policy_context(context),
2321            },
2322            None,
2323            context.space.as_ref(),
2324            context.chat_scope().and_then(|scope| scope.github.as_ref()),
2325        )
2326    }
2327
2328    fn authorized_sets(
2329        &self,
2330        context: &AuthenticatedContext,
2331    ) -> Vec<(&CapabilityId, &ConstraintSet)> {
2332        self.constraints
2333            .iter()
2334            .filter(|(capability, set)| {
2335                set.route.is_generic()
2336                    && storage_scope_permits(context, set)
2337                    && (set.constraints.storage.is_none() || context.chat_scope().is_some())
2338                    && render_chat_slots(set.constraints.http.as_ref(), context.chat_scope())
2339                        .is_ok()
2340                    && probe_permits(context, set.effect)
2341                    && self
2342                        .authorize_capability(context, capability, set, None)
2343                        .allowed
2344            })
2345            .collect()
2346    }
2347
2348    #[must_use]
2349    pub fn command_words(&self, context: &AuthenticatedContext) -> Vec<String> {
2350        self.reachable_command_words(context, &self.authorized_sets(context))
2351    }
2352
2353    #[must_use]
2354    pub fn command_word_help(&self, context: &AuthenticatedContext) -> BTreeMap<String, String> {
2355        let words = self.command_words(context);
2356        self.command_word_help_for(&words)
2357    }
2358
2359    fn command_word_help_for(&self, words: &[String]) -> BTreeMap<String, String> {
2360        let all = self.registry.command_word_help();
2361        words
2362            .iter()
2363            .filter_map(|word| all.get(word).map(|page| (word.clone(), page.clone())))
2364            .collect()
2365    }
2366
2367    fn reachable_providers(
2368        &self,
2369        context: &AuthenticatedContext,
2370        authorized: &[(&CapabilityId, &ConstraintSet)],
2371    ) -> BTreeSet<ProviderId> {
2372        let reachable = authorized
2373            .iter()
2374            .map(|(_, set)| set.provider.clone())
2375            .collect::<BTreeSet<_>>();
2376        let storage_providers = self
2377            .constraints
2378            .iter()
2379            .map(|(_, set)| set)
2380            .filter(|set| set.constraints.storage.is_some())
2381            .map(|set| set.provider.clone())
2382            .collect::<BTreeSet<_>>();
2383        let reserved = self.constraints.chat_memory_provider().cloned();
2384        reachable
2385            .into_iter()
2386            .filter(|provider| {
2387                Some(provider) != reserved.as_ref()
2388                    && (context.chat_scope().is_some() || !storage_providers.contains(provider))
2389            })
2390            .collect()
2391    }
2392
2393    fn reachable_command_words(
2394        &self,
2395        context: &AuthenticatedContext,
2396        authorized: &[(&CapabilityId, &ConstraintSet)],
2397    ) -> Vec<String> {
2398        let reachable = self.reachable_providers(context, authorized);
2399        let mut words = self
2400            .registry
2401            .command_words_by_provider()
2402            .into_iter()
2403            .filter(|(provider, _)| reachable.contains(*provider))
2404            .flat_map(|(_, words)| words.iter().cloned())
2405            .collect::<Vec<_>>();
2406        words.sort();
2407        words.dedup();
2408        words
2409    }
2410
2411    #[expect(
2412        clippy::too_many_arguments,
2413        reason = "reshaped by the unit that next rewrites this"
2414    )]
2415    pub async fn run_command(
2416        &self,
2417        peer: &AuthenticatedContext,
2418        grant: Option<&AttestorGrant>,
2419        attestation: Option<&Attestation>,
2420        word: &str,
2421        argv: &[String],
2422        stdin_piped: bool,
2423    ) -> Result<CommandRunOutcome, BrokerHostError> {
2424        let attested = match attestation {
2425            Some(claim) => {
2426                let (context, refusal) = self.resolve_context(peer, grant, claim);
2427                if let Some(refusal) = refusal {
2428                    report_inspection_refusal(&refusal, peer, claim.subjects.name(), &claim.agent);
2429                    if refusal.reason == CONSOLE_REAL_SCOPE_REASON {
2430                        return Ok(CommandRunOutcome::Rendered {
2431                            stdout: String::new(),
2432                            stderr: format!("{CONSOLE_REAL_SCOPE_REFUSAL}\n"),
2433                            status: 2,
2434                        });
2435                    }
2436                    return Err(BrokerHostError::UnknownCommandWord {
2437                        word: word.to_owned(),
2438                    });
2439                }
2440                Some((context, claim))
2441            }
2442            None => None,
2443        };
2444        let memory_word = self.is_chat_memory_word(word);
2445        let context = attested.as_ref().map_or(peer, |(context, _)| context);
2446        let installed = self
2447            .registry
2448            .command_words_by_provider()
2449            .into_iter()
2450            .any(|(_, words)| words.iter().any(|candidate| candidate == word));
2451        let reachable = if memory_word {
2452            attested.as_ref().is_some_and(|(context, claim)| {
2453                self.memory_surface(context, &claim.agent).is_some()
2454            })
2455        } else {
2456            self.command_words(context)
2457                .iter()
2458                .any(|candidate| candidate == word)
2459        };
2460        if installed && !reachable {
2461            return Ok(CommandRunOutcome::Rendered {
2462                stdout: String::new(),
2463                stderr: format!("dekopon-shell: {word}: not granted in this conversation\n"),
2464                status: 127,
2465            });
2466        }
2467        let outcome = self.registry.run_command(word, argv, stdin_piped).await?;
2468        if matches!(
2469            &outcome,
2470            CommandRunOutcome::Proposed { capability, .. } if {
2471                let route = self.route(capability);
2472                if memory_word { !route.is_chat_memory_retrieval() } else { route.is_chat_memory() }
2473            }
2474        ) {
2475            return Err(BrokerHostError::UnknownCommandWord {
2476                word: word.to_owned(),
2477            });
2478        }
2479        Ok(outcome)
2480    }
2481
2482    #[must_use]
2483    pub fn capabilities(&self, context: &AuthenticatedContext) -> Vec<AvailableCapability> {
2484        self.available_capabilities(&self.authorized_sets(context))
2485    }
2486
2487    #[must_use]
2488    #[allow(
2489        clippy::type_complexity,
2490        reason = "a session's reachable capabilities, command words, and each reachable word's \
2491                  --help page, in that order; a named struct would only rename what the three \
2492                  call sites already destructure by position"
2493    )]
2494    pub fn capability_view(
2495        &self,
2496        context: &AuthenticatedContext,
2497    ) -> (
2498        Vec<AvailableCapability>,
2499        Vec<String>,
2500        BTreeMap<String, String>,
2501    ) {
2502        let authorized = self.authorized_sets(context);
2503        let words = self.reachable_command_words(context, &authorized);
2504        let help = self.command_word_help_for(&words);
2505        (self.available_capabilities(&authorized), words, help)
2506    }
2507
2508    fn available_capabilities(
2509        &self,
2510        authorized: &[(&CapabilityId, &ConstraintSet)],
2511    ) -> Vec<AvailableCapability> {
2512        let mut capabilities = authorized
2513            .iter()
2514            .map(|(capability_id, set)| {
2515                let (_, manifest_capability) = self
2516                    .registry
2517                    .capability(capability_id)
2518                    .expect("constraint validation proves every capability route");
2519                let mut capability = manifest_capability.clone();
2520                capability.effect = set.effect;
2521                capability.risk = set.risk;
2522                AvailableCapability {
2523                    provider: set.provider.clone(),
2524                    capability,
2525                }
2526            })
2527            .collect::<Vec<_>>();
2528        capabilities.sort_by(|left, right| left.capability.id.cmp(&right.capability.id));
2529        capabilities
2530    }
2531
2532    #[must_use]
2533    #[allow(clippy::type_complexity, reason = "see capability_view")]
2534    pub fn capability_ceiling(
2535        &self,
2536    ) -> (
2537        Vec<AvailableCapability>,
2538        Vec<String>,
2539        BTreeMap<String, String>,
2540    ) {
2541        let mut capabilities = self
2542            .constraints
2543            .iter()
2544            .filter_map(|(capability, _)| self.available_capability(capability))
2545            .collect::<Vec<_>>();
2546        capabilities.sort_by(|left, right| left.capability.id.cmp(&right.capability.id));
2547        let words = self.registry.command_words();
2548        let help = self.registry.command_word_help();
2549        (capabilities, words, help)
2550    }
2551
2552    #[must_use]
2553    pub fn display_principal(&self, subjects: &AttestedSubject) -> Option<PrincipalId> {
2554        self.identities
2555            .resolve_attested(subjects)
2556            .ok()
2557            .flatten()
2558            .cloned()
2559    }
2560
2561    #[must_use]
2562    pub fn principal_ceiling(&self) -> Option<PrincipalId> {
2563        self.identities
2564            .principals()
2565            .max_by_key(|principal| principal.as_str().len())
2566            .cloned()
2567    }
2568
2569    #[must_use]
2570    pub fn chat_memory_ceiling(&self) -> Option<ChatMemorySurface> {
2571        let config = self.chat_memory.as_ref()?;
2572        Some(ChatMemorySurface {
2573            max_lookback_turns: config.max_lookback_turns,
2574            prompt_note: MEMORY_PROMPT_NOTE.to_owned(),
2575        })
2576    }
2577
2578    #[must_use]
2579    #[allow(clippy::type_complexity, reason = "see capability_view")]
2580    pub fn capability_surface(
2581        &self,
2582        peer: &AuthenticatedContext,
2583        grant: Option<&AttestorGrant>,
2584        attestation: Option<&Attestation>,
2585    ) -> Option<(
2586        Vec<AvailableCapability>,
2587        Vec<String>,
2588        BTreeMap<String, String>,
2589        Option<ChatMemorySurface>,
2590    )> {
2591        self.session_surface(peer, grant, attestation).ok()
2592    }
2593
2594    #[allow(clippy::type_complexity, reason = "see capability_view")]
2595    pub fn session_surface(
2596        &self,
2597        peer: &AuthenticatedContext,
2598        grant: Option<&AttestorGrant>,
2599        attestation: Option<&Attestation>,
2600    ) -> Result<
2601        (
2602            Vec<AvailableCapability>,
2603            Vec<String>,
2604            BTreeMap<String, String>,
2605            Option<ChatMemorySurface>,
2606        ),
2607        Refusal,
2608    > {
2609        let Some(claim) = attestation else {
2610            let (capabilities, words, help) = self.capability_view(peer);
2611            return Ok((capabilities, words, help, None));
2612        };
2613        let (context, refusal) = self.resolve_context(peer, grant, claim);
2614        if let Some(refusal) = refusal {
2615            report_inspection_refusal(&refusal, peer, claim.subjects.name(), &claim.agent);
2616            return Err(refusal);
2617        }
2618        let (mut capabilities, mut words, mut help) = self.capability_view(&context);
2619        let memory = self.memory_surface(&context, &claim.agent);
2620        if memory.is_some() {
2621            for route in [
2622                CapabilityRoute::ChatMemoryRecent,
2623                CapabilityRoute::ChatMemorySearch,
2624            ] {
2625                let (capability, _) = self
2626                    .constraints
2627                    .routed(route)
2628                    .ok_or_else(|| unevaluated_refusal("memory-route-unavailable"))?;
2629                capabilities.push(
2630                    self.available_capability(capability)
2631                        .ok_or_else(|| unevaluated_refusal("memory-route-unavailable"))?,
2632                );
2633            }
2634            capabilities.sort_by(|left, right| left.capability.id.cmp(&right.capability.id));
2635            let chat_memory_words = self.chat_memory_words();
2636            help.extend(self.command_word_help_for(&chat_memory_words));
2637            words.extend(chat_memory_words);
2638            words.sort();
2639            words.dedup();
2640        }
2641        Ok((capabilities, words, help, memory))
2642    }
2643
2644    pub fn space_grants(
2645        &self,
2646        peer: &AuthenticatedContext,
2647        grant: Option<&AttestorGrant>,
2648        attestation: Option<&Attestation>,
2649    ) -> Option<Vec<CapabilityId>> {
2650        let claim = attestation?;
2651        let (mut context, refusal) = self.resolve_context(peer, grant, claim);
2652        if refusal.is_some() {
2653            return None;
2654        }
2655        context.principal = context.space.as_ref()?.clone();
2656        let mut capabilities = self.capabilities(&context);
2657        if self.memory_surface(&context, &claim.agent).is_some() {
2658            for route in [
2659                CapabilityRoute::ChatMemoryRecent,
2660                CapabilityRoute::ChatMemorySearch,
2661            ] {
2662                let (capability, _) = self.constraints.routed(route)?;
2663                capabilities.push(self.available_capability(capability)?);
2664            }
2665        }
2666        capabilities.sort_by(|left, right| left.capability.id.cmp(&right.capability.id));
2667        Some(
2668            capabilities
2669                .into_iter()
2670                .map(|available| available.capability.id)
2671                .collect(),
2672        )
2673    }
2674
2675    pub async fn invoke(
2676        &self,
2677        peer: &AuthenticatedContext,
2678        grant: Option<&AttestorGrant>,
2679        attestation: Option<&Attestation>,
2680        mut request: InvocationRequest,
2681        assets: dekopon_broker_host::asset::AssetInputs,
2682    ) -> Result<AssetInvocationResult, BrokerError> {
2683        let (context, mut refusal) = match attestation {
2684            Some(claim) => self.resolve_context(peer, grant, claim),
2685            None => (peer.clone(), None),
2686        };
2687        let chat = attestation.filter(|claim| claim.scope.is_some());
2688        if chat.is_some() {
2689            refusal = refusal.map(|refusal| {
2690                if refusal.reason == CONSOLE_REAL_SCOPE_REASON {
2691                    refusal
2692                } else {
2693                    refusal.opaque()
2694                }
2695            });
2696        }
2697        if let Some(claim) = chat
2698            && refusal.is_none()
2699            && !claim.binds(&request.id)
2700        {
2701            refusal = Some(unevaluated_refusal(CHAT_REFUSAL));
2702        }
2703        let route = self.route(&request.capability);
2704        if refusal.is_none() {
2705            if let Some(claim) = chat {
2706                match route {
2707                    CapabilityRoute::Generic => {}
2708                    // Recording is reachable only through `record_delivered_turn`, whatever a
2709                    // proposal names and whatever attestation carries it.
2710                    CapabilityRoute::ChatMemoryRecord => {
2711                        refusal = Some(unevaluated_refusal("record-operation-required"));
2712                    }
2713                    CapabilityRoute::ChatMemoryRecent | CapabilityRoute::ChatMemorySearch => {
2714                        if self.memory_surface(&context, &claim.agent).is_none() {
2715                            refusal = Some(unevaluated_refusal("memory-unavailable"));
2716                        } else if let Err(reason) = self.curate_memory_input(route, &mut request) {
2717                            refusal = Some(unevaluated_refusal(reason));
2718                        }
2719                    }
2720                }
2721            } else if route.is_chat_memory() {
2722                refusal = Some(unevaluated_refusal("chat-scope-required"));
2723            }
2724        }
2725        let mut outputs = dekopon_broker_host::asset::AssetOutputs::default();
2726        let result = self
2727            .invoke_inner(&context, request, refusal, assets, &mut outputs)
2728            .await?;
2729        Ok(AssetInvocationResult {
2730            result,
2731            assets: outputs,
2732        })
2733    }
2734
2735    pub async fn record_delivered_turn(
2736        &self,
2737        peer: &AuthenticatedContext,
2738        grant: Option<&AttestorGrant>,
2739        attestation: &Attestation,
2740        mut turn: DeliveredTurnRequest,
2741    ) -> Result<InvocationResult, BrokerError> {
2742        let (context, claim_refusal) = self.resolve_context(peer, grant, attestation);
2743        if let Some(scope) = context.chat_scope()
2744            && scope.transport.as_str() == CONSOLE_SMOKE_TRANSPORT
2745        {
2746            turn.delivery = console_smoke_delivery(scope, turn.delivery);
2747        }
2748        let refusal = claim_refusal
2749            .map(|refusal| {
2750                if refusal.reason == CONSOLE_REAL_SCOPE_REASON {
2751                    refusal
2752                } else {
2753                    refusal.opaque()
2754                }
2755            })
2756            .or_else(|| {
2757                if !attestation.binds(&turn.id) {
2758                    Some(unevaluated_refusal(CHAT_REFUSAL))
2759                } else if self.memory_surface(&context, &attestation.agent).is_none() {
2760                    Some(unevaluated_refusal("memory-unavailable"))
2761                } else if !turn.is_bounded()
2762                    || !context
2763                        .chat_scope()
2764                        .is_some_and(|scope| turn.delivery.is_canonical_for(scope))
2765                {
2766                    Some(unevaluated_refusal("invalid-turn"))
2767                } else {
2768                    None
2769                }
2770            });
2771        let capability = self
2772            .constraints
2773            .routed(CapabilityRoute::ChatMemoryRecord)
2774            .map_or_else(
2775                || {
2776                    UNROUTED_RECORD_CAPABILITY
2777                        .parse()
2778                        .expect("reserved record label is a valid capability identifier")
2779                },
2780                |(capability, _)| capability.clone(),
2781            );
2782        let input = serde_json::json!({
2783            "delivery": turn.delivery,
2784            "user": turn.user(),
2785            "assistant": turn.assistant(),
2786        });
2787        let request = InvocationRequest {
2788            id: turn.id,
2789            capability,
2790            trace_parent: turn.trace_parent,
2791            secret_use: None,
2792            input,
2793        };
2794        self.invoke_inner(
2795            &context,
2796            request,
2797            refusal,
2798            Default::default(),
2799            &mut Default::default(),
2800        )
2801        .await
2802    }
2803
2804    pub fn resolve_context(
2805        &self,
2806        peer: &AuthenticatedContext,
2807        grant: Option<&AttestorGrant>,
2808        claim: &Attestation,
2809    ) -> (AuthenticatedContext, Option<Refusal>) {
2810        let refused = || {
2811            let mut context = peer.with_refused_subject(claim.subjects.name().clone());
2812            context.chat_scope = claim.scope.clone();
2813            context
2814        };
2815        let Some(grant) = grant else {
2816            return (refused(), Some(unevaluated_refusal("attestation-denied")));
2817        };
2818        if self.console_real_scope_refused(peer, claim) {
2819            return (refused(), Some(console_real_scope_refusal()));
2820        }
2821        let resolved = match self.identities.resolve_attested(&claim.subjects) {
2822            Ok(resolved) => resolved,
2823            Err(split) => {
2824                if !grant.permits(&claim.subjects) {
2825                    return (refused(), Some(unevaluated_refusal("attestation-denied")));
2826                }
2827                tracing::warn!(
2828                    event = "broker_subject_split",
2829                    subject = %claim.subjects.name(),
2830                    subject_id = claim.subjects.id_form().map(ToString::to_string),
2831                    principal = %split.name_principal,
2832                    id_principal = %split.id_principal,
2833                    via = %peer.principal(),
2834                    "broker.subject.split"
2835                );
2836                return (refused(), Some(unevaluated_refusal("split-subject")));
2837            }
2838        };
2839        let Some(principal) = resolved else {
2840            let mut refusal = unevaluated_refusal("unmapped-subject");
2841            if grant.permits(&claim.subjects) {
2842                refusal.session = dekopon_broker_protocol::SessionRefusal::UnmappedSubject;
2843            }
2844            return (refused(), Some(refusal));
2845        };
2846        if self.identities.principal_kind(principal) == PrincipalKind::Space
2847            && !claim.scope.as_ref().is_some_and(|scope| {
2848                (match scope.trigger {
2849                    Trigger::Wake | Trigger::Probe => true,
2850                    Trigger::Message | Trigger::Job => false,
2851                }) && scope.participant.is_none()
2852                    && scope.github.is_none()
2853                    && scope.delivery.is_none()
2854                    && space_subject(scope).as_ref() == Some(claim.subjects.name())
2855            })
2856        {
2857            return (refused(), Some(unevaluated_refusal("attestation-denied")));
2858        }
2859        let actor = Actor::Agent {
2860            agent: claim.agent.clone(),
2861        };
2862        if !grant.permits(&claim.subjects) {
2863            return (refused(), Some(unevaluated_refusal("attestation-denied")));
2864        }
2865        let scope = match &claim.scope {
2866            Some(scope) if scope.transport.as_str() == CONSOLE_SMOKE_TRANSPORT => {
2867                if !is_console_smoke_literal(scope) {
2868                    return (refused(), Some(unevaluated_refusal(CONSOLE_SMOKE_REFUSAL)));
2869                }
2870                let mut derived = scope.clone();
2871                derived.conversation.id = self.console_smoke_conversation(
2872                    peer.principal(),
2873                    claim.subjects.name(),
2874                    &claim.agent,
2875                );
2876                Some(derived)
2877            }
2878            scope => scope.clone(),
2879        };
2880        let derived = match scope {
2881            Some(scope) => {
2882                if !scope
2883                    .conversation
2884                    .is_canonical_for(scope.kind, claim.subjects.name())
2885                {
2886                    return (refused(), Some(unevaluated_refusal("attestation-denied")));
2887                }
2888                if scope
2889                    .delivery
2890                    .as_ref()
2891                    .is_some_and(|delivery| !delivery.is_canonical_for(&scope))
2892                {
2893                    return (refused(), Some(unevaluated_refusal("attestation-denied")));
2894                }
2895                if let Some(batch) = &scope.github {
2896                    let subject = match (claim.subjects.name().tenant(), claim.subjects.name().id())
2897                    {
2898                        (Some(owner), repo) => format!("{owner}/{repo}"),
2899                        _ => String::new(),
2900                    };
2901                    if scope.kind != ChatTransportKind::Github
2902                        || scope.trigger != Trigger::Message
2903                        || !matches!(&scope.delivery,Some(DeliveryIdentity::Github{delivery}) if delivery==batch.lead().delivery.as_str())
2904                        || batch.events().iter().any(|event| {
2905                            event.repository.full_name.as_str() != subject
2906                                || scope.conversation.thread.as_deref()
2907                                    != Some(event.thread().to_string().as_str())
2908                        })
2909                    {
2910                        return (refused(), Some(unevaluated_refusal("attestation-denied")));
2911                    }
2912                }
2913                AuthenticatedContext::attested_chat(
2914                    principal.clone(),
2915                    actor,
2916                    peer.principal().clone(),
2917                    claim.subjects.name().clone(),
2918                    scope,
2919                )
2920            }
2921            None => AuthenticatedContext::attested(
2922                principal.clone(),
2923                actor,
2924                peer.principal().clone(),
2925                claim.subjects.name().clone(),
2926            ),
2927        };
2928        let Ok(mut context) = derived else {
2929            return (refused(), Some(unevaluated_refusal("attestation-denied")));
2930        };
2931        context.space = context
2932            .chat_scope()
2933            .and_then(space_subject)
2934            .and_then(|subject| {
2935                self.identities
2936                    .resolve(&subject)
2937                    .filter(|mapped| self.identities.principal_kind(mapped) == PrincipalKind::Space)
2938                    .cloned()
2939            });
2940        let decision = self.authorize_agent_prompt(&context, &claim.agent);
2941        if decision.allowed {
2942            (context, None)
2943        } else {
2944            let named_denial = !decision.errors_present
2945                && match decision.space.as_ref().and_then(|space| space.denied_by) {
2946                    Some(DenyingPrincipal::Space) => false,
2947                    Some(DenyingPrincipal::Asker | DenyingPrincipal::Both) | None => true,
2948                };
2949            let mut refusal = decided_refusal(decision, "agent-denied");
2950            if named_denial {
2951                refusal.session = dekopon_broker_protocol::SessionRefusal::AgentDenied {
2952                    principal: principal.clone(),
2953                };
2954            }
2955            (context, Some(refusal))
2956        }
2957    }
2958
2959    #[must_use]
2960    pub fn console_real_scope_refused(
2961        &self,
2962        peer: &AuthenticatedContext,
2963        claim: &Attestation,
2964    ) -> bool {
2965        peer.principal().as_str() == "dekopon-console"
2966            && claim
2967                .scope
2968                .as_ref()
2969                .is_some_and(|scope| scope.transport.as_str() != CONSOLE_SMOKE_TRANSPORT)
2970    }
2971
2972    fn console_smoke_conversation(
2973        &self,
2974        via: &PrincipalId,
2975        subject: &Subject,
2976        agent: &AgentId,
2977    ) -> String {
2978        let mut hasher = Sha256::new();
2979        hasher.update(CONSOLE_SMOKE_DOMAIN);
2980        hasher.update(self.console_smoke_nonce);
2981        for part in [via.as_str(), subject.canonical().as_str(), agent.as_str()] {
2982            hasher.update(part);
2983            hasher.update([0]);
2984        }
2985        // The hyphen keeps the id outside the Slack, Discord, Telegram and WhatsApp id grammars.
2986        format!("smoke-{}", hex_bytes(&hasher.finalize()))
2987    }
2988
2989    fn route(&self, capability: &CapabilityId) -> CapabilityRoute {
2990        self.constraints
2991            .get(capability)
2992            .map_or(CapabilityRoute::Generic, |set| set.route)
2993    }
2994
2995    fn chat_memory_words(&self) -> Vec<String> {
2996        let Some(provider) = self.constraints.chat_memory_provider() else {
2997            return Vec::new();
2998        };
2999        self.registry
3000            .command_words_by_provider()
3001            .into_iter()
3002            .filter(|(candidate, _)| *candidate == provider)
3003            .flat_map(|(_, words)| words.iter().cloned())
3004            .collect()
3005    }
3006
3007    fn is_chat_memory_word(&self, word: &str) -> bool {
3008        self.chat_memory_words().iter().any(|value| value == word)
3009    }
3010
3011    fn memory_surface(
3012        &self,
3013        context: &AuthenticatedContext,
3014        agent: &AgentId,
3015    ) -> Option<ChatMemorySurface> {
3016        let config = self.chat_memory.as_ref()?;
3017        if !config.enabled_for(agent) || context.chat_scope().is_none() {
3018            return None;
3019        }
3020        for route in CapabilityRoute::CHAT_MEMORY {
3021            let (capability, set) = self.constraints.routed(route)?;
3022            if !self
3023                .authorize_capability(context, capability, set, None)
3024                .allowed
3025            {
3026                return None;
3027            }
3028        }
3029        Some(ChatMemorySurface {
3030            max_lookback_turns: config.max_lookback_turns,
3031            prompt_note: MEMORY_PROMPT_NOTE.to_owned(),
3032        })
3033    }
3034
3035    fn available_capability(&self, capability: &CapabilityId) -> Option<AvailableCapability> {
3036        let set = self.constraints.get(capability)?;
3037        let (_, manifest) = self.registry.capability(capability)?;
3038        let mut capability = manifest.clone();
3039        capability.effect = set.effect;
3040        capability.risk = set.risk;
3041        Some(AvailableCapability {
3042            provider: set.provider.clone(),
3043            capability,
3044        })
3045    }
3046
3047    fn effective_authority(
3048        &self,
3049        context: &AuthenticatedContext,
3050        memory_route: bool,
3051    ) -> Vec<(&CapabilityId, &ConstraintSet)> {
3052        let effective_memory_surface = memory_route
3053            && match context.actor() {
3054                Actor::Agent { agent } => self.memory_surface(context, agent).is_some(),
3055                Actor::Human { .. } | Actor::Service { .. } => false,
3056            };
3057        self.constraints
3058            .iter()
3059            .filter(|(capability, set)| {
3060                (set.route.is_generic() || effective_memory_surface)
3061                    && storage_scope_permits(context, set)
3062                    && self
3063                        .authorize_capability(context, capability, set, None)
3064                        .allowed
3065            })
3066            .collect()
3067    }
3068
3069    fn authorized_bindings<'a>(
3070        &'a self,
3071        context: &AuthenticatedContext,
3072        effective_capabilities: &BTreeSet<CapabilityId>,
3073    ) -> Vec<(&'a SecretUseBinding, &'a CapabilityId)> {
3074        self.secrets
3075            .authority_bindings()
3076            .into_iter()
3077            .flat_map(|binding| {
3078                binding
3079                    .capabilities
3080                    .iter()
3081                    .map(move |capability| (binding, capability))
3082            })
3083            .filter(|(binding, capability)| {
3084                let proposal = binding.proposal();
3085                effective_capabilities.contains(*capability)
3086                    && self.constraints.get(capability).is_some_and(|set| {
3087                        self.authorize_secret_use(
3088                            context,
3089                            capability,
3090                            set,
3091                            &proposal,
3092                            self.selection(context.actor(), capability, &proposal),
3093                        )
3094                        .allowed
3095                    })
3096            })
3097            .collect()
3098    }
3099
3100    fn current_operational(&self) -> Result<OperationalSnapshot, BrokerError> {
3101        Ok(OperationalSnapshot {
3102            host: self.registry.host_limits().clone(),
3103            storage: self
3104                .registry
3105                .storage_host()
3106                .ok_or(BrokerError::MemoryUnavailable)?
3107                .limits()
3108                .clone(),
3109            memory: self.chat_memory.clone(),
3110        })
3111    }
3112
3113    fn authority_surface_v1(
3114        &self,
3115        context: &AuthenticatedContext,
3116        interface: StorageInterface,
3117        memory_route: bool,
3118        operational: &OperationalSnapshot,
3119    ) -> Result<Vec<u8>, BrokerError> {
3120        let mut encoded = AuthorityEncoder::new();
3121        encoded.text("format", "dekopon-authority-surface-v1");
3122        encoded.text(
3123            "backend",
3124            if memory_route {
3125                "jsonl@0.1.0/chat-memory-format-v1"
3126            } else {
3127                match interface {
3128                    StorageInterface::Jsonl => "jsonl@0.1.0",
3129                    StorageInterface::DurableFiles => "durable-files@0.1.0/rollback-journal-v1",
3130                }
3131            },
3132        );
3133        // This authority encoding excludes principal mapping deliberately; remapping the same
3134        // subject without changing effective authority must never rotate the generation.
3135
3136        let artifacts = self
3137            .registry
3138            .loaded_provider_metadata()
3139            .map(|metadata| {
3140                (
3141                    metadata.manifest.id.clone(),
3142                    metadata.artifact_sha256.clone(),
3143                )
3144            })
3145            .collect::<BTreeMap<_, _>>();
3146        let effective = self.effective_authority(context, memory_route);
3147        let effective_capabilities = effective
3148            .iter()
3149            .map(|(capability, _)| (*capability).clone())
3150            .collect::<BTreeSet<_>>();
3151        encoded.number("capabilityCount", effective.len() as u128);
3152        for (capability, set) in effective {
3153            let digest = artifacts
3154                .get(&set.provider)
3155                .ok_or(BrokerError::MemoryUnavailable)?;
3156            encode_capability_authority(
3157                &mut encoded,
3158                capability,
3159                set,
3160                self.effective_default_proposal(context.actor(), capability)
3161                    .as_ref(),
3162                digest,
3163            );
3164        }
3165
3166        let secret_bindings = self.authorized_bindings(context, &effective_capabilities);
3167        if !secret_bindings.is_empty() {
3168            encoded.number("secretBindingCount", secret_bindings.len() as u128);
3169            encoded.optional_text("secretMapRevision", self.secrets.authority_revision());
3170        }
3171        for (binding, capability) in secret_bindings {
3172            encoded.text("secretBinding", &binding.binding_id);
3173            encoded.text("secretDrn", binding.secret.as_str());
3174            encoded.text("secretCapability", capability.as_str());
3175            encoded.text("secretSink", &binding.sink.to_string());
3176            encoded.optional_text("secretBasicUsername", binding.basic_username.as_deref());
3177            let mut hosts = binding.allowed_hosts.clone();
3178            hosts.sort();
3179            hosts.dedup();
3180            encoded.number("secretHostCount", hosts.len() as u128);
3181            for host in hosts {
3182                encoded.text("secretHost", &host);
3183            }
3184            let mut methods = binding.allowed_methods.clone();
3185            methods.sort();
3186            methods.dedup();
3187            encoded.number("secretMethodCount", methods.len() as u128);
3188            for method in methods {
3189                encoded.text("secretMethod", &method);
3190            }
3191            let mut paths = binding
3192                .allowed_paths
3193                .iter()
3194                .map(|rule| match rule {
3195                    dekopon_capability::HttpPathRule::Exact { path } => {
3196                        format!("exact:{path}")
3197                    }
3198                    dekopon_capability::HttpPathRule::SegmentPrefix { path } => {
3199                        format!("segment-prefix:{path}")
3200                    }
3201                })
3202                .collect::<Vec<_>>();
3203            paths.sort();
3204            paths.dedup();
3205            encoded.number("secretPathCount", paths.len() as u128);
3206            for path in paths {
3207                encoded.text("secretPath", &path);
3208            }
3209            encoded.boolean("secretAllowQuery", binding.allow_query);
3210            encoded.number("secretMaxInjections", u128::from(binding.max_injections));
3211        }
3212
3213        encode_host_limits(&mut encoded, &operational.host);
3214        self.registry
3215            .storage_host()
3216            .ok_or(BrokerError::MemoryUnavailable)?;
3217        encode_storage_limits(&mut encoded, &operational.storage);
3218        if let Some(memory) = operational.memory.as_ref().filter(|_| memory_route) {
3219            encode_memory_config(&mut encoded, memory);
3220        }
3221        Ok(encoded.finish())
3222    }
3223
3224    fn prepare_storage_grant(
3225        &self,
3226        context: &AuthenticatedContext,
3227        request: &InvocationRequest,
3228        set: &ConstraintSet,
3229    ) -> Result<Option<StorageGrantPreparation>, BrokerError> {
3230        let Some(storage) = &set.constraints.storage else {
3231            return Ok(None);
3232        };
3233        let scope = context.chat_scope().ok_or(BrokerError::MemoryUnavailable)?;
3234        let subject = context
3235            .attested_subject()
3236            .ok_or(BrokerError::MemoryUnavailable)?;
3237        let agent = match context.actor() {
3238            Actor::Agent { agent } => agent.clone(),
3239            Actor::Human { .. } | Actor::Service { .. } => {
3240                return Err(BrokerError::MemoryUnavailable);
3241            }
3242        };
3243        let memory_route = set.route.is_chat_memory();
3244        let (policy, authority, memory) = if memory_route {
3245            let memory = match self
3246                .chat_memory
3247                .as_ref()
3248                .map_or(ContinuityPolicy::Paranoid, |config| {
3249                    config.continuity_policy
3250                }) {
3251                ContinuityPolicy::Relaxed => MemoryContinuity::Relaxed,
3252                ContinuityPolicy::Paranoid => MemoryContinuity::Paranoid {
3253                    surface: self.memory_surface_v2(context)?,
3254                    legacy: self.legacy_continuity(context)?,
3255                    on_unproven: self
3256                        .chat_memory
3257                        .as_ref()
3258                        .and_then(|config| config.continuity_migration.as_ref())
3259                        .map(|migration| migration.on_unproven)
3260                        .unwrap_or_default(),
3261                },
3262            };
3263            (ContinuityPolicy::Paranoid, Vec::new(), Some(memory))
3264        } else {
3265            let policy = if storage.scope == StorageScope::PrivateConversation {
3266                ContinuityPolicy::Paranoid
3267            } else {
3268                ContinuityPolicy::Relaxed
3269            };
3270            let authority = self.authority_surface_v1(
3271                context,
3272                storage.interface,
3273                false,
3274                &self.current_operational()?,
3275            )?;
3276            (policy, authority, None)
3277        };
3278        let host = self
3279            .registry
3280            .storage_host()
3281            .ok_or(BrokerError::MemoryUnavailable)?;
3282        let grant_request = StorageGrantRequest::new(
3283            request.id.clone(),
3284            request.capability.clone(),
3285            set.provider.clone(),
3286            storage.interface,
3287            storage.access,
3288            storage.scope,
3289            agent,
3290            subject.clone(),
3291            scope.kind.to_string(),
3292            scope.transport.to_string(),
3293            scope.conversation.id.clone(),
3294            scope.conversation.key(),
3295            policy,
3296            authority,
3297        )
3298        .with_shared_namespace(storage.namespace.clone())
3299        .with_space_key(context.space_binding().map(|binding| binding.key));
3300        let grant_request = match memory {
3301            Some(memory) => grant_request.with_memory_continuity(memory),
3302            None => grant_request,
3303        };
3304        host.prepare_grant(grant_request)
3305            .map(Some)
3306            .map_err(|source| BrokerError::Storage { source })
3307    }
3308
3309    fn curate_memory_input(
3310        &self,
3311        route: CapabilityRoute,
3312        request: &mut InvocationRequest,
3313    ) -> Result<(), &'static str> {
3314        let config = self.chat_memory.as_ref().ok_or("memory-unavailable")?;
3315        request.input = match route {
3316            CapabilityRoute::ChatMemoryRecent => {
3317                let last = request
3318                    .input
3319                    .as_object()
3320                    .filter(|object| object.len() == 1)
3321                    .and_then(|object| object.get("last"))
3322                    .and_then(serde_json::Value::as_u64)
3323                    .filter(|last| *last > 0 && *last <= u64::from(config.max_recent_turns))
3324                    .ok_or("invalid-memory-input")?;
3325                serde_json::json!({
3326                    "operation": "recent", "last": last,
3327                    "maxLookbackTurns": config.max_lookback_turns,
3328                    "maxRecentTurns": config.max_recent_turns,
3329                    "maxResultBytes": config.max_result_bytes,
3330                })
3331            }
3332            CapabilityRoute::ChatMemorySearch => {
3333                let query = request
3334                    .input
3335                    .as_object()
3336                    .filter(|object| object.len() == 1)
3337                    .and_then(|object| object.get("query"))
3338                    .and_then(serde_json::Value::as_str)
3339                    .filter(|query| {
3340                        !query.is_empty() && query.len() as u64 <= config.max_query_bytes
3341                    })
3342                    .ok_or("invalid-memory-input")?;
3343                serde_json::json!({
3344                    "operation": "search", "query": query,
3345                    "maxLookbackTurns": config.max_lookback_turns,
3346                    "maxSearchResults": config.max_search_results,
3347                    "maxResultBytes": config.max_result_bytes,
3348                })
3349            }
3350            CapabilityRoute::Generic | CapabilityRoute::ChatMemoryRecord => {
3351                return Err("invalid-memory-input");
3352            }
3353        };
3354        Ok(())
3355    }
3356
3357    async fn invoke_inner(
3358        &self,
3359        context: &AuthenticatedContext,
3360        mut request: InvocationRequest,
3361        refusal: Option<Refusal>,
3362        assets: dekopon_broker_host::asset::AssetInputs,
3363        outputs: &mut dekopon_broker_host::asset::AssetOutputs,
3364    ) -> Result<InvocationResult, BrokerError> {
3365        let authorize = tracing::info_span!(
3366            "broker.authorize",
3367            invocation = %request.id,
3368            capability = %request.capability,
3369            subject = tracing::field::Empty,
3370            via = tracing::field::Empty,
3371            trigger = tracing::field::Empty,
3372            outcome = tracing::field::Empty,
3373            policy.errors_present = tracing::field::Empty,
3374            secret = tracing::field::Empty,
3375            secret.selection = tracing::field::Empty,
3376            input = tracing::field::Empty,
3377            input.bytes = tracing::field::Empty,
3378        );
3379        if let Some(subject) = context.attested_subject() {
3380            authorize.record("subject", tracing::field::display(subject));
3381        }
3382        if let Some(via) = context.via() {
3383            authorize.record("via", tracing::field::display(via));
3384        }
3385        if let Some(scope) = context.chat_scope() {
3386            authorize.record("trigger", scope.trigger.as_str());
3387        }
3388        let input = dekopon_core::bounded_display(&request.input);
3389        authorize.record("input", tracing::field::display(input.text()));
3390        authorize.record("input.bytes", input.bytes());
3391        // Instrumented rather than entered with a guard, since a guard held across the audit-append
3392        // await would stay entered on the worker thread while suspended, misattributing another
3393        // connection's spans to this request's authorization.
3394        let authorized = async {
3395            if let Some(refusal) = refusal {
3396                authorize.record("outcome", refusal.reason);
3397                return self
3398                    .deny(context, &request, refusal)
3399                    .await
3400                    .map(ControlFlow::Break);
3401            }
3402            // Before the decision: a denial still records the defaulted secret it refused.
3403            match self.secret_use_or_default(
3404                context.actor(),
3405                &request.capability,
3406                request.secret_use.take(),
3407            ) {
3408                Ok(secret_use) => request.secret_use = secret_use,
3409                Err(refusal) => {
3410                    authorize.record("outcome", refusal.reason);
3411                    return self
3412                        .deny(context, &request, refusal)
3413                        .await
3414                        .map(ControlFlow::Break);
3415                }
3416            }
3417            let mut decision = match self.authorize_invocation(context, &request.capability) {
3418                Ok(authorized) => authorized,
3419                Err(refusal) => {
3420                    // A policy error denies exactly like a non-match; this is recorded as a flag
3421                    // rather than the error text so denial explanations can't become a
3422                    // per-request channel leaking policy source or entity data.
3423                    if let Some(evaluation) = &refusal.evaluation {
3424                        authorize.record("policy.errors_present", evaluation.errors_present);
3425                        if evaluation.errors_present {
3426                            tracing::warn!(
3427                                event = "broker_policy_evaluation_error",
3428                                invocation = %request.id,
3429                                policy.target = "capability",
3430                                "broker.policy.evaluation.error"
3431                            );
3432                        }
3433                        if let Some(cause) = &evaluation.cause {
3434                            tracing::warn!(
3435                                target: "dekopon_broker::audit",
3436                                {
3437                                    audit.event = "policy.request.refused",
3438                                    capability.id = %request.capability,
3439                                    error.reason = %cause,
3440                                },
3441                                "policy.request.refused"
3442                            );
3443                        }
3444                    }
3445                    authorize.record("outcome", refusal.reason);
3446                    return self
3447                        .deny(context, &request, refusal)
3448                        .await
3449                        .map(ControlFlow::Break);
3450                }
3451            };
3452            let bound = self.bind_secret_use(
3453                context,
3454                &request.capability,
3455                &mut decision,
3456                request.secret_use.as_ref(),
3457            );
3458            authorize.record("policy.errors_present", decision.errors_present);
3459            if let Err(refusal) = bound {
3460                authorize.record("outcome", refusal.reason);
3461                if refusal
3462                    .evaluation
3463                    .as_ref()
3464                    .is_some_and(|evaluation| evaluation.errors_present)
3465                {
3466                    tracing::warn!(
3467                        event = "broker_policy_evaluation_error",
3468                        invocation = %request.id,
3469                        policy.target = "secret",
3470                        "broker.policy.evaluation.error"
3471                    );
3472                }
3473                return self
3474                    .deny(context, &request, refusal)
3475                    .await
3476                    .map(ControlFlow::Break);
3477            }
3478            authorize.record("outcome", "allowed");
3479            Ok(ControlFlow::Continue(decision))
3480        }
3481        .instrument(authorize.clone())
3482        .await?;
3483        let decision = match authorized {
3484            ControlFlow::Break(denied) => return Ok(denied),
3485            ControlFlow::Continue(allowed) => allowed,
3486        };
3487        let CapabilityDecision {
3488            set,
3489            policy_ids,
3490            slots,
3491            space,
3492            ..
3493        } = decision;
3494        let execute = tracing::info_span!(
3495            "broker.execute",
3496            provider = %set.provider,
3497            storage = tracing::field::Empty,
3498            storage.namespace = tracing::field::Empty,
3499            storage.reset = tracing::field::Empty,
3500            outcome = tracing::field::Empty,
3501            otel.status_code = tracing::field::Empty,
3502            otel.status_description = tracing::field::Empty,
3503            error = tracing::field::Empty,
3504            error.code = tracing::field::Empty,
3505            error.message = tracing::field::Empty,
3506        );
3507        if set.constraints.storage.is_some() {
3508            execute.record("storage", true);
3509        }
3510        self.execute(
3511            context, request, set, policy_ids, slots, space, assets, outputs,
3512        )
3513        .instrument(execute)
3514        .await
3515    }
3516
3517    async fn deny(
3518        &self,
3519        context: &AuthenticatedContext,
3520        request: &InvocationRequest,
3521        refusal: Refusal,
3522    ) -> Result<InvocationResult, BrokerError> {
3523        let Refusal {
3524            reason,
3525            wire,
3526            policy_ids,
3527            evaluation,
3528            ..
3529        } = refusal;
3530        let mut authority = decision_authority(
3531            context,
3532            self.identities.principal_kind(context.principal()),
3533            evaluation
3534                .as_ref()
3535                .and_then(|evaluation| evaluation.space.clone()),
3536        );
3537        authority.github_denial = evaluation
3538            .as_ref()
3539            .and_then(|evaluation| evaluation.github_denial.clone());
3540        let decision_id = format!("deny-{}", request.id);
3541        let decision = self.decision_reference(&decision_id);
3542        let trace = request.trace_parent.trace();
3543        let material = DecisionMaterial {
3544            invocation: &request.id,
3545            trace,
3546            principal: context.principal(),
3547            actor: context.actor(),
3548            via: context.via(),
3549            attested_subject: context.attested_subject(),
3550            capability: &request.capability,
3551            secret_use: request.secret_use.as_ref(),
3552            provider: None,
3553            authorized_by: &self.broker_principal,
3554            policy_ids: &policy_ids,
3555            policy_digest: &self.policy_digest,
3556            constraints: None,
3557            allowed: false,
3558            reason: Some(reason),
3559            space: authority.space.as_ref(),
3560        };
3561        let storage_host = self.registry.storage_host();
3562        let storage_backed =
3563            storage_host.is_some() && self.capability_uses_storage(&request.capability);
3564        let digest = if storage_backed {
3565            let bytes = serde_json::to_vec(&material)
3566                .map_err(|source| BrokerError::DecisionEvidence { source })?;
3567            storage_host
3568                .as_ref()
3569                .expect("storage_backed proves a configured host")
3570                .evidence_commitment("policy-decision", &bytes)
3571        } else {
3572            decision_evidence_digest("policy-decision", &material)?
3573        };
3574        self.record_audit(AuditEvent::Decision {
3575            authority,
3576            invocation: request.id.clone(),
3577            trace,
3578            principal: Some(context.principal().clone()),
3579            actor: Some(context.actor().clone()),
3580            via: context.via().cloned(),
3581            attested_subject: context.attested_subject().cloned(),
3582            capability: request.capability.clone(),
3583            secret: request
3584                .secret_use
3585                .as_ref()
3586                .map(|secret| secret.secret().clone()),
3587            secret_sink: request.secret_use.as_ref().map(SecretUseProposal::sink),
3588            provider: None,
3589            authorized_by: Some(self.broker_principal.clone()),
3590            decision_id: decision_id.clone(),
3591            policy_ids,
3592            policy_error_ids: Vec::new(),
3593            policy_errors_present: evaluation
3594                .as_ref()
3595                .and_then(|evaluation| context.space.as_ref().map(|_| evaluation.errors_present)),
3596            decision_point: "invocation".to_owned(),
3597            policy_digest: Some(self.policy_digest.clone()),
3598            allowed: false,
3599            reason: Some(reason.to_owned()),
3600            decision_digest: digest.clone(),
3601            storage_scope_commitment: None,
3602            storage: None,
3603        })
3604        .await
3605        .map_err(|source| {
3606            report_audit_failure("decision", &request.id, &source);
3607            BrokerError::DecisionAudit { source }
3608        })?;
3609        Ok(InvocationResult {
3610            invocation: request.id.clone(),
3611            decision,
3612            outcome: InvocationOutcome::Denied,
3613            exit_status: None,
3614            error: Some(wire.to_owned()),
3615            detail: None,
3616            evidence: vec![Evidence {
3617                kind: "policy-decision".to_owned(),
3618                digest,
3619                media_type: POLICY_EVIDENCE_MEDIA_TYPE.to_owned(),
3620                uri: None,
3621            }],
3622        })
3623    }
3624
3625    #[allow(
3626        clippy::too_many_arguments,
3627        reason = "the terminal record takes the exact authorization identity and policy material \
3628                  already in scope; bundling it would create a second partial invocation type"
3629    )]
3630    async fn fail_authorized_before_provider(
3631        &self,
3632        context: &AuthenticatedContext,
3633        invocation: &InvocationId,
3634        trace: TraceId,
3635        capability: &CapabilityId,
3636        decision_id: &str,
3637        decision: DecisionReference,
3638        set: &ConstraintSet,
3639        policy_ids: &[String],
3640        policy_evidence: Evidence,
3641        reason: &'static str,
3642    ) -> Result<InvocationResult, BrokerError> {
3643        let artifact = self
3644            .registry
3645            .loaded_provider_metadata()
3646            .find(|metadata| metadata.manifest.id == set.provider)
3647            .map(|metadata| metadata.artifact_sha256);
3648        let event = execution_event(
3649            context,
3650            invocation,
3651            trace,
3652            capability,
3653            decision_id,
3654            policy_ids,
3655            &self.policy_digest,
3656            artifact.as_deref(),
3657            &self.broker_principal,
3658            set,
3659            InvocationOutcome::Failed,
3660            None,
3661            0,
3662            Some(reason.to_owned()),
3663            None,
3664            Vec::new(),
3665            None,
3666            None,
3667        );
3668        let execution = tracing::Span::current();
3669        execution.record("outcome", "failed");
3670        execution.record("otel.status_description", reason);
3671        execution.record("error", reason);
3672        self.record_audit(event).await.map_err(|source| {
3673            execution.record("outcome", "authorized-failure-unaudited");
3674            execution.record("error", source.category());
3675            report_audit_failure("authorized-failure", invocation, &source);
3676            BrokerError::AuthorizedFailureAudit { source }
3677        })?;
3678        Ok(InvocationResult {
3679            invocation: invocation.clone(),
3680            decision,
3681            outcome: InvocationOutcome::Failed,
3682            exit_status: None,
3683            error: Some(reason.to_owned()),
3684            detail: None,
3685            evidence: vec![policy_evidence],
3686        })
3687    }
3688
3689    #[expect(
3690        clippy::too_many_arguments,
3691        clippy::too_many_lines,
3692        reason = "reshaped by the unit that next rewrites this"
3693    )]
3694    async fn execute(
3695        &self,
3696        context: &AuthenticatedContext,
3697        mut request: InvocationRequest,
3698        set: ConstraintSet,
3699        policy_ids: Vec<String>,
3700        slots: ChatSlotValues,
3701        space: Option<SpaceDecision>,
3702        assets: dekopon_broker_host::asset::AssetInputs,
3703        outputs: &mut dekopon_broker_host::asset::AssetOutputs,
3704    ) -> Result<InvocationResult, BrokerError> {
3705        // Deliberately non-mutating here: the authorization decision must be recorded before
3706        // materialize can create a namespace, rotate a generation pointer, or update lifecycle
3707        // state.
3708        let authority = decision_authority(
3709            context,
3710            self.identities.principal_kind(context.principal()),
3711            space,
3712        );
3713        let mut storage_preparation = self.prepare_storage_grant(context, &request, &set)?;
3714        if let Some(preparation) = &storage_preparation {
3715            tracing::Span::current().record("storage.namespace", preparation.namespace());
3716        }
3717        let storage_scope_commitment = storage_preparation
3718            .as_ref()
3719            .map(StorageGrantPreparation::scope_commitment);
3720        if set.route == CapabilityRoute::ChatMemoryRecord {
3721            let config = self
3722                .chat_memory
3723                .as_ref()
3724                .ok_or(BrokerError::MemoryUnavailable)?;
3725            let object = request
3726                .input
3727                .as_object()
3728                .filter(|object| object.len() == 3)
3729                .ok_or(BrokerError::InvalidMemoryInput)?;
3730            #[allow(
3731                clippy::map_err_ignore,
3732                reason = "not wire input: every externally reachable entry point refuses \
3733                          the record route, so the only proposal reaching here is the one \
3734                          `record_delivered_turn` builds from a typed DeliveryIdentity \
3735                          — this is that value's own round trip, and serde has no malformed \
3736                          input to name"
3737            )]
3738            let delivery: DeliveryIdentity = object
3739                .get("delivery")
3740                .cloned()
3741                .ok_or(BrokerError::InvalidMemoryInput)
3742                .and_then(|value| {
3743                    serde_json::from_value(value).map_err(|_| BrokerError::InvalidMemoryInput)
3744                })?;
3745            #[allow(
3746                clippy::map_err_ignore,
3747                reason = "`DeliveryIdentity` is a derived-Serialize enum of strings and integers, \
3748                          so serde_json has no failure to describe"
3749            )]
3750            let delivery =
3751                serde_json::to_vec(&delivery).map_err(|_| BrokerError::InvalidMemoryInput)?;
3752            let user = object
3753                .get("user")
3754                .and_then(serde_json::Value::as_str)
3755                .ok_or(BrokerError::InvalidMemoryInput)?;
3756            let assistant = object
3757                .get("assistant")
3758                .and_then(serde_json::Value::as_str)
3759                .ok_or(BrokerError::InvalidMemoryInput)?;
3760            let preparation = storage_preparation
3761                .as_ref()
3762                .ok_or(BrokerError::MemoryUnavailable)?;
3763            request.input = serde_json::json!({
3764                "operation": "record",
3765                "id": preparation.record_id(&delivery),
3766                "commitment": preparation.content_commitment(user, assistant),
3767                "user": user,
3768                "assistant": assistant,
3769                "maxTurnBytes": config.max_turn_bytes,
3770                "maxLookbackTurns": config.max_lookback_turns,
3771                "compactionTargetBytes": config.compaction_target_bytes,
3772                "compactionThresholdBytes": config.compaction_threshold_bytes,
3773            });
3774        }
3775        let decision_id = format!("allow-{}", request.id);
3776        let decision = self.decision_reference(&decision_id);
3777        let invocation_id = request.id.clone();
3778        let trace = request.trace_parent.trace();
3779        let capability = request.capability.clone();
3780        let secret_use = request.secret_use.take();
3781        let proposal = ProposedInvocation::new(
3782            request.id,
3783            request.capability,
3784            context.actor().clone(),
3785            trace,
3786            request.input,
3787        )
3788        .with_secret_use(secret_use);
3789        let request_authorizer = set.constraints.http.as_ref().map(|_| {
3790            let policy = Arc::clone(&self.policy);
3791            let audit = Arc::clone(&self.audit);
3792            let principal = context.principal().clone();
3793            let actor = context.actor().clone();
3794            let via = context.via().cloned();
3795            let subject = context.attested_subject().cloned();
3796            let provider = set.provider.clone();
3797            let broker_principal = self.broker_principal.clone();
3798            let policy_digest = self.policy_digest.clone();
3799            let effect = set.effect;
3800            let risk = set.risk;
3801            let invocation = invocation_id.clone();
3802            let capability = capability.clone();
3803            let authority = authority.clone();
3804            let space = context.space.clone();
3805            let github = context.chat_scope().and_then(|scope| scope.github.clone());
3806            let context = policy_context(context);
3807            let sequence = std::sync::atomic::AtomicUsize::new(0);
3808            Arc::new(move |facts: dekopon_broker_host::HttpRequestFacts| {
3809                let request = PolicyRequest {
3810                    principal: principal.clone(),
3811                    target: PolicyTarget::Capability {
3812                        capability: capability.clone(),
3813                        provider: provider.clone(),
3814                        effect,
3815                        risk,
3816                    },
3817                    context: context.clone(),
3818                };
3819                let facts = dekopon_policy::HttpRequestFacts {
3820                    method: facts.method,
3821                    host: facts.host,
3822                    path: facts.path,
3823                    query: facts.query,
3824                    headers: facts.headers,
3825                    body: facts.body.map_or(
3826                        dekopon_policy::RequestBody::Streamed,
3827                        dekopon_policy::RequestBody::Buffered,
3828                    ),
3829                    content_type: facts.content_type,
3830                };
3831                // Cedar measures its recursion reserve against stacker's thread bounds, which a
3832                // Wasmtime fiber stack falls outside, so it evaluates on a segment stacker tracks.
3833                let result = stacker::grow(POLICY_STACK_BYTES, || {
3834                    Self::evaluate(
3835                        &policy,
3836                        request,
3837                        Some(facts),
3838                        space.as_ref(),
3839                        github.as_ref(),
3840                    )
3841                });
3842                let mut authority = authority.clone();
3843                authority.space = result.space.clone();
3844                authority.github_denial = result.github_denial.clone();
3845                let material = DecisionMaterial {
3846                    invocation: &invocation,
3847                    trace,
3848                    principal: &principal,
3849                    actor: &actor,
3850                    via: via.as_ref(),
3851                    attested_subject: subject.as_ref(),
3852                    capability: &capability,
3853                    secret_use: None,
3854                    provider: Some(&provider),
3855                    authorized_by: &broker_principal,
3856                    policy_ids: &result.policy.determining_policy_ids,
3857                    policy_digest: &policy_digest,
3858                    constraints: None,
3859                    allowed: result.allowed,
3860                    reason: (!result.allowed).then(|| denial_reason(&result, "policy-denied")),
3861                    space: authority.space.as_ref(),
3862                };
3863                let digest = decision_evidence_digest("policy-decision", &material);
3864                let ordinal = sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3865                let decision_id = format!("http-{invocation}-{ordinal}");
3866                if result.errors_present
3867                    && let Some(opaque) = result.opaque_body
3868                {
3869                    tracing::warn!(
3870                        target: "dekopon_broker::audit",
3871                        {
3872                            audit.event = "policy.request.body_opaque",
3873                            invocation.id = %invocation,
3874                            capability.id = %capability,
3875                            decision.id = decision_id.as_str(),
3876                            request.body.reason = opaque.label(),
3877                        },
3878                        "policy.request.body_opaque"
3879                    );
3880                }
3881                let reason =
3882                    (!result.allowed).then(|| denial_reason(&result, "policy-denied").to_owned());
3883                let decision_digest = match digest {
3884                    Ok(digest) => digest,
3885                    Err(source) => {
3886                        tracing::error!(
3887                            event = "broker_decision_evidence_failed",
3888                            invocation = %invocation,
3889                            point = "http.request",
3890                            cause_type = std::any::type_name_of_val(&source),
3891                            "broker.decision.evidence.failed"
3892                        );
3893                        return Box::pin(async { false })
3894                            as std::pin::Pin<Box<dyn Future<Output = bool> + Send>>;
3895                    }
3896                };
3897                let event = AuditEvent::Decision {
3898                    authority,
3899                    invocation: invocation.clone(),
3900                    trace,
3901                    principal: Some(principal.clone()),
3902                    actor: Some(actor.clone()),
3903                    via: via.clone(),
3904                    attested_subject: subject.clone(),
3905                    capability: capability.clone(),
3906                    secret: None,
3907                    secret_sink: None,
3908                    provider: Some(provider.clone()),
3909                    authorized_by: Some(broker_principal.clone()),
3910                    decision_id,
3911                    policy_ids: result.policy.determining_policy_ids,
3912                    policy_error_ids: result.policy.erroring_policy_ids,
3913                    policy_errors_present: Some(result.policy.errors_present),
3914                    decision_point: "http.request".to_owned(),
3915                    policy_digest: Some(policy_digest.clone()),
3916                    allowed: result.policy.allowed,
3917                    reason,
3918                    decision_digest,
3919                    storage_scope_commitment: None,
3920                    storage: None,
3921                };
3922                let audit = Arc::clone(&audit);
3923                let invocation = invocation.clone();
3924                Box::pin(async move {
3925                    emit_audit_event(&event);
3926                    match audit.append(event).await {
3927                        Ok(()) => result.policy.allowed,
3928                        Err(source) => {
3929                            report_audit_failure("decision", &invocation, &source);
3930                            false
3931                        }
3932                    }
3933                }) as std::pin::Pin<Box<dyn Future<Output = bool> + Send>>
3934            }) as dekopon_broker_host::RequestAuthorizer
3935        });
3936        let authorized = self
3937            .gate
3938            .authorize(
3939                proposal,
3940                set.provider.clone(),
3941                decision_id.clone(),
3942                self.broker_principal.clone(),
3943                self.policy_hex_digest().to_owned(),
3944                set.constraints.clone(),
3945            )
3946            .map_err(|source| BrokerError::Authorization { source })?;
3947        let decision_digest = if authority.space.is_some() {
3948            let material = DecisionMaterial {
3949                invocation: &invocation_id,
3950                trace,
3951                principal: context.principal(),
3952                actor: context.actor(),
3953                via: context.via(),
3954                attested_subject: context.attested_subject(),
3955                capability: &capability,
3956                secret_use: authorized.proposal().secret_use.as_ref(),
3957                provider: Some(&set.provider),
3958                authorized_by: &self.broker_principal,
3959                policy_ids: &policy_ids,
3960                policy_digest: &self.policy_digest,
3961                constraints: Some(&set.constraints),
3962                allowed: true,
3963                reason: None,
3964                space: authority.space.as_ref(),
3965            };
3966            let material = (&authorized, material);
3967            if let Some(preparation) = storage_preparation.as_ref() {
3968                let bytes = serde_json::to_vec(&material)
3969                    .map_err(|source| BrokerError::DecisionEvidence { source })?;
3970                preparation.evidence_commitment("policy-decision", &bytes)
3971            } else {
3972                decision_evidence_digest("policy-decision", &material)?
3973            }
3974        } else if let Some(preparation) = storage_preparation.as_ref() {
3975            let bytes = serde_json::to_vec(&authorized)
3976                .map_err(|source| BrokerError::DecisionEvidence { source })?;
3977            preparation.evidence_commitment("authorized-invocation", &bytes)
3978        } else {
3979            decision_evidence_digest("authorized-invocation", &authorized)?
3980        };
3981        let policy_evidence = Evidence {
3982            kind: "policy-decision".to_owned(),
3983            digest: decision_digest.clone(),
3984            media_type: POLICY_EVIDENCE_MEDIA_TYPE.to_owned(),
3985            uri: None,
3986        };
3987
3988        self.record_audit(AuditEvent::Decision {
3989            authority,
3990            invocation: invocation_id.clone(),
3991            trace,
3992            principal: Some(context.principal().clone()),
3993            actor: Some(context.actor().clone()),
3994            via: context.via().cloned(),
3995            attested_subject: context.attested_subject().cloned(),
3996            capability: capability.clone(),
3997            secret: authorized
3998                .proposal()
3999                .secret_use
4000                .as_ref()
4001                .map(|secret| secret.secret().clone()),
4002            secret_sink: authorized
4003                .proposal()
4004                .secret_use
4005                .as_ref()
4006                .map(SecretUseProposal::sink),
4007            provider: Some(set.provider.clone()),
4008            authorized_by: Some(self.broker_principal.clone()),
4009            decision_id: decision_id.clone(),
4010            policy_ids: policy_ids.clone(),
4011            policy_error_ids: Vec::new(),
4012            policy_errors_present: None,
4013            decision_point: "invocation".to_owned(),
4014            policy_digest: Some(self.policy_digest.clone()),
4015            allowed: true,
4016            reason: None,
4017            decision_digest,
4018            storage_scope_commitment: storage_scope_commitment.clone(),
4019            storage: None,
4020        })
4021        .await
4022        .map_err(|source| {
4023            tracing::Span::current().record("outcome", "decision-unaudited");
4024            tracing::Span::current().record("error", source.category());
4025            report_audit_failure("decision", &invocation_id, &source);
4026            BrokerError::DecisionAudit { source }
4027        })?;
4028
4029        let storage_grant = match storage_preparation.take() {
4030            None => None,
4031            Some(preparation) => {
4032                let span = tracing::Span::current();
4033                let materialized = tokio::task::spawn_blocking(move || {
4034                    span.in_scope(|| preparation.materialize())
4035                })
4036                .await
4037                .map_err(|source| BrokerError::StorageTask { source })?;
4038                Some(materialized.map_err(|source| {
4039                    if source.namespace_reset() {
4040                        tracing::Span::current().record("storage.reset", true);
4041                    }
4042                    BrokerError::Storage { source }
4043                })?)
4044            }
4045        };
4046
4047        let proposed_secret = authorized.proposal().secret_use.clone();
4048        let credential = if let Some(proposal) = proposed_secret {
4049            let material = match self.secrets.resolver.resolve(proposal.secret()).await {
4050                Ok(material) => material,
4051                Err(source) => {
4052                    tracing::warn!(
4053                        event = "broker_secret_resolution_failed",
4054                        invocation = %invocation_id,
4055                        category = source.category,
4056                        "broker.secret.resolution.failed"
4057                    );
4058                    return self
4059                        .fail_authorized_before_provider(
4060                            context,
4061                            &invocation_id,
4062                            trace,
4063                            &capability,
4064                            &decision_id,
4065                            decision,
4066                            &set,
4067                            &policy_ids,
4068                            policy_evidence,
4069                            "secret-resolution",
4070                        )
4071                        .await;
4072                }
4073            };
4074            let Some(grant) = authorized.constraints().secret_use.as_ref() else {
4075                return self
4076                    .fail_authorized_before_provider(
4077                        context,
4078                        &invocation_id,
4079                        trace,
4080                        &capability,
4081                        &decision_id,
4082                        decision,
4083                        &set,
4084                        &policy_ids,
4085                        policy_evidence,
4086                        "secret-authorization",
4087                    )
4088                    .await;
4089            };
4090            let SecretMaterial {
4091                bytes,
4092                chatgpt_account,
4093            } = material;
4094            let built = match proposal.sink() {
4095                SecretSinkKind::HttpBearer => BoundCredential::secret_bearer(bytes, grant),
4096                SecretSinkKind::HttpBasic => BoundCredential::secret_basic(bytes, grant),
4097                SecretSinkKind::HttpBot => BoundCredential::secret_bot(bytes, grant),
4098            }
4099            .and_then(|credential| match &chatgpt_account {
4100                Some(account) => credential.with_chatgpt_account(account.expose()),
4101                None => Ok(credential),
4102            });
4103            match built {
4104                Ok(credential) => Some(credential),
4105                Err(source) => {
4106                    tracing::warn!(
4107                        event = "broker_secret_credential_failed",
4108                        invocation = %invocation_id,
4109                        category = "invalid-material",
4110                        cause_type = std::any::type_name_of_val(&source),
4111                        "broker.secret.credential.failed"
4112                    );
4113                    return self
4114                        .fail_authorized_before_provider(
4115                            context,
4116                            &invocation_id,
4117                            trace,
4118                            &capability,
4119                            &decision_id,
4120                            decision,
4121                            &set,
4122                            &policy_ids,
4123                            policy_evidence,
4124                            "secret-credential",
4125                        )
4126                        .await;
4127                }
4128            }
4129        } else {
4130            None
4131        };
4132        let provider_artifact_sha256 = self
4133            .registry
4134            .loaded_provider_metadata()
4135            .find(|metadata| metadata.manifest.id == set.provider)
4136            .map(|metadata| metadata.artifact_sha256);
4137        let started = Instant::now();
4138        let execution = self
4139            .registry
4140            .invoke_with_storage(
4141                authorized,
4142                credential,
4143                storage_grant,
4144                dekopon_broker_host::HttpInvocation {
4145                    slots,
4146                    authorizer: request_authorizer,
4147                },
4148                assets,
4149            )
4150            .await;
4151        let duration_ms = duration_millis(started.elapsed());
4152        let (result, audit_event) = match execution {
4153            Ok(output) => {
4154                *outputs = output.assets;
4155                let mut evidence = vec![policy_evidence];
4156                if let Some(storage) = &output.storage {
4157                    evidence.push(Evidence {
4158                        kind: "storage".to_owned(),
4159                        digest: storage.evidence_commitment.clone(),
4160                        media_type: STORAGE_EVIDENCE_MEDIA_TYPE.to_owned(),
4161                        uri: None,
4162                    });
4163                }
4164                if !output.http_calls.is_empty() {
4165                    evidence.push(Evidence {
4166                        kind: "http-calls".to_owned(),
4167                        digest: outcome_evidence_digest(
4168                            &invocation_id,
4169                            "http-calls",
4170                            &output.http_calls,
4171                        )?,
4172                        media_type: HTTP_EVIDENCE_MEDIA_TYPE.to_owned(),
4173                        uri: None,
4174                    });
4175                }
4176                let event = execution_event(
4177                    context,
4178                    &invocation_id,
4179                    trace,
4180                    &capability,
4181                    &decision_id,
4182                    &policy_ids,
4183                    &self.policy_digest,
4184                    provider_artifact_sha256.as_deref(),
4185                    &self.broker_principal,
4186                    &set,
4187                    InvocationOutcome::Succeeded,
4188                    None,
4189                    duration_ms,
4190                    None,
4191                    None,
4192                    output.http_calls,
4193                    storage_scope_commitment.clone(),
4194                    output.storage,
4195                );
4196                (
4197                    InvocationResult {
4198                        invocation: invocation_id.clone(),
4199                        decision: decision.clone(),
4200                        outcome: InvocationOutcome::Succeeded,
4201                        exit_status: None,
4202                        error: None,
4203                        detail: (!output.stderr.is_empty())
4204                            .then(|| ProviderFailureDetail::new("provider-stderr", &output.stderr)),
4205                        evidence,
4206                    },
4207                    event,
4208                )
4209            }
4210            Err(failure) => {
4211                let error = public_host_error(&failure.error).to_owned();
4212                let detail = provider_failure_detail(&failure.error);
4213                let mut evidence = vec![policy_evidence];
4214                if let Some(storage) = &failure.storage {
4215                    evidence.push(Evidence {
4216                        kind: "storage".to_owned(),
4217                        digest: storage.evidence_commitment.clone(),
4218                        media_type: STORAGE_EVIDENCE_MEDIA_TYPE.to_owned(),
4219                        uri: None,
4220                    });
4221                }
4222                if !failure.http_calls.is_empty() {
4223                    evidence.push(Evidence {
4224                        kind: "http-calls".to_owned(),
4225                        digest: outcome_evidence_digest(
4226                            &invocation_id,
4227                            "http-calls",
4228                            &failure.http_calls,
4229                        )?,
4230                        media_type: HTTP_EVIDENCE_MEDIA_TYPE.to_owned(),
4231                        uri: None,
4232                    });
4233                }
4234                let event = execution_event(
4235                    context,
4236                    &invocation_id,
4237                    trace,
4238                    &capability,
4239                    &decision_id,
4240                    &policy_ids,
4241                    &self.policy_digest,
4242                    provider_artifact_sha256.as_deref(),
4243                    &self.broker_principal,
4244                    &set,
4245                    InvocationOutcome::Failed,
4246                    Some(&failure.error),
4247                    duration_ms,
4248                    Some(error.clone()),
4249                    detail.clone(),
4250                    failure.http_calls,
4251                    storage_scope_commitment.clone(),
4252                    failure.storage,
4253                );
4254                (
4255                    InvocationResult {
4256                        invocation: invocation_id.clone(),
4257                        decision,
4258                        outcome: InvocationOutcome::Failed,
4259                        exit_status: provider_exit_status(&failure.error),
4260                        error: Some(error),
4261                        detail,
4262                        evidence,
4263                    },
4264                    event,
4265                )
4266            }
4267        };
4268
4269        let execution = tracing::Span::current();
4270        match result.outcome {
4271            InvocationOutcome::Succeeded => {
4272                execution.record("outcome", "succeeded");
4273            }
4274            InvocationOutcome::Denied | InvocationOutcome::Failed => {
4275                execution.record("outcome", "failed");
4276                execution.record("otel.status_code", "error");
4277            }
4278        }
4279        if let Some(error) = result.error.as_deref() {
4280            execution.record("otel.status_description", error);
4281            execution.record("error", error);
4282        }
4283        if let Some(detail) = result.detail.as_ref() {
4284            execution.record("error.code", detail.code.as_str());
4285            execution.record("error.message", detail.message.as_str());
4286        }
4287
4288        self.record_audit(audit_event).await.map_err(|source| {
4289            execution.record("outcome", "outcome-unaudited");
4290            execution.record("error", source.category());
4291            report_audit_failure("outcome", &invocation_id, &source);
4292            BrokerError::OutcomeAudit {
4293                invocation: invocation_id.clone(),
4294                source,
4295            }
4296        })?;
4297        Ok(result)
4298    }
4299
4300    async fn record_audit(&self, event: AuditEvent) -> Result<(), AuditError> {
4301        emit_audit_event(&event);
4302        self.audit.append(event).await
4303    }
4304
4305    fn policy_hex_digest(&self) -> &str {
4306        self.policy_digest
4307            .strip_prefix("sha256:")
4308            .unwrap_or(&self.policy_digest)
4309    }
4310
4311    fn decision_reference(&self, decision_id: &str) -> DecisionReference {
4312        DecisionReference {
4313            decision_id: decision_id.to_owned(),
4314            authorized_by: self.broker_principal.clone(),
4315            policy_digest: self.policy_hex_digest().to_owned(),
4316        }
4317    }
4318}
4319
4320struct AuthorityEncoder {
4321    bytes: Vec<u8>,
4322}
4323
4324impl AuthorityEncoder {
4325    fn new() -> Self {
4326        Self { bytes: Vec::new() }
4327    }
4328
4329    fn field(&mut self, label: &str, value: &[u8]) {
4330        self.bytes
4331            .extend_from_slice(&(label.len() as u64).to_be_bytes());
4332        self.bytes.extend_from_slice(label.as_bytes());
4333        self.bytes
4334            .extend_from_slice(&(value.len() as u64).to_be_bytes());
4335        self.bytes.extend_from_slice(value);
4336    }
4337
4338    fn text(&mut self, label: &str, value: &str) {
4339        self.field(label, value.as_bytes());
4340    }
4341
4342    fn number(&mut self, label: &str, value: u128) {
4343        self.field(label, &value.to_be_bytes());
4344    }
4345
4346    fn byte(&mut self, label: &str, value: u8) {
4347        self.field(label, &[value]);
4348    }
4349
4350    fn boolean(&mut self, label: &str, value: bool) {
4351        self.byte(label, u8::from(value));
4352    }
4353
4354    fn optional_text(&mut self, label: &str, value: Option<&str>) {
4355        match value {
4356            Some(value) => {
4357                self.byte(&format!("{label}.present"), 1);
4358                self.text(label, value);
4359            }
4360            None => self.byte(&format!("{label}.present"), 0),
4361        }
4362    }
4363
4364    fn finish(self) -> Vec<u8> {
4365        self.bytes
4366    }
4367}
4368
4369fn effect_tag(value: EffectKind) -> u8 {
4370    match value {
4371        EffectKind::ReadOnly => 0,
4372        EffectKind::LocalWrite => 1,
4373        EffectKind::ExternalWrite => 2,
4374    }
4375}
4376
4377fn risk_tag(value: RiskLevel) -> u8 {
4378    match value {
4379        RiskLevel::Low => 0,
4380        RiskLevel::Medium => 1,
4381        RiskLevel::High => 2,
4382        RiskLevel::Critical => 3,
4383    }
4384}
4385
4386fn encode_capability_authority(
4387    encoded: &mut AuthorityEncoder,
4388    capability: &CapabilityId,
4389    set: &ConstraintSet,
4390    default_secret: Option<&SecretUseProposal>,
4391    provider_artifact_sha256: &str,
4392) {
4393    encoded.text("capability", capability.as_str());
4394    encoded.text("provider", set.provider.as_str());
4395    encoded.byte("effect", effect_tag(set.effect));
4396    encoded.byte("risk", risk_tag(set.risk));
4397    if let Some(default) = default_secret {
4398        encoded.text("defaultSecretDrn", default.secret().as_str());
4399        encoded.text("defaultSecretSink", &default.sink().to_string());
4400        encoded.optional_text("defaultSecretBasicUsername", default.username());
4401    }
4402    encode_execution_constraints(encoded, &set.constraints);
4403    encoded.text("providerArtifactSha256", provider_artifact_sha256);
4404}
4405
4406fn encode_execution_constraints(
4407    encoded: &mut AuthorityEncoder,
4408    constraints: &ExecutionConstraints,
4409) {
4410    encoded.number("execution.timeoutMs", u128::from(constraints.timeout_ms));
4411    if let Some(http) = &constraints.http {
4412        encoded.byte("execution.http.present", 1);
4413        let hosts = http.allowed_hosts.iter().collect::<BTreeSet<_>>();
4414        encoded.number("execution.http.allowedHostCount", hosts.len() as u128);
4415        for host in hosts {
4416            encoded.text("execution.http.allowedHost", host);
4417        }
4418        let methods = http.allowed_methods.iter().collect::<BTreeSet<_>>();
4419        encoded.number("execution.http.allowedMethodCount", methods.len() as u128);
4420        for method in methods {
4421            encoded.text("execution.http.allowedMethod", method);
4422        }
4423        encoded.number("execution.http.maxRequests", u128::from(http.max_requests));
4424        encoded.number(
4425            "execution.http.maxRequestBytes",
4426            u128::from(http.max_request_bytes),
4427        );
4428        encoded.number(
4429            "execution.http.maxResponseBytes",
4430            u128::from(http.max_response_bytes),
4431        );
4432        encoded.boolean(
4433            "execution.http.allowPlaintextLoopback",
4434            http.allow_plaintext_loopback,
4435        );
4436        if http.propagate_trace {
4437            encoded.boolean("execution.http.propagateTrace", true);
4438        }
4439        if http.signed_download == Some(dekopon_capability::SignedDownload::GithubActionsLogsV1) {
4440            encoded.text("execution.http.signedDownload", "github-actions-logs-v1");
4441        }
4442        encode_request_templates(encoded, &http.request_templates);
4443    } else {
4444        encoded.byte("execution.http.present", 0);
4445    }
4446    encode_storage_constraints(encoded, constraints.storage.as_ref());
4447    encode_asset_constraints(encoded, constraints.asset.as_ref());
4448}
4449
4450fn encode_request_templates(
4451    encoded: &mut AuthorityEncoder,
4452    templates: &[dekopon_capability::RequestTemplate],
4453) {
4454    if !templates.is_empty() {
4455        let templates = templates.iter().collect::<BTreeSet<_>>();
4456        encoded.number(
4457            "execution.http.requestTemplateCount",
4458            templates.len() as u128,
4459        );
4460        for template in templates {
4461            encoded.text("execution.http.requestTemplate.method", &template.method);
4462            encoded.text(
4463                "execution.http.requestTemplate.path",
4464                &template.path.to_string(),
4465            );
4466            encoded.number(
4467                "execution.http.requestTemplate.pinnedCount",
4468                template.query.pinned.len() as u128,
4469            );
4470            for (key, slot) in &template.query.pinned {
4471                encoded.text("execution.http.requestTemplate.pinnedKey", key);
4472                encoded.text("execution.http.requestTemplate.pinnedSlot", slot.as_str());
4473            }
4474            encoded.number(
4475                "execution.http.requestTemplate.allowedCount",
4476                template.query.allowed.len() as u128,
4477            );
4478            for key in &template.query.allowed {
4479                encoded.text("execution.http.requestTemplate.allowedKey", key);
4480            }
4481        }
4482    }
4483}
4484
4485fn encode_storage_constraints(
4486    encoded: &mut AuthorityEncoder,
4487    storage: Option<&StorageConstraints>,
4488) {
4489    if let Some(storage) = storage {
4490        encoded.byte("execution.storage.present", 1);
4491        encoded.byte(
4492            "execution.storage.interface",
4493            match storage.interface {
4494                StorageInterface::Jsonl => 0,
4495                StorageInterface::DurableFiles => 1,
4496            },
4497        );
4498        encoded.byte(
4499            "execution.storage.access",
4500            match storage.access {
4501                StorageAccess::ReadOnly => 0,
4502                StorageAccess::ReadWrite => 1,
4503            },
4504        );
4505        encoded.byte(
4506            "execution.storage.namespace",
4507            match storage.scope {
4508                StorageScope::PrivateConversation => 0,
4509                StorageScope::SharedConversation => 1,
4510                StorageScope::Agent => 2,
4511                StorageScope::Space => 3,
4512            },
4513        );
4514        if let Some(namespace) = &storage.namespace {
4515            encoded.text("execution.storage.sharedNamespace", namespace.as_str());
4516        }
4517    } else {
4518        encoded.byte("execution.storage.present", 0);
4519    }
4520}
4521
4522fn encode_asset_constraints(
4523    encoded: &mut AuthorityEncoder,
4524    asset: Option<&dekopon_capability::AssetConstraints>,
4525) {
4526    if let Some(asset) = asset {
4527        encoded.byte("execution.asset.present", 1);
4528        encoded.boolean("execution.asset.attach", asset.attach);
4529        encoded.boolean("execution.asset.remove", asset.remove);
4530        encoded.boolean("execution.asset.send", asset.send);
4531    } else {
4532        encoded.byte("execution.asset.present", 0);
4533    }
4534}
4535
4536fn encode_host_limits(
4537    encoded: &mut AuthorityEncoder,
4538    limits: &dekopon_broker_host::BrokerHostLimits,
4539) {
4540    encoded.number("host.maxMemoryBytes", limits.max_memory_bytes as u128);
4541    encoded.number("host.maxTableElements", limits.max_table_elements as u128);
4542    encoded.number("host.maxInstances", limits.max_instances as u128);
4543    encoded.number("host.maxTables", limits.max_tables as u128);
4544    encoded.number("host.maxMemories", limits.max_memories as u128);
4545    encoded.number("host.maxInputBytes", limits.max_input_bytes as u128);
4546    encoded.number("host.maxOutputBytes", limits.max_output_bytes as u128);
4547    encoded.number("host.maxHttpRequests", u128::from(limits.max_http_requests));
4548    encoded.number(
4549        "host.maxHttpRequestBytes",
4550        u128::from(limits.max_http_request_bytes),
4551    );
4552    encoded.number(
4553        "host.maxHttpResponseBytes",
4554        u128::from(limits.max_http_response_bytes),
4555    );
4556    encoded.number("host.maxHttpHeaders", limits.max_http_headers as u128);
4557    encoded.number(
4558        "host.maxHttpHeaderBytes",
4559        limits.max_http_header_bytes as u128,
4560    );
4561    encoded.number("host.fuel", u128::from(limits.fuel));
4562    encoded.number("host.maxTimeoutNanos", limits.max_timeout.as_nanos());
4563}
4564
4565fn encode_memory_config(encoded: &mut AuthorityEncoder, memory: &ChatMemoryConfig) {
4566    encoded.byte(
4567        "memory.continuityPolicy",
4568        match memory.continuity_policy {
4569            ContinuityPolicy::Relaxed => 0,
4570            ContinuityPolicy::Paranoid => 1,
4571        },
4572    );
4573    encoded.number(
4574        "memory.maxLookbackTurns",
4575        u128::from(memory.max_lookback_turns),
4576    );
4577    encoded.number("memory.maxRecentTurns", u128::from(memory.max_recent_turns));
4578    encoded.number(
4579        "memory.maxSearchResults",
4580        u128::from(memory.max_search_results),
4581    );
4582    encoded.number("memory.maxQueryBytes", u128::from(memory.max_query_bytes));
4583    encoded.number("memory.maxResultBytes", u128::from(memory.max_result_bytes));
4584    encoded.number("memory.maxTurnBytes", u128::from(memory.max_turn_bytes));
4585    encoded.number(
4586        "memory.compactionTargetBytes",
4587        u128::from(memory.compaction_target_bytes),
4588    );
4589    encoded.number(
4590        "memory.compactionThresholdBytes",
4591        u128::from(memory.compaction_threshold_bytes),
4592    );
4593}
4594
4595fn encode_storage_limits(
4596    encoded: &mut AuthorityEncoder,
4597    limits: &dekopon_storage_host::StorageLimits,
4598) {
4599    for (label, value) in [
4600        ("storage.maxRootBytes", limits.max_root_bytes),
4601        ("storage.maxNamespaces", limits.max_namespaces),
4602        ("storage.maxNamespaceBytes", limits.max_namespace_bytes),
4603        (
4604            "storage.maxFilesPerNamespace",
4605            limits.max_files_per_namespace,
4606        ),
4607        ("storage.maxFileBytes", limits.max_file_bytes),
4608        ("storage.maxOpenHandles", limits.max_open_handles),
4609        (
4610            "storage.maxHandlesPerInvocation",
4611            limits.max_handles_per_invocation,
4612        ),
4613        (
4614            "storage.maxHostCallsPerInvocation",
4615            limits.max_host_calls_per_invocation,
4616        ),
4617        (
4618            "storage.maxReadBytesPerCall",
4619            limits.max_read_bytes_per_call,
4620        ),
4621        (
4622            "storage.maxReadBytesPerInvocation",
4623            limits.max_read_bytes_per_invocation,
4624        ),
4625        (
4626            "storage.maxWriteBytesPerCall",
4627            limits.max_write_bytes_per_call,
4628        ),
4629        (
4630            "storage.maxWriteBytesPerInvocation",
4631            limits.max_write_bytes_per_invocation,
4632        ),
4633        (
4634            "storage.maxEntropyBytesPerCall",
4635            limits.max_entropy_bytes_per_call,
4636        ),
4637        (
4638            "storage.maxEntropyBytesPerInvocation",
4639            limits.max_entropy_bytes_per_invocation,
4640        ),
4641        ("storage.lockTimeoutMs", limits.lock_timeout_ms),
4642        (
4643            "storage.finalizationBudgetMs",
4644            limits.finalization_budget_ms,
4645        ),
4646        // The label keeps the key's old name: renaming it would rotate every authority-bound generation.
4647        (
4648            "storage.maxPendingTransactions",
4649            limits.max_active_invocations,
4650        ),
4651        ("storage.startupMaxEntries", limits.startup_max_entries),
4652    ] {
4653        encoded.number(label, u128::from(value));
4654    }
4655}
4656
4657const CHAT_REFUSAL: &str = "chat-attestation-denied";
4658
4659const CONSOLE_SMOKE_TRANSPORT: &str = "console-smoke";
4660const CONSOLE_SMOKE_REFUSAL: &str = "console-smoke-claim-denied";
4661const CONSOLE_REAL_SCOPE_REASON: &str = "console-real-scope-denied";
4662pub const CONSOLE_REAL_SCOPE_REFUSAL: &str = "dekopon sandbox: console sessions cannot attest a real conversation; use --smoke-conversation or the authenticated gateway";
4663const CONSOLE_SMOKE_DOMAIN: &[u8] = b"dekopon-console-smoke-v1\0";
4664
4665fn render_chat_slots(
4666    http: Option<&HttpConstraints>,
4667    scope: Option<&ChatScopeClaim>,
4668) -> Result<ChatSlotValues, &'static str> {
4669    let mut values = ChatSlotValues::default();
4670    let Some(http) = http.filter(|http| !http.request_templates.is_empty()) else {
4671        return Ok(values);
4672    };
4673    let scope = scope.ok_or("chat-scope-required")?;
4674    let api_form = |id: &str| match scope.kind {
4675        ChatTransportKind::Slack => id.to_ascii_uppercase(),
4676        ChatTransportKind::Fauxlack
4677        | ChatTransportKind::Discord
4678        | ChatTransportKind::Telegram
4679        | ChatTransportKind::Whatsapp
4680        | ChatTransportKind::Github
4681        | ChatTransportKind::Local => id.to_owned(),
4682    };
4683    for slot in http.template_slots() {
4684        let value = match slot {
4685            ChatSlot::ConversationId => api_form(&scope.conversation.id),
4686            ChatSlot::ConversationThread => scope
4687                .conversation
4688                .thread
4689                .clone()
4690                .ok_or("request-template-slot-absent")?,
4691            ChatSlot::ConversationApiChannel => {
4692                api_form(scope.conversation.api_channel(scope.kind))
4693            }
4694            ChatSlot::Transport => scope.transport.as_str().to_owned(),
4695        };
4696        values.insert(slot, value);
4697    }
4698    Ok(values)
4699}
4700
4701fn is_console_smoke_literal(scope: &ChatScopeClaim) -> bool {
4702    let ChatScopeClaim {
4703        transport: _,
4704        kind,
4705        conversation:
4706            Conversation {
4707                kind: conversation_kind,
4708                container,
4709                id,
4710                thread,
4711            },
4712        delivery,
4713        participant: _,
4714        github,
4715        trigger,
4716    } = scope;
4717    *kind == ChatTransportKind::Local
4718        && *conversation_kind == ConversationKind::DirectMessage
4719        && container.is_none()
4720        && id == CONSOLE_SMOKE_TRANSPORT
4721        && thread.is_none()
4722        && *trigger == Trigger::Message
4723        && delivery.is_none()
4724        && github.is_none()
4725}
4726
4727fn console_smoke_delivery(
4728    scope: &ChatScopeClaim,
4729    placeholder: DeliveryIdentity,
4730) -> DeliveryIdentity {
4731    match placeholder {
4732        DeliveryIdentity::Local {
4733            boot_nonce,
4734            connection,
4735            sequence,
4736            ..
4737        } => DeliveryIdentity::Local {
4738            transport: scope.transport.clone(),
4739            conversation: scope.conversation.key(),
4740            boot_nonce,
4741            connection,
4742            sequence,
4743        },
4744        placeholder @ (DeliveryIdentity::Fauxlack { .. }
4745        | DeliveryIdentity::Github { .. }
4746        | DeliveryIdentity::Slack { .. }
4747        | DeliveryIdentity::Discord { .. }
4748        | DeliveryIdentity::Telegram { .. }
4749        | DeliveryIdentity::Whatsapp { .. }) => placeholder,
4750    }
4751}
4752
4753#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
4754#[serde(rename_all = "camelCase")]
4755pub enum DenyingPrincipal {
4756    Asker,
4757    Space,
4758    Both,
4759}
4760
4761impl DenyingPrincipal {
4762    const fn as_str(self) -> &'static str {
4763        match self {
4764            Self::Asker => "asker",
4765            Self::Space => "space",
4766            Self::Both => "both",
4767        }
4768    }
4769}
4770
4771#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
4772#[serde(rename_all = "camelCase")]
4773pub struct SpaceDecision {
4774    id: PrincipalId,
4775    #[serde(skip_serializing_if = "Option::is_none")]
4776    asker_allowed: Option<bool>,
4777    #[serde(skip_serializing_if = "Option::is_none")]
4778    allowed: Option<bool>,
4779    #[serde(skip_serializing_if = "Vec::is_empty")]
4780    policy_ids: Vec<String>,
4781    #[serde(skip_serializing_if = "Option::is_none")]
4782    denied_by: Option<DenyingPrincipal>,
4783}
4784
4785#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
4786#[serde(rename_all = "kebab-case")]
4787enum GithubDenier {
4788    Facts,
4789    AuthorSet,
4790}
4791impl GithubDenier {
4792    fn as_str(self) -> &'static str {
4793        match self {
4794            Self::Facts => "facts",
4795            Self::AuthorSet => "author-set",
4796        }
4797    }
4798}
4799#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
4800#[serde(rename_all = "camelCase")]
4801struct GithubDenial {
4802    phase: GithubDenier,
4803    delivery: dekopon_core::github::GithubDeliveryId,
4804}
4805
4806fn denying_principal(asker: bool, space: bool) -> Option<DenyingPrincipal> {
4807    match (asker, space) {
4808        (true, true) => None,
4809        (false, true) => Some(DenyingPrincipal::Asker),
4810        (true, false) => Some(DenyingPrincipal::Space),
4811        (false, false) => Some(DenyingPrincipal::Both),
4812    }
4813}
4814fn merge_policy_decision(previous: &mut PolicyDecision, next: PolicyDecision) {
4815    previous.allowed &= next.allowed;
4816    previous.errors_present |= next.errors_present;
4817    previous
4818        .determining_policy_ids
4819        .extend(next.determining_policy_ids);
4820    previous.determining_policy_ids.sort();
4821    previous.determining_policy_ids.dedup();
4822    previous
4823        .erroring_policy_ids
4824        .extend(next.erroring_policy_ids);
4825    previous.erroring_policy_ids.sort();
4826    previous.erroring_policy_ids.dedup();
4827    previous.refusal = previous.refusal.take().or(next.refusal);
4828    previous.opaque_body = previous.opaque_body.take().or(next.opaque_body);
4829}
4830
4831struct EvaluatedDecision {
4832    github_denial: Option<GithubDenial>,
4833    policy: PolicyDecision,
4834    space: Option<SpaceDecision>,
4835}
4836impl std::ops::Deref for EvaluatedDecision {
4837    type Target = PolicyDecision;
4838    fn deref(&self) -> &Self::Target {
4839        &self.policy
4840    }
4841}
4842
4843fn merge_space_decision(previous: &mut Option<SpaceDecision>, next: Option<SpaceDecision>) {
4844    if let Some(mut next) = next {
4845        if let Some(previous) = previous.as_ref() {
4846            next.asker_allowed = next
4847                .asker_allowed
4848                .zip(previous.asker_allowed)
4849                .map(|(a, b)| a && b);
4850            next.allowed = next.allowed.zip(previous.allowed).map(|(a, b)| a && b);
4851            next.policy_ids.extend(previous.policy_ids.iter().cloned());
4852            next.policy_ids.sort();
4853            next.policy_ids.dedup();
4854        }
4855        next.denied_by = next
4856            .asker_allowed
4857            .zip(next.allowed)
4858            .and_then(|(asker, space)| denying_principal(asker, space));
4859        *previous = Some(next);
4860    }
4861}
4862
4863#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
4864#[serde(rename_all = "camelCase")]
4865pub struct DecisionAuthority {
4866    #[serde(default, skip_serializing_if = "Option::is_none")]
4867    github_denial: Option<GithubDenial>,
4868    principal_kind: PrincipalKind,
4869    started_by: Option<TurnStartedBy>,
4870    chat: Option<ChatScopeClaim>,
4871    space: Option<SpaceDecision>,
4872}
4873
4874fn decision_authority(
4875    context: &AuthenticatedContext,
4876    kind: PrincipalKind,
4877    space: Option<SpaceDecision>,
4878) -> Box<DecisionAuthority> {
4879    Box::new(DecisionAuthority {
4880        github_denial: None,
4881        principal_kind: kind,
4882        started_by: turn_started_by(context),
4883        chat: context.chat_scope.clone(),
4884        space: space.or_else(|| {
4885            context.space.as_ref().map(|id| SpaceDecision {
4886                id: id.clone(),
4887                asker_allowed: None,
4888                allowed: None,
4889                policy_ids: Vec::new(),
4890                denied_by: None,
4891            })
4892        }),
4893    })
4894}
4895
4896pub struct Refusal {
4897    pub session: dekopon_broker_protocol::SessionRefusal,
4898    pub reason: &'static str,
4899    wire: &'static str,
4900    pub policy_ids: Vec<String>,
4901    evaluation: Option<Box<PolicyEvaluation>>,
4902}
4903
4904struct PolicyEvaluation {
4905    github_denial: Option<GithubDenial>,
4906    errors_present: bool,
4907    cause: Option<String>,
4908    space: Option<SpaceDecision>,
4909}
4910
4911pub struct CapabilityDecision {
4912    pub set: ConstraintSet,
4913    policy_ids: Vec<String>,
4914    slots: ChatSlotValues,
4915    space: Option<SpaceDecision>,
4916    errors_present: bool,
4917}
4918
4919impl Refusal {
4920    fn opaque(mut self) -> Self {
4921        self.wire = CHAT_REFUSAL;
4922        self
4923    }
4924}
4925
4926const fn console_real_scope_refusal() -> Refusal {
4927    Refusal {
4928        session: dekopon_broker_protocol::SessionRefusal::Other,
4929        reason: CONSOLE_REAL_SCOPE_REASON,
4930        wire: CONSOLE_REAL_SCOPE_REFUSAL,
4931        policy_ids: Vec::new(),
4932        evaluation: None,
4933    }
4934}
4935
4936const fn unevaluated_refusal(reason: &'static str) -> Refusal {
4937    Refusal {
4938        session: dekopon_broker_protocol::SessionRefusal::Other,
4939        reason,
4940        wire: reason,
4941        policy_ids: Vec::new(),
4942        evaluation: None,
4943    }
4944}
4945
4946fn determined_refusal(reason: &'static str, policy_ids: Vec<String>) -> Refusal {
4947    Refusal {
4948        session: dekopon_broker_protocol::SessionRefusal::Other,
4949        reason,
4950        wire: reason,
4951        policy_ids,
4952        evaluation: None,
4953    }
4954}
4955
4956fn decided_refusal(decision: EvaluatedDecision, denied: &'static str) -> Refusal {
4957    let reason = denial_reason(&decision, denied);
4958    Refusal {
4959        evaluation: Some(Box::new(PolicyEvaluation {
4960            errors_present: decision.errors_present,
4961            cause: decision.policy.refusal,
4962            space: decision.space,
4963            github_denial: decision.github_denial,
4964        })),
4965        ..determined_refusal(reason, decision.policy.determining_policy_ids)
4966    }
4967}
4968
4969fn denial_reason(decision: &EvaluatedDecision, denied: &'static str) -> &'static str {
4970    if decision.errors_present {
4971        "policy-error"
4972    } else {
4973        denied
4974    }
4975}
4976
4977fn report_inspection_refusal(
4978    refusal: &Refusal,
4979    peer: &AuthenticatedContext,
4980    subject: &Subject,
4981    agent: &AgentId,
4982) {
4983    tracing::warn!(
4984        event = "broker_capabilities_refused",
4985        reason = refusal.reason,
4986        policy_ids = ?refusal.policy_ids,
4987        subject = %subject,
4988        agent = %agent,
4989        via = %peer.principal(),
4990        "broker.capabilities.refused"
4991    );
4992}
4993
4994fn emit_audit_event(event: &AuditEvent) {
4995    if let AuditEvent::Decision { authority, .. } = event
4996        && let Some(batch) = authority
4997            .chat
4998            .as_ref()
4999            .and_then(|scope| scope.github.as_ref())
5000    {
5001        let deliveries = batch.deliveries();
5002        let labels = batch
5003            .events()
5004            .iter()
5005            .map(dekopon_core::github::GithubEvent::label)
5006            .collect::<Vec<_>>();
5007        let labels = labels.iter().map(String::as_str).collect::<Vec<_>>();
5008        let actors = batch
5009            .events()
5010            .iter()
5011            .map(|event| event.actor.id.get())
5012            .collect::<Vec<_>>();
5013        let actors = actors.iter().collect::<Vec<_>>();
5014        dekopon_telemetry::with_event_string_array("github.delivery", &deliveries, || {
5015            dekopon_telemetry::with_event_string_array("github.event", &labels, || {
5016                dekopon_telemetry::with_event_string_array("github.actor.id", &actors, || {
5017                    emit_audit_event_record(event)
5018                })
5019            })
5020        });
5021    } else {
5022        emit_audit_event_record(event);
5023    }
5024}
5025
5026fn emit_audit_event_record(event: &AuditEvent) {
5027    match event {
5028        AuditEvent::Decision {
5029            authority,
5030            invocation,
5031            principal,
5032            actor,
5033            via,
5034            attested_subject,
5035            capability,
5036            secret,
5037            secret_sink,
5038            provider,
5039            authorized_by,
5040            decision_id,
5041            policy_ids,
5042            policy_error_ids,
5043            policy_errors_present,
5044            decision_point,
5045            policy_digest,
5046            allowed,
5047            reason,
5048            storage_scope_commitment,
5049            storage,
5050            decision_digest: _,
5051            trace: _,
5052        } => tracing::info!(
5053            target: "dekopon_broker::audit",
5054            {
5055                audit.event = "broker.decision",
5056                github.denier = authority.github_denial.as_ref().map(|denial|denial.phase.as_str()),
5057                github.denier.delivery = authority.github_denial.as_ref().map(|denial|denial.delivery.as_str()),
5058                principal.kind = authority.principal_kind.as_str(),
5059                turn.started_by = authority.started_by.map(TurnStartedBy::as_str),
5060                space.id = authority.space.as_ref().map(|space| space.id.as_str()),
5061                asker.allowed = authority.space.as_ref().and_then(|space| space.asker_allowed),
5062                space.allowed = authority.space.as_ref().and_then(|space| space.allowed),
5063                space.policy.ids = authority.space.as_ref().and_then(|space| joined(&space.policy_ids)),
5064                decision.denied_by = authority.space.as_ref().and_then(|space| space.denied_by.map(DenyingPrincipal::as_str)),
5065                transport.id = authority.chat.as_ref().map(|chat| chat.transport.as_str()),
5066                transport.kind = authority.chat.as_ref().map(|chat| chat.kind.to_string()),
5067                conversation.kind = authority.chat.as_ref().map(|chat| chat.conversation.kind.as_str()),
5068                conversation.container = authority.chat.as_ref().and_then(|chat| chat.conversation.container.as_deref()),
5069                conversation.id = authority.chat.as_ref().map(|chat| chat.conversation.id.as_str()),
5070                conversation.thread = authority.chat.as_ref().and_then(|chat| chat.conversation.thread.as_deref()),
5071                participant.handle = authority.chat.as_ref().and_then(|chat| chat.participant.as_deref()),
5072                delivery.kind = authority.chat.as_ref().and_then(|chat| chat.delivery.as_ref().map(delivery_kind)),
5073                delivery.id = authority.chat.as_ref().and_then(|chat| chat.delivery.as_ref().map(delivery_id)),
5074                invocation.id = %invocation,
5075                capability.id = %capability,
5076                decision.id = decision_id.as_str(),
5077                decision.allowed = allowed,
5078                decision.reason = reason.as_deref(),
5079                principal = principal.as_ref().map(ToString::to_string),
5080                actor.kind = actor.as_ref().map(actor_kind),
5081                actor.id = actor.as_ref().map(actor_id),
5082                via = via.as_ref().map(ToString::to_string),
5083                subject = attested_subject.as_ref().map(ToString::to_string),
5084                provider = provider.as_ref().map(ToString::to_string),
5085                authorized.by = authorized_by.as_ref().map(ToString::to_string),
5086                policy.ids = joined(policy_ids),
5087                policy.error_ids = joined(policy_error_ids),
5088                policy.errors_present = policy_errors_present,
5089                decision.point = decision_point.as_str(),
5090                policy.digest = policy_digest.as_deref(),
5091                secret = secret.as_ref().map(ToString::to_string),
5092                secret.sink = secret_sink.as_ref().map(ToString::to_string),
5093                storage.scope_commitment = storage_scope_commitment
5094                    .as_ref()
5095                    .map(StorageScopeCommitment::as_str),
5096                storage.evidence = storage.as_ref().and_then(rendered),
5097            },
5098            "broker.decision"
5099        ),
5100        AuditEvent::Execution {
5101            invocation,
5102            principal,
5103            actor,
5104            via,
5105            attested_subject,
5106            capability,
5107            secret,
5108            secret_sink,
5109            provider,
5110            authorized_by,
5111            decision_id,
5112            policy_ids,
5113            policy_digest,
5114            provider_artifact_sha256,
5115            effect,
5116            risk,
5117            outcome,
5118            exit_status,
5119            duration_ms,
5120            error,
5121            error_detail,
5122            http_calls,
5123            storage_scope_commitment,
5124            storage,
5125            trace: _,
5126        } => tracing::info!(
5127            target: "dekopon_broker::audit",
5128            {
5129                audit.event = "broker.execution",
5130                invocation.id = %invocation,
5131                capability.id = %capability,
5132                decision.id = decision_id.as_str(),
5133                principal = principal.as_ref().map(ToString::to_string),
5134                actor.kind = actor.as_ref().map(actor_kind),
5135                actor.id = actor.as_ref().map(actor_id),
5136                via = via.as_ref().map(ToString::to_string),
5137                subject = attested_subject.as_ref().map(ToString::to_string),
5138                provider = provider.as_ref().map(ToString::to_string),
5139                authorized.by = authorized_by.as_ref().map(ToString::to_string),
5140                policy.ids = joined(policy_ids),
5141                policy.digest = policy_digest.as_deref(),
5142                provider.artifact_sha256 = provider_artifact_sha256.as_deref(),
5143                secret = secret.as_ref().map(ToString::to_string),
5144                secret.sink = secret_sink.as_ref().map(ToString::to_string),
5145                effect = ?effect,
5146                risk = ?risk,
5147                outcome = ?outcome,
5148                process.exit.code = exit_status.map(std::num::NonZeroU8::get),
5149                duration_ms = duration_ms,
5150                error = error.as_deref(),
5151                error.code = error_detail.as_ref().map(|detail| detail.code.as_str()),
5152                error.message = error_detail.as_ref().map(|detail| detail.message.as_str()),
5153                http.calls = rendered(http_calls),
5154                vm.session = http_calls
5155                    .iter()
5156                    .find_map(|call| call.vm_session.as_ref())
5157                    .map(dekopon_core::VmSession::as_str),
5158                storage.scope_commitment = storage_scope_commitment
5159                    .as_ref()
5160                    .map(StorageScopeCommitment::as_str),
5161                storage.evidence = storage.as_ref().and_then(rendered),
5162            },
5163            "broker.execution"
5164        ),
5165    }
5166}
5167
5168fn delivery_kind(delivery: &DeliveryIdentity) -> &'static str {
5169    match delivery {
5170        DeliveryIdentity::Fauxlack { .. } => "fauxlack",
5171        DeliveryIdentity::Slack { .. } => "slack",
5172        DeliveryIdentity::Discord { .. } => "discord",
5173        DeliveryIdentity::Telegram { .. } => "telegram",
5174        DeliveryIdentity::Whatsapp { .. } => "whatsapp",
5175        DeliveryIdentity::Local { .. } => "local",
5176        DeliveryIdentity::Github { .. } => "github",
5177    }
5178}
5179
5180fn delivery_id(delivery: &DeliveryIdentity) -> String {
5181    match delivery {
5182        DeliveryIdentity::Slack { timestamp, .. } => timestamp.clone(),
5183        DeliveryIdentity::Fauxlack { message, .. }
5184        | DeliveryIdentity::Discord { message, .. }
5185        | DeliveryIdentity::Telegram { message, .. }
5186        | DeliveryIdentity::Whatsapp { message, .. } => message.clone(),
5187        DeliveryIdentity::Github { delivery } => delivery.clone(),
5188        DeliveryIdentity::Local {
5189            boot_nonce,
5190            connection,
5191            sequence,
5192            ..
5193        } => format!("{boot_nonce}-{connection}-{sequence}"),
5194    }
5195}
5196
5197const fn actor_kind(actor: &Actor) -> &'static str {
5198    match actor {
5199        Actor::Human { .. } => "human",
5200        Actor::Agent { .. } => "agent",
5201        Actor::Service { .. } => "service",
5202    }
5203}
5204
5205fn actor_id(actor: &Actor) -> String {
5206    match actor {
5207        Actor::Human { principal } | Actor::Service { principal } => principal.to_string(),
5208        Actor::Agent { agent } => agent.to_string(),
5209    }
5210}
5211
5212fn rendered<T: Serialize>(value: &T) -> Option<String> {
5213    let json = serde_json::to_string(value).ok()?;
5214    (json != "[]" && json != "null").then_some(json)
5215}
5216
5217fn joined(ids: &[String]) -> Option<String> {
5218    (!ids.is_empty()).then(|| ids.join(","))
5219}
5220
5221fn report_audit_failure(stage: &'static str, invocation: &InvocationId, source: &AuditError) {
5222    tracing::error!(
5223        event = "broker_audit_append_failed",
5224        audit.stage = stage,
5225        category = source.category(),
5226        invocation = %invocation,
5227        error = %error_chain(source),
5228        "broker.audit.append.failed"
5229    );
5230}
5231
5232#[allow(
5233    clippy::too_many_arguments,
5234    reason = "audit construction keeps every trusted correlation field explicit"
5235)]
5236fn execution_event(
5237    context: &AuthenticatedContext,
5238    invocation: &InvocationId,
5239    trace: TraceId,
5240    capability: &CapabilityId,
5241    decision_id: &str,
5242    policy_ids: &[String],
5243    policy_digest: &str,
5244    provider_artifact_sha256: Option<&str>,
5245    authorized_by: &PrincipalId,
5246    set: &ConstraintSet,
5247    outcome: InvocationOutcome,
5248    provider_failure: Option<&BrokerHostError>,
5249    duration_ms: u64,
5250    error: Option<String>,
5251    error_detail: Option<ProviderFailureDetail>,
5252    http_calls: Vec<HttpCallEvidence>,
5253    storage_scope_commitment: Option<StorageScopeCommitment>,
5254    storage: Option<StorageEvidence>,
5255) -> AuditEvent {
5256    AuditEvent::Execution {
5257        invocation: invocation.clone(),
5258        trace,
5259        principal: Some(context.principal().clone()),
5260        actor: Some(context.actor().clone()),
5261        via: context.via().cloned(),
5262        attested_subject: context.attested_subject().cloned(),
5263        capability: capability.clone(),
5264        secret: set
5265            .constraints
5266            .secret_use
5267            .as_ref()
5268            .map(|secret| secret.secret.clone()),
5269        secret_sink: set
5270            .constraints
5271            .secret_use
5272            .as_ref()
5273            .map(|secret| secret.sink),
5274        provider: Some(set.provider.clone()),
5275        authorized_by: Some(authorized_by.clone()),
5276        decision_id: decision_id.to_owned(),
5277        policy_ids: policy_ids.to_vec(),
5278        policy_digest: Some(policy_digest.to_owned()),
5279        provider_artifact_sha256: provider_artifact_sha256.map(str::to_owned),
5280        effect: set.effect,
5281        risk: set.risk,
5282        outcome,
5283        exit_status: provider_failure.and_then(provider_execution_exit_status),
5284        duration_ms,
5285        error,
5286        error_detail,
5287        http_calls,
5288        storage_scope_commitment,
5289        storage,
5290    }
5291}
5292
5293#[expect(
5294    clippy::wildcard_enum_match_arm,
5295    reason = "reshaped by the unit that next rewrites this"
5296)]
5297fn provider_failure_detail(error: &BrokerHostError) -> Option<ProviderFailureDetail> {
5298    match error {
5299        BrokerHostError::ProviderFailure { stderr, .. } => {
5300            Some(ProviderFailureDetail::new("provider-exit", stderr))
5301        }
5302        BrokerHostError::HostCallRejected {
5303            reason:
5304                dekopon_broker_host::HostCallRejection::Http(
5305                    dekopon_broker_host::PolicyViolation::RedirectRefused,
5306                ),
5307            ..
5308        } => Some(ProviderFailureDetail::new(
5309            "redirect-refused",
5310            "signed download redirect refused",
5311        )),
5312        BrokerHostError::HostCallRejected {
5313            reason:
5314                dekopon_broker_host::HostCallRejection::Http(
5315                    dekopon_broker_host::PolicyViolation::ByteLimit(Some(exceeded)),
5316                ),
5317            ..
5318        } => Some(ProviderFailureDetail::new(
5319            exceeded.key.as_str(),
5320            &exceeded.to_string(),
5321        )),
5322        _ => None,
5323    }
5324}
5325
5326fn provider_execution_exit_status(error: &BrokerHostError) -> Option<std::num::NonZeroU8> {
5327    match error {
5328        BrokerHostError::ProviderFailure { .. } => provider_exit_status(error),
5329        BrokerHostError::PeerDisconnected
5330        | BrokerHostError::AssetOverBudget
5331        | BrokerHostError::AssetInput { .. }
5332        | BrokerHostError::NoProviders
5333        | BrokerHostError::InvalidLimit { .. }
5334        | BrokerHostError::AuthorizationExceedsHostLimit { .. }
5335        | BrokerHostError::InvalidHttpAuthorization
5336        | BrokerHostError::MixedHostAuthorization
5337        | BrokerHostError::InvalidSecretAuthorization { .. }
5338        | BrokerHostError::SecretAuthorizationExceedsHttp
5339        | BrokerHostError::SecretCredentialMismatch
5340        | BrokerHostError::StorageDisabled
5341        | BrokerHostError::MissingStorageGrant
5342        | BrokerHostError::UnexpectedStorageGrant
5343        | BrokerHostError::StorageGrantMismatch
5344        | BrokerHostError::Storage { .. }
5345        | BrokerHostError::HttpConfiguration { .. }
5346        | BrokerHostError::Engine { .. }
5347        | BrokerHostError::Store { .. }
5348        | BrokerHostError::Linker { .. }
5349        | BrokerHostError::InvalidArtifactSize { .. }
5350        | BrokerHostError::InvalidArtifactDigest
5351        | BrokerHostError::ArtifactTooLarge { .. }
5352        | BrokerHostError::ArtifactSizeMismatch { .. }
5353        | BrokerHostError::ArtifactDigestMismatch { .. }
5354        | BrokerHostError::ProviderIdentityMismatch { .. }
5355        | BrokerHostError::ArtifactMetadata { .. }
5356        | BrokerHostError::CompiledArtifactMissing { .. }
5357        | BrokerHostError::CompiledArtifact { .. }
5358        | BrokerHostError::CacheMaintenance { .. }
5359        | BrokerHostError::PrecompileWorker { .. }
5360        | BrokerHostError::MemoryBudgetExhausted { .. }
5361        | BrokerHostError::Compile { .. }
5362        | BrokerHostError::Instantiate { .. }
5363        | BrokerHostError::DescribeUsedHostImport { .. }
5364        | BrokerHostError::ConflictingProviders { .. }
5365        | BrokerHostError::InvalidCommandRun { .. }
5366        | BrokerHostError::UnknownCommandWord { .. }
5367        | BrokerHostError::MissingCommandExport { .. }
5368        | BrokerHostError::CommandExportSignature { .. }
5369        | BrokerHostError::CommandInputTooLarge { .. }
5370        | BrokerHostError::RunCommand { .. }
5371        | BrokerHostError::RunCommandUsedHostImport { .. }
5372        | BrokerHostError::Describe { .. }
5373        | BrokerHostError::InvalidManifest { .. }
5374        | BrokerHostError::Manifest { .. }
5375        | BrokerHostError::UnknownCapability { .. }
5376        | BrokerHostError::AuthorizedProviderMismatch { .. }
5377        | BrokerHostError::ProviderDoesNotImplement { .. }
5378        | BrokerHostError::InputNotObject { .. }
5379        | BrokerHostError::SerializeInput { .. }
5380        | BrokerHostError::InputTooLarge { .. }
5381        | BrokerHostError::OutputTooLarge { .. }
5382        | BrokerHostError::Timeout { .. }
5383        | BrokerHostError::HostCallRejected { .. }
5384        | BrokerHostError::StorageCallRejected { .. }
5385        | BrokerHostError::Invoke { .. }
5386        | BrokerHostError::StdioAdmission { .. } => None,
5387    }
5388}
5389
5390fn provider_exit_status(error: &BrokerHostError) -> Option<std::num::NonZeroU8> {
5391    if let BrokerHostError::ProviderFailure { status, .. } = error {
5392        std::num::NonZeroU8::new(*status)
5393    } else if let BrokerHostError::HostCallRejected {
5394        reason:
5395            dekopon_broker_host::HostCallRejection::Http(
5396                dekopon_broker_host::PolicyViolation::RedirectRefused,
5397            ),
5398        ..
5399    } = error
5400    {
5401        std::num::NonZeroU8::new(3)
5402    } else {
5403        None
5404    }
5405}
5406
5407#[derive(Serialize)]
5408#[serde(rename_all = "camelCase")]
5409struct DecisionMaterial<'a> {
5410    invocation: &'a InvocationId,
5411    trace: TraceId,
5412    principal: &'a PrincipalId,
5413    actor: &'a Actor,
5414    via: Option<&'a PrincipalId>,
5415    attested_subject: Option<&'a Subject>,
5416    capability: &'a CapabilityId,
5417    #[serde(skip_serializing_if = "Option::is_none")]
5418    secret_use: Option<&'a SecretUseProposal>,
5419    provider: Option<&'a ProviderId>,
5420    authorized_by: &'a PrincipalId,
5421    #[serde(skip_serializing_if = "<[String]>::is_empty")]
5422    policy_ids: &'a [String],
5423    policy_digest: &'a str,
5424    constraints: Option<&'a ExecutionConstraints>,
5425    allowed: bool,
5426    reason: Option<&'a str>,
5427    #[serde(skip_serializing_if = "Option::is_none")]
5428    space: Option<&'a SpaceDecision>,
5429}
5430
5431fn decision_evidence_digest(label: &str, value: &impl Serialize) -> Result<String, BrokerError> {
5432    evidence_digest(label, value).map_err(|source| BrokerError::DecisionEvidence { source })
5433}
5434
5435fn outcome_evidence_digest(
5436    invocation: &InvocationId,
5437    label: &str,
5438    value: &impl Serialize,
5439) -> Result<String, BrokerError> {
5440    evidence_digest(label, value).map_err(|source| BrokerError::OutcomeEvidence {
5441        invocation: invocation.clone(),
5442        source,
5443    })
5444}
5445
5446fn evidence_digest(label: &str, value: &impl Serialize) -> Result<String, serde_json::Error> {
5447    Ok(digest_parts(
5448        EVIDENCE_HASH_DOMAIN,
5449        &[label.as_bytes(), &[0], &serde_json::to_vec(value)?],
5450    ))
5451}
5452
5453fn digest_parts(domain: &[u8], parts: &[&[u8]]) -> String {
5454    let mut hasher = Sha256::new();
5455    hasher.update(domain);
5456    for part in parts {
5457        hasher.update(part);
5458    }
5459    format!("sha256:{}", hex_bytes(&hasher.finalize()))
5460}
5461
5462fn hex_bytes(bytes: &[u8]) -> String {
5463    const HEX: &[u8; 16] = b"0123456789abcdef";
5464    let mut output = String::with_capacity(bytes.len() * 2);
5465    for byte in bytes {
5466        output.push(char::from(HEX[usize::from(byte >> 4)]));
5467        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
5468    }
5469    output
5470}
5471
5472fn duration_millis(duration: std::time::Duration) -> u64 {
5473    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
5474}
5475
5476#[expect(
5477    clippy::wildcard_enum_match_arm,
5478    reason = "reshaped by the unit that next rewrites this"
5479)]
5480fn public_host_error(error: &BrokerHostError) -> &'static str {
5481    match error {
5482        BrokerHostError::AuthorizationExceedsHostLimit { .. }
5483        | BrokerHostError::InvalidHttpAuthorization
5484        | BrokerHostError::MixedHostAuthorization
5485        | BrokerHostError::StorageDisabled
5486        | BrokerHostError::MissingStorageGrant
5487        | BrokerHostError::UnexpectedStorageGrant
5488        | BrokerHostError::StorageGrantMismatch
5489        | BrokerHostError::InvalidSecretAuthorization { .. }
5490        | BrokerHostError::SecretAuthorizationExceedsHttp
5491        | BrokerHostError::SecretCredentialMismatch
5492        | BrokerHostError::HttpConfiguration { .. } => "authorization-constraint",
5493        BrokerHostError::UnknownCapability { .. }
5494        | BrokerHostError::ProviderDoesNotImplement { .. }
5495        | BrokerHostError::UnknownCommandWord { .. } => "capability-unavailable",
5496        // These startup-only variants are named explicitly rather than wildcarded, so a future
5497        // variant can never be silently misclassified here.
5498        BrokerHostError::ConflictingProviders { .. }
5499        | BrokerHostError::MissingCommandExport { .. }
5500        | BrokerHostError::CommandExportSignature { .. }
5501        | BrokerHostError::InvalidArtifactSize { .. }
5502        | BrokerHostError::InvalidArtifactDigest
5503        | BrokerHostError::ArtifactTooLarge { .. }
5504        | BrokerHostError::ArtifactSizeMismatch { .. }
5505        | BrokerHostError::ArtifactDigestMismatch { .. }
5506        | BrokerHostError::ProviderIdentityMismatch { .. } => "provider-configuration",
5507        BrokerHostError::MemoryBudgetExhausted { .. } => "host-memory-budget",
5508        BrokerHostError::AssetOverBudget => "over-budget",
5509        BrokerHostError::AuthorizedProviderMismatch { .. } => "authorized-provider-mismatch",
5510        BrokerHostError::AssetInput { .. }
5511        | BrokerHostError::InputNotObject { .. }
5512        | BrokerHostError::SerializeInput { .. }
5513        | BrokerHostError::InputTooLarge { .. }
5514        | BrokerHostError::CommandInputTooLarge { .. } => "invalid-input",
5515        BrokerHostError::OutputTooLarge { .. } => "invalid-provider-output",
5516        BrokerHostError::RunCommand { .. }
5517        | BrokerHostError::RunCommandUsedHostImport { .. }
5518        | BrokerHostError::InvalidCommandRun { .. } => "command-rewrite-failed",
5519        BrokerHostError::Timeout { .. } => "provider-timeout",
5520        BrokerHostError::PeerDisconnected => "peer-disconnected",
5521        BrokerHostError::HostCallRejected { reason, .. } => match reason {
5522            dekopon_broker_host::HostCallRejection::Http(violation) => violation.label(),
5523            dekopon_broker_host::HostCallRejection::MonotonicOverflow
5524            | dekopon_broker_host::HostCallRejection::RandomTooLarge
5525            | dekopon_broker_host::HostCallRejection::RandomEntropy
5526            | dekopon_broker_host::HostCallRejection::AssetCallRejected => reason.label(),
5527        },
5528        BrokerHostError::StorageCallRejected {
5529            reason: "quota", ..
5530        } => "storage-quota",
5531        BrokerHostError::StorageCallRejected {
5532            reason: "timeout", ..
5533        } => "storage-timeout",
5534        BrokerHostError::StorageCallRejected {
5535            reason: "corrupt", ..
5536        } => "storage-corrupt",
5537        BrokerHostError::StorageCallRejected {
5538            reason: "denied", ..
5539        } => "storage-io",
5540        BrokerHostError::StorageCallRejected { .. } => "storage-io",
5541        BrokerHostError::Storage { source } => match source {
5542            dekopon_storage_host::StorageHostError::QuotaExceeded => "storage-quota",
5543            dekopon_storage_host::StorageHostError::Busy => "storage-busy",
5544            dekopon_storage_host::StorageHostError::Timeout => "storage-timeout",
5545            dekopon_storage_host::StorageHostError::Corrupt { .. }
5546            | dekopon_storage_host::StorageHostError::CorruptLayout { .. } => "storage-corrupt",
5547            _ => "storage-io",
5548        },
5549        BrokerHostError::Invoke { .. } => "provider-trap",
5550        BrokerHostError::ProviderFailure { .. } => "provider-failure",
5551        BrokerHostError::StdioAdmission { .. } => "invalid-input",
5552        BrokerHostError::NoProviders
5553        | BrokerHostError::InvalidLimit { .. }
5554        | BrokerHostError::Engine { .. }
5555        | BrokerHostError::Store { .. }
5556        | BrokerHostError::Linker { .. }
5557        | BrokerHostError::ArtifactMetadata { .. }
5558        | BrokerHostError::CompiledArtifact { .. }
5559        | BrokerHostError::CompiledArtifactMissing { .. }
5560        | BrokerHostError::CacheMaintenance { .. }
5561        | BrokerHostError::PrecompileWorker { .. }
5562        | BrokerHostError::Compile { .. }
5563        | BrokerHostError::Instantiate { .. }
5564        | BrokerHostError::DescribeUsedHostImport { .. }
5565        | BrokerHostError::Describe { .. }
5566        | BrokerHostError::InvalidManifest { .. }
5567        | BrokerHostError::Manifest { .. } => "broker-host-failure",
5568    }
5569}
5570
5571#[derive(Debug, Error)]
5572pub enum BrokerError {
5573    #[error("chat memory is unavailable")]
5574    MemoryUnavailable,
5575    #[error("chat memory input is invalid")]
5576    InvalidMemoryInput,
5577    #[error("broker storage authority failed")]
5578    Storage {
5579        #[source]
5580        source: dekopon_storage_host::StorageHostError,
5581    },
5582    #[error("broker storage materialization did not complete")]
5583    StorageTask {
5584        #[source]
5585        source: tokio::task::JoinError,
5586    },
5587    #[error("broker could not create constrained authorization")]
5588    Authorization {
5589        #[source]
5590        source: AuthorizationError,
5591    },
5592    #[error("broker could not serialize bounded decision evidence")]
5593    DecisionEvidence {
5594        #[source]
5595        source: serde_json::Error,
5596    },
5597    #[error("broker could not audit its authorization decision")]
5598    DecisionAudit {
5599        #[source]
5600        source: AuditError,
5601    },
5602    #[error("broker could not audit an authorized pre-provider failure")]
5603    AuthorizedFailureAudit {
5604        #[source]
5605        source: AuditError,
5606    },
5607    #[error("broker could not serialize terminal evidence for {invocation}")]
5608    OutcomeEvidence {
5609        invocation: InvocationId,
5610        #[source]
5611        source: serde_json::Error,
5612    },
5613    #[error("broker could not audit terminal execution for {invocation}")]
5614    OutcomeAudit {
5615        invocation: InvocationId,
5616        #[source]
5617        source: AuditError,
5618    },
5619}
5620
5621impl BrokerError {
5622    #[must_use]
5623    #[expect(
5624        clippy::wildcard_enum_match_arm,
5625        reason = "reshaped by the unit that next rewrites this"
5626    )]
5627    pub const fn storage_failure_code(&self) -> Option<&'static str> {
5628        let source = match self {
5629            Self::Storage { source } => source,
5630            Self::StorageTask { .. } => return Some("storage-io"),
5631            _ => return None,
5632        };
5633        Some(match source {
5634            dekopon_storage_host::StorageHostError::QuotaExceeded
5635            | dekopon_storage_host::StorageHostError::Arithmetic => "storage-quota",
5636            dekopon_storage_host::StorageHostError::Busy => "storage-busy",
5637            dekopon_storage_host::StorageHostError::Timeout => "storage-timeout",
5638            dekopon_storage_host::StorageHostError::Corrupt { .. }
5639            | dekopon_storage_host::StorageHostError::CorruptLayout { .. } => "storage-corrupt",
5640            _ => "storage-io",
5641        })
5642    }
5643
5644    #[must_use]
5645    pub fn storage_namespace_reset(&self) -> bool {
5646        matches!(self, Self::Storage { source } if source.namespace_reset())
5647    }
5648
5649    #[must_use]
5650    pub const fn capacity_failure_code(&self) -> Option<&'static str> {
5651        match self {
5652            Self::DecisionAudit {
5653                source: AuditError::Full { .. },
5654            }
5655            | Self::AuthorizedFailureAudit {
5656                source: AuditError::Full { .. },
5657            } => Some("capacity-exhausted"),
5658            Self::MemoryUnavailable
5659            | Self::InvalidMemoryInput
5660            | Self::Storage { .. }
5661            | Self::StorageTask { .. }
5662            | Self::Authorization { .. }
5663            | Self::DecisionEvidence { .. }
5664            | Self::OutcomeEvidence { .. }
5665            | Self::OutcomeAudit { .. } => None,
5666        }
5667    }
5668
5669    #[must_use]
5670    pub const fn unaudited_outcome(&self) -> Option<&InvocationId> {
5671        match self {
5672            Self::OutcomeEvidence { invocation, .. } | Self::OutcomeAudit { invocation, .. } => {
5673                Some(invocation)
5674            }
5675            Self::MemoryUnavailable
5676            | Self::InvalidMemoryInput
5677            | Self::Storage { .. }
5678            | Self::StorageTask { .. }
5679            | Self::Authorization { .. }
5680            | Self::DecisionEvidence { .. }
5681            | Self::DecisionAudit { .. }
5682            | Self::AuthorizedFailureAudit { .. } => None,
5683        }
5684    }
5685}
5686
5687#[cfg(test)]
5688mod tests;
5689
5690fn storage_scope_permits(context: &AuthenticatedContext, set: &ConstraintSet) -> bool {
5691    match set
5692        .constraints
5693        .storage
5694        .as_ref()
5695        .map(|storage| storage.scope)
5696    {
5697        Some(StorageScope::Space) => context.space.is_some(),
5698        Some(StorageScope::Agent) => context.space.is_none(),
5699        Some(StorageScope::PrivateConversation | StorageScope::SharedConversation) | None => true,
5700    }
5701}