Skip to main content

lean_ctx/core/context_admission/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Context admission: the one local decision every governed source passes
3//! *before* it is cached, compressed, indexed or delivered.
4//!
5//! `admit` runs the built-in detectors (secrets, checksum-validated PII,
6//! prompt injection, classification markers, secret-like paths) over the
7//! original text, decides one [`ContextDispositionV1`], applies the required
8//! transformations and re-checks the result. Blocking signals are evaluated
9//! before any redaction can hide them, and a redaction that leaves a
10//! detectable secret behind withholds the content instead (fail closed).
11//!
12//! The result carries the canonical `context_gateway` vocabulary — signals
13//! with honest coverage, reason codes, classification — and never the matched
14//! values. Defaults are on (owner decision E2); each detector can be tuned in
15//! the global `[context_gateway]` section, which project-local configuration
16//! cannot weaken.
17
18pub mod capture;
19pub mod carrier;
20mod clean;
21pub(crate) mod cross_line;
22mod detectors;
23pub mod egress;
24pub mod hud;
25mod notes;
26pub mod origin;
27pub mod provider;
28pub mod receipt_store;
29pub mod recovery;
30pub(crate) mod semantic;
31pub mod semantic_deferred;
32pub mod stored;
33pub mod stores;
34pub mod tool_output;
35pub mod withheld;
36
37use std::path::Path;
38
39use lean_ctx_protocol::Sha256Digest;
40use lean_ctx_protocol::context_gateway::{
41    ClassificationV1, ContextDecisionV1, ContextDispositionV1, CoverageKindV1,
42    DestinationConstraintV1, DestinationLocalityV1, DestinationV1, DetectorSignalV1, GatewayModeV1,
43    ReasonCodeV1, TransformationKindV1, TrustLevelV1,
44};
45use serde::{Deserialize, Serialize};
46use sha2::{Digest, Sha256};
47
48use crate::core::config::SecretDetectionConfig;
49use crate::core::input_filters::FilterAction;
50
51/// `[context_gateway]` — global only; never merged from a project-local file.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(default)]
54pub struct ContextGatewayConfig {
55    /// Master switch. `LEAN_CTX_CONTEXT_GATEWAY=off` overrides it.
56    pub enabled: bool,
57    pub mode: GatewayModeV1,
58    /// Credentials and keys (patterns from `[secret_detection]`).
59    pub secrets: FilterAction,
60    /// Checksum-validated PII only: payment cards.
61    pub pii: FilterAction,
62    /// Prompt-injection heuristic (OWASP LLM01).
63    pub injection: FilterAction,
64    /// Explicit classification markings (`CONFIDENTIAL`, `classification: …`).
65    pub classification: FilterAction,
66    /// Bytes each detector may inspect per object; beyond it, coverage is
67    /// `partial`. Governed and sovereign modes withhold partially inspected
68    /// content, developer mode delivers it with a visible note.
69    pub max_inspected_bytes: usize,
70    /// Per-detector time budget; a detector that runs out reports `timed_out`.
71    pub detector_timeout_ms: u64,
72    /// Additional placement constraints applied to every final egress target.
73    /// These remain active when content scanning is disabled.
74    pub destination_constraints: Vec<DestinationConstraintV1>,
75    /// Optional target allow-list. Provider and locality are always checked;
76    /// model/account/region are checked when the configured entry supplies them.
77    /// Unknown locality never matches. Account references are configured labels,
78    /// not provider-verified identities.
79    pub allowed_destinations: Vec<DestinationV1>,
80    /// Where redaction counts are shown (see `hud`).
81    pub hud: hud::HudPlacement,
82}
83
84/// Same bound as policy-pack content inspection (`policy::content`).
85pub const DEFAULT_MAX_INSPECTED_BYTES: usize = 8 * 1024 * 1024;
86pub const DEFAULT_DETECTOR_TIMEOUT_MS: u64 = 2_000;
87
88impl Default for ContextGatewayConfig {
89    fn default() -> Self {
90        Self {
91            enabled: true,
92            mode: GatewayModeV1::Developer,
93            secrets: FilterAction::Redact,
94            pii: FilterAction::Redact,
95            injection: FilterAction::Warn,
96            classification: FilterAction::Warn,
97            max_inspected_bytes: DEFAULT_MAX_INSPECTED_BYTES,
98            detector_timeout_ms: DEFAULT_DETECTOR_TIMEOUT_MS,
99            destination_constraints: Vec::new(),
100            allowed_destinations: Vec::new(),
101            hud: hud::HudPlacement::Auto,
102        }
103    }
104}
105
106impl ContextGatewayConfig {
107    /// Effective master switch. The `LEAN_CTX_CONTEXT_GATEWAY` kill switch
108    /// (`0|false|off`) is a developer convenience: it disables admission only
109    /// in developer mode. A governed or sovereign deployment is configured by
110    /// its operator in the global file; a process environment cannot switch
111    /// its protection off, so the variable is ignored there (and reported, see
112    /// [`Self::kill_switch`]). Any other value still forces the gateway on.
113    #[must_use]
114    pub fn enabled_effective(&self) -> bool {
115        self.enabled_under(EnvSwitch::read())
116    }
117
118    /// The effective switch under one captured environment state. Admission
119    /// uses only this form, with the state its `AdmissionPolicy` captured:
120    /// the live environment is read once per snapshot, never per decision.
121    #[must_use]
122    pub(crate) fn enabled_under(&self, env: EnvSwitch) -> bool {
123        match self.kill_switch_under(env) {
124            KillSwitch::Unset | KillSwitch::Ignored => self.enabled,
125            KillSwitch::ForcedOn => true,
126            KillSwitch::Honoured => false,
127        }
128    }
129
130    /// What the `LEAN_CTX_CONTEXT_GATEWAY` environment variable does under
131    /// this configuration (for `doctor` and the admission log). Reads the
132    /// live environment.
133    #[must_use]
134    pub fn kill_switch(&self) -> KillSwitch {
135        self.kill_switch_under(EnvSwitch::read())
136    }
137
138    fn kill_switch_under(&self, env: EnvSwitch) -> KillSwitch {
139        match env {
140            EnvSwitch::Unset => return KillSwitch::Unset,
141            EnvSwitch::On => return KillSwitch::ForcedOn,
142            EnvSwitch::Off => {}
143        }
144        if self.mode == GatewayModeV1::Developer {
145            KillSwitch::Honoured
146        } else {
147            static REPORTED: std::sync::Once = std::sync::Once::new();
148            REPORTED.call_once(|| {
149                tracing::warn!(
150                    "LEAN_CTX_CONTEXT_GATEWAY=off ignored: the context gateway runs in {:?} mode",
151                    self.mode
152                );
153            });
154            KillSwitch::Ignored
155        }
156    }
157
158    /// Destination policy is a hard authorization gate, independent of the
159    /// optional content-detector switch.
160    #[must_use]
161    pub(crate) fn has_destination_policy(&self) -> bool {
162        !self.destination_constraints.is_empty() || !self.allowed_destinations.is_empty()
163    }
164
165    /// Check the final, trusted destination against configured placement rules.
166    #[must_use]
167    pub(crate) fn allows_destination(&self, actual: &DestinationV1) -> bool {
168        if actual.locality == DestinationLocalityV1::Unknown
169            || !actual.satisfies_all(&self.destination_constraints)
170        {
171            return false;
172        }
173        self.allowed_destinations.is_empty()
174            || self.allowed_destinations.iter().any(|expected| {
175                expected.locality != DestinationLocalityV1::Unknown
176                    && expected.provider == actual.provider
177                    && expected.locality == actual.locality
178                    && expected.organization_managed == actual.organization_managed
179                    && expected
180                        .model
181                        .as_ref()
182                        .is_none_or(|reference| actual.model.as_ref() == Some(reference))
183                    && expected
184                        .account_ref
185                        .as_ref()
186                        .is_none_or(|reference| actual.account_ref.as_ref() == Some(reference))
187                    && expected
188                        .region
189                        .as_ref()
190                        .is_none_or(|reference| actual.region.as_ref() == Some(reference))
191            })
192    }
193}
194
195/// The raw state of `LEAN_CTX_CONTEXT_GATEWAY`, read once and carried in the
196/// admission snapshot. It is the only environment-derived input of admission.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum EnvSwitch {
199    Unset,
200    /// `0|false|off`.
201    Off,
202    /// Any other value.
203    On,
204}
205
206impl EnvSwitch {
207    /// The live environment, now.
208    pub(crate) fn read() -> Self {
209        match std::env::var("LEAN_CTX_CONTEXT_GATEWAY") {
210            Err(_) => Self::Unset,
211            Ok(value) if matches!(value.trim(), "0" | "false" | "off") => Self::Off,
212            Ok(_) => Self::On,
213        }
214    }
215}
216
217/// Effect of the `LEAN_CTX_CONTEXT_GATEWAY` environment variable.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum KillSwitch {
220    Unset,
221    /// Set to a value other than `0|false|off`: the gateway is on.
222    ForcedOn,
223    /// `off` in developer mode: admission is disabled (`gateway.disabled`).
224    Honoured,
225    /// `off` in governed or sovereign mode: has no effect.
226    Ignored,
227}
228
229/// Everything `admit` needs, resolved once from the global configuration.
230#[derive(Debug, Clone)]
231pub struct AdmissionPolicy {
232    pub gateway: ContextGatewayConfig,
233    /// Pattern source for the secrets detector. An explicit
234    /// `secret_detection.enabled = false` turns the secrets detector off.
235    pub secret_patterns: SecretDetectionConfig,
236    /// Optional licensed semantic detectors (advisory; see `semantic`).
237    pub(crate) semantic: Option<semantic::SemanticDetector>,
238    /// Set when the snapshot this policy was resolved from could not apply the
239    /// global configuration, so `gateway` holds built-in defaults, not the
240    /// operator's settings. The configured mode is unknown: nothing is
241    /// admitted in this state, in any mode.
242    load_failure: Option<crate::core::config::ConfigLoadFailure>,
243    /// The environment switch as it was when this snapshot was taken.
244    env_switch: EnvSwitch,
245}
246
247impl AdmissionPolicy {
248    /// Resolve from a configuration snapshot. Whether the operator's settings
249    /// were applied is read from that same snapshot (`Config::load_failure`),
250    /// never from the process-global parse diagnostic.
251    #[must_use]
252    pub fn from_config(config: &crate::core::config::Config) -> Self {
253        Self {
254            gateway: config.context_gateway.clone(),
255            secret_patterns: config.secret_detection.clone(),
256            semantic: semantic::SemanticDetector::for_snapshot(config),
257            load_failure: config.load_failure,
258            env_switch: EnvSwitch::read(),
259        }
260    }
261
262    /// Built-in detectors only, from explicit settings.
263    #[must_use]
264    pub fn builtin(gateway: ContextGatewayConfig, secret_patterns: SecretDetectionConfig) -> Self {
265        Self {
266            gateway,
267            secret_patterns,
268            semantic: None,
269            load_failure: None,
270            env_switch: EnvSwitch::read(),
271        }
272    }
273
274    /// Whether this policy stands in for a global configuration that could
275    /// not be loaded (see [`Self::from_config`]).
276    #[must_use]
277    pub fn config_unloadable(&self) -> bool {
278        self.load_failure.is_some()
279    }
280
281    /// Reason codes of the refusal for an unloadable configuration: the one
282    /// stable admission code, then the loader's specific code. Never the
283    /// parse error text, which can quote file content.
284    pub(crate) fn config_refusal_codes(&self) -> Option<[&'static str; 2]> {
285        self.load_failure
286            .map(|failure| ["gateway.config_unloadable", failure.code()])
287    }
288
289    /// The master switch as admission applies it: an unloadable configuration
290    /// can never be "disabled", whatever its default values or the
291    /// environment say.
292    #[must_use]
293    pub fn enabled_effective(&self) -> bool {
294        self.config_unloadable() || self.gateway_switch()
295    }
296
297    /// The gateway's own switch under the environment state this snapshot
298    /// captured when it was built. The fingerprint and every decision taken
299    /// with this policy use exactly this value; the live environment is not
300    /// consulted again. Whether the snapshot is still current is a separate,
301    /// explicit question (`egress::PolicyEpoch::is_current`).
302    fn gateway_switch(&self) -> bool {
303        self.gateway.enabled_under(self.env_switch)
304    }
305
306    fn secrets_action(&self) -> FilterAction {
307        if self.secret_patterns.enabled {
308            self.gateway.secrets
309        } else {
310            FilterAction::Off
311        }
312    }
313
314    fn actions(&self) -> detectors::Actions {
315        detectors::Actions {
316            secrets: self.secrets_action(),
317            pii: self.gateway.pii,
318            injection: self.gateway.injection,
319            classification: self.gateway.classification,
320        }
321    }
322
323    fn budget(&self) -> detectors::Budget {
324        detectors::Budget {
325            max_bytes: self.gateway.max_inspected_bytes,
326            deadline: std::time::Duration::from_millis(self.gateway.detector_timeout_ms),
327        }
328    }
329
330    /// Canonical bytes of everything that decides an admission: the gateway
331    /// settings and the secret patterns. Keys the clean memo and is hashed into
332    /// every receipt's policy reference.
333    fn fingerprint(&self) -> Vec<u8> {
334        let mut value = serde_json::json!({
335            "gateway": &self.gateway,
336            "secret_patterns": &self.secret_patterns,
337            // `false` without a detector (bytes unchanged); otherwise the
338            // identity of the runtime this policy's detector is bound to.
339            "semantic": self
340                .semantic
341                .as_ref()
342                .map_or(serde_json::Value::Bool(false), semantic::SemanticDetector::identity),
343        });
344        // Added only in the failure state, so every digest recorded under a
345        // loadable configuration keeps its bytes.
346        if let Some(failure) = self.load_failure
347            && let Some(map) = value.as_object_mut()
348        {
349            map.insert("config_unloadable".to_owned(), failure.code().into());
350        }
351        // The effective switch is an input of every decision, and the
352        // environment can move it without touching a configuration byte
353        // (`LEAN_CTX_CONTEXT_GATEWAY`). It is bound whenever it differs from
354        // the configured value — and only then, so digests taken without an
355        // environment override keep their bytes.
356        let effective = self.enabled_effective();
357        if effective != self.gateway.enabled
358            && let Some(map) = value.as_object_mut()
359        {
360            map.insert("enabled_effective".to_owned(), effective.into());
361        }
362        serde_json::to_vec(&value).unwrap_or_default()
363    }
364
365    /// Governed and sovereign modes treat every enabled detector as mandatory:
366    /// content it could not fully inspect is withheld.
367    fn detectors_mandatory(&self) -> bool {
368        self.gateway.mode != GatewayModeV1::Developer
369    }
370}
371
372/// Content-free counts for the HUD line and the receipt.
373#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
374pub struct AdmissionCounts {
375    pub secrets: u32,
376    pub pii: u32,
377    /// 1 when the object carries prompt-injection signals: an object is
378    /// flagged once, however many of its lines matched.
379    pub injection: u32,
380    /// Which pattern families flagged it
381    /// ([`crate::core::output_sanitizer::InjectionCategory`] bits).
382    pub injection_patterns: u8,
383    pub markings: u32,
384    /// Enabled detectors that did not inspect the whole object.
385    pub incomplete: u32,
386    /// Findings of the optional semantic detectors.
387    pub semantic: u32,
388}
389
390/// The outcome of admitting one object.
391#[derive(Debug, Clone)]
392pub struct Admission {
393    /// `None` when the content is withheld; never the original then.
394    pub text: Option<String>,
395    pub classification: ClassificationV1,
396    pub trust: TrustLevelV1,
397    pub decision: ContextDecisionV1,
398    pub counts: AdmissionCounts,
399}
400
401impl Admission {
402    #[must_use]
403    pub fn disposition(&self) -> ContextDispositionV1 {
404        self.decision.disposition
405    }
406
407    /// Whether the delivered text may enter derived stores (caches, indexes,
408    /// archives). Restricted content never does (owner decision E3).
409    #[must_use]
410    pub fn storable(&self) -> bool {
411        self.text.is_some() && self.classification < ClassificationV1::Restricted
412    }
413
414    /// One stable, content-free line describing what the gateway did, or
415    /// `None` when it changed and flagged nothing.
416    #[must_use]
417    pub fn hud_line(&self) -> Option<String> {
418        self.hud_line_placed(true)
419    }
420
421    /// [`Self::hud_line`] for the model-facing output. With
422    /// `redaction_counts == false` (the host shows lean-ctx out of band),
423    /// counts of masked values are left to the status line: the markers in the
424    /// content already tell the model, the human sees the count elsewhere.
425    /// Detected-but-delivered values, untrusted content and incomplete
426    /// inspection are always stated, because the model must act on them.
427    #[must_use]
428    pub fn hud_line_placed(&self, redaction_counts: bool) -> Option<String> {
429        render_hud(
430            self.counts,
431            &self.decision,
432            self.text.is_none(),
433            redaction_counts,
434        )
435    }
436}
437
438/// The HUD line for `counts` under `decision`; see [`Admission::hud_line_placed`].
439fn render_hud(
440    c: AdmissionCounts,
441    decision: &ContextDecisionV1,
442    withheld: bool,
443    redaction_counts: bool,
444) -> Option<String> {
445    let mut parts = Vec::new();
446    let redacted = decision.disposition == ContextDispositionV1::AllowRedacted;
447    let verb = if redacted { "redacted" } else { "detected" };
448    let show_values = !redacted || redaction_counts;
449    if c.secrets > 0 && show_values {
450        parts.push(format!("{} secret(s) {verb}", c.secrets));
451    }
452    if c.pii > 0 && show_values {
453        parts.push(format!("{} PII value(s) {verb}", c.pii));
454    }
455    if c.injection > 0 {
456        parts.push(format!("{} prompt-injection signal(s)", c.injection));
457    }
458    if c.markings > 0 {
459        parts.push(format!("{} classification marking(s)", c.markings));
460    }
461    let codes = || decision.reason_codes.iter().map(ReasonCodeV1::as_str);
462    if c.incomplete > 0 {
463        let reasons: Vec<&str> = codes()
464            .filter(|code| code.starts_with("coverage.") || code.starts_with("detector."))
465            .collect();
466        parts.push(format!("not fully inspected ({})", reasons.join(", ")));
467    }
468    if c.semantic > 0 {
469        parts.push(format!("{} semantic finding(s)", c.semantic));
470    }
471    let semantic_gaps: Vec<&str> = codes()
472        .filter(|code| {
473            matches!(*code, "semantic.partial" | "semantic.unavailable")
474                || (code.starts_with("semantic.") && code.ends_with(".not_inspected"))
475        })
476        .collect();
477    if !semantic_gaps.is_empty() {
478        parts.push(format!(
479            "semantic check incomplete ({})",
480            semantic_gaps.join(", ")
481        ));
482    }
483    if withheld {
484        let reasons: Vec<&str> = codes().collect();
485        return Some(format!(
486            "[lean-ctx gateway: content withheld — {}]",
487            reasons.join(", ")
488        ));
489    }
490    (!parts.is_empty()).then(|| format!("[lean-ctx gateway: {}]", parts.join(" · ")))
491}
492
493/// Admit `text` (from `path`, when it came from a file) of origin `class`
494/// under `policy`.
495///
496/// Trust is `min(origin_floor(class), content_trust)` (pz21 §1.2). An
497/// external or unknown class is noted in the call's origin ledger first,
498/// before any early return, and its injection action is raised from `Warn`
499/// to `Redact` where the text is delivered or stored for delivery (a
500/// detached store write inside `outside_call` included), never inside an
501/// egress-equality check (`capture::egress_check`, NB-2).
502#[must_use]
503pub fn admit(
504    text: &str,
505    path: Option<&Path>,
506    class: &origin::SourceClass,
507    policy: &AdmissionPolicy,
508) -> Admission {
509    capture::note_origin(class);
510    let floor = class.origin_floor();
511    let object = content_digest(text);
512    let gateway = &policy.gateway;
513    if let Some(codes) = policy.config_refusal_codes() {
514        // The operator's mode and detector actions are unknown. Running the
515        // built-in defaults here would silently turn a governed installation
516        // into a developer one.
517        return Admission {
518            text: None,
519            classification: gateway.mode.unclassified(),
520            trust: TrustLevelV1::Unknown,
521            decision: ContextDecisionV1 {
522                object,
523                disposition: ContextDispositionV1::Deny,
524                reason_codes: codes.iter().map(|code| reason(code)).collect(),
525                signals: Vec::new(),
526                required_transformations: Vec::new(),
527            },
528            counts: AdmissionCounts::default(),
529        };
530    }
531    if !policy.gateway_switch() {
532        // Developer mode skips the detectors, not the origin (N-2): a
533        // project file stays `Internal`, outside text keeps its floor.
534        return Admission {
535            text: Some(text.to_owned()),
536            classification: gateway.mode.unclassified(),
537            trust: floor,
538            decision: ContextDecisionV1 {
539                object,
540                disposition: ContextDispositionV1::Allow,
541                reason_codes: vec![reason("gateway.disabled")],
542                signals: Vec::new(),
543                required_transformations: Vec::new(),
544            },
545            counts: AdmissionCounts::default(),
546        };
547    }
548
549    let mut actions = policy.actions();
550    if class.is_external_or_unknown()
551        && !capture::egress_check_active()
552        && actions.injection == FilterAction::Warn
553    {
554        // Redaction default for untrusted or unknown text (pz21 §1.3 item 2):
555        // only the flagged lines; governed modes may already block.
556        actions.injection = FilterAction::Redact;
557    }
558    let findings = detectors::inspect(
559        text,
560        path,
561        &actions,
562        &policy.secret_patterns,
563        policy.budget(),
564    );
565    let mut counts = findings.counts();
566
567    let mut reasons = Vec::new();
568    let mut disposition = ContextDispositionV1::Allow;
569    // A detector that did not inspect everything never reports "clean": its
570    // reason is always recorded, and mandatory detectors withhold the object.
571    for incomplete in findings.incomplete() {
572        reasons.push(incomplete);
573        if policy.detectors_mandatory() {
574            disposition = ContextDispositionV1::Deny;
575        }
576    }
577    let mut transformations = Vec::new();
578    for (action, hits, code) in [
579        (actions.secrets, counts.secrets, "secret"),
580        (actions.pii, counts.pii, "pii"),
581        (actions.injection, counts.injection, "injection"),
582        (actions.classification, counts.markings, "classification"),
583    ] {
584        if hits == 0 {
585            continue;
586        }
587        let step = match action {
588            FilterAction::Block => {
589                reasons.push(reason(&format!("{code}.blocked")));
590                ContextDispositionV1::Deny
591            }
592            // A marking classifies the whole object; there is no span to mask.
593            FilterAction::Redact if code == "classification" => {
594                reasons.push(reason(&format!("{code}.blocked")));
595                ContextDispositionV1::Deny
596            }
597            FilterAction::Redact => {
598                reasons.push(reason(&format!("{code}.redacted")));
599                if !transformations.contains(&TransformationKindV1::Redaction) {
600                    transformations.push(TransformationKindV1::Redaction);
601                }
602                ContextDispositionV1::AllowRedacted
603            }
604            FilterAction::Warn => {
605                reasons.push(reason(&format!("{code}.flagged")));
606                ContextDispositionV1::Allow
607            }
608            FilterAction::Off => continue,
609        };
610        disposition = disposition.most_restrictive(step);
611    }
612
613    // Optional semantic detectors: advisory, so an incomplete run is reported
614    // but only an actual finding can tighten the decision.
615    let semantic = policy
616        .semantic
617        .as_ref()
618        .map(|detect| semantic::run(text, detect, &actions, gateway.max_inspected_bytes));
619    if let Some(outcome) = &semantic {
620        counts.semantic = outcome.hits;
621        for (step, code) in &outcome.steps {
622            reasons.push(code.clone());
623            if *step == ContextDispositionV1::AllowRedacted
624                && !transformations.contains(&TransformationKindV1::Redaction)
625            {
626                transformations.push(TransformationKindV1::Redaction);
627            }
628            disposition = disposition.most_restrictive(*step);
629        }
630        if let Some(code) = &outcome.incomplete {
631            reasons.push(code.clone());
632        }
633    }
634
635    let mut delivered = if disposition == ContextDispositionV1::Deny {
636        None
637    } else {
638        // Semantic spans refer to the original text, so they are masked first.
639        let semantic_masked = semantic
640            .as_ref()
641            .filter(|outcome| !outcome.redactions.is_empty())
642            .map(|outcome| semantic::redact(text, &outcome.redactions));
643        let source = semantic_masked.as_deref().unwrap_or(text);
644        Some(findings.redact(source, &actions, &policy.secret_patterns))
645    };
646    // Fail closed: a redaction that leaves a detectable secret or PII value
647    // behind must not be delivered as if it were clean. A rewrite is always
648    // re-checked; so is unchanged text after a redacting detector reported a
649    // value, because the redactor then kept what the detector flagged
650    // (GHSA-xmx8-69qv-7f86). Clean, unchanged text needs no second pass.
651    let reported = (actions.secrets == FilterAction::Redact && counts.secrets > 0)
652        || (actions.pii == FilterAction::Redact && counts.pii > 0);
653    if let Some(output) = &delivered
654        && (output != text || reported)
655        && detectors::residual(output, &actions, &policy.secret_patterns)
656    {
657        reasons.push(reason("redaction.incomplete"));
658        disposition = ContextDispositionV1::Deny;
659        delivered = None;
660    }
661
662    let classification = findings.classification(gateway.mode, &actions);
663    let semantic_injection = semantic.as_ref().is_some_and(|outcome| {
664        outcome
665            .steps
666            .iter()
667            // A finding, not the statement that the category was not inspected.
668            .any(|(_, code)| {
669                let code = code.as_str();
670                code.starts_with("semantic.prompt_injection") && !code.ends_with(".not_inspected")
671            })
672    });
673    let content_trust = if counts.injection > 0 || semantic_injection {
674        TrustLevelV1::Untrusted
675    } else {
676        TrustLevelV1::Internal
677    };
678    let trust = floor.min(content_trust);
679    let mut signals: Vec<DetectorSignalV1> = findings.signals();
680    if let Some(outcome) = semantic {
681        signals.push(outcome.signal);
682    }
683    Admission {
684        text: delivered,
685        classification,
686        trust,
687        decision: ContextDecisionV1 {
688            object,
689            disposition,
690            reason_codes: reasons,
691            signals,
692            required_transformations: transformations,
693        },
694        counts,
695    }
696}
697
698/// Capture facts from a shell process. The flags describe raw byte streams,
699/// before decoding or rendering; marker text is never used to infer completeness.
700#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
701pub struct OutputCompleteness {
702    pub truncated: bool,
703    pub timed_out: bool,
704    pub reader_incomplete: bool,
705    pub cancelled: bool,
706    /// Set conservatively when captured bytes required lossy text decoding.
707    /// On Windows the legacy ACP decoder may also be lossy for some code pages.
708    pub decode_lossy: bool,
709}
710
711impl OutputCompleteness {
712    pub const fn complete() -> Self {
713        Self {
714            truncated: false,
715            timed_out: false,
716            reader_incomplete: false,
717            cancelled: false,
718            decode_lossy: false,
719        }
720    }
721
722    pub fn is_complete(self) -> bool {
723        !(self.truncated
724            || self.timed_out
725            || self.reader_incomplete
726            || self.cancelled
727            || self.decode_lossy)
728    }
729
730    fn reason_codes(self) -> Vec<&'static str> {
731        let mut reasons = Vec::new();
732        if self.truncated {
733            reasons.push("coverage.output_truncated");
734        }
735        if self.timed_out {
736            reasons.push("coverage.output_timed_out");
737        }
738        if self.reader_incomplete {
739            reasons.push("coverage.output_reader_incomplete");
740        }
741        if self.cancelled {
742            reasons.push("coverage.output_cancelled");
743        }
744        if self.decode_lossy {
745            reasons.push("coverage.output_decode_lossy");
746        }
747        reasons
748    }
749}
750
751/// Result of inspecting tool output. A missing text means delivery is denied;
752/// rendered then contains only the stable, content-free gateway notice.
753#[derive(Debug, Clone)]
754pub struct ToolOutputAdmission {
755    pub text: Option<String>,
756    pub notice: Option<String>,
757}
758
759impl ToolOutputAdmission {
760    pub fn withheld(&self) -> bool {
761        self.text.is_none()
762    }
763
764    pub fn rendered(&self) -> String {
765        match (&self.text, &self.notice) {
766            (Some(text), Some(notice)) if text.is_empty() => notice.clone(),
767            (Some(text), Some(notice)) => format!("{notice}\n{text}"),
768            (Some(text), None) => text.clone(),
769            (None, Some(notice)) => notice.clone(),
770            (None, None) => "[lean-ctx gateway: content withheld]".to_string(),
771        }
772    }
773}
774
775/// Output of the command the current call classified (`ctx_shell` sets the
776/// class of every command it runs, pz21 §1.8). Without a classified call the
777/// origin is unknown, never assumed to be the project's: a caller that knows
778/// its command or source passes the class to [`admit_tool_output_as`]
779/// (`patterns::output_class`).
780pub fn admit_tool_output(text: &str, completeness: OutputCompleteness) -> ToolOutputAdmission {
781    let class = capture::current()
782        .and_then(|capture| capture.output_class())
783        .unwrap_or(origin::SourceClass::Unclassified {
784            tool: "tool_output",
785        });
786    admit_tool_output_as(text, completeness, &class)
787}
788
789/// [`admit_tool_output`] for output of origin `class`.
790pub fn admit_tool_output_as(
791    text: &str,
792    completeness: OutputCompleteness,
793    class: &origin::SourceClass,
794) -> ToolOutputAdmission {
795    capture::note_origin(class);
796    // Check active project policy against the original bytes before Gateway
797    // redaction can hide a phrase that policy must block.
798    let project_original = crate::core::policy::content::protect_active(text);
799    let project_rewrote = project_original
800        .as_ref()
801        .is_ok_and(|admitted| admitted.as_ref() != text);
802    let policy = carrier::current_policy();
803    let mut admission = admit(text, None, class, &policy);
804    mark_capture_incomplete(&mut admission, completeness, &policy);
805
806    let gateway_output = admission.text.clone();
807    let text = project_original
808        .as_deref()
809        .ok()
810        .zip(gateway_output.as_deref())
811        .and_then(|(project_original, gateway_output)| {
812            compose_active_gateway_output(
813                project_original,
814                gateway_output,
815                class,
816                &policy,
817                completeness,
818            )
819        });
820    let policy_withheld = project_original.is_err() || (gateway_output.is_some() && text.is_none());
821    if let Some(admitted) = &text {
822        admission.text = Some(admitted.clone());
823        if project_rewrote
824            || gateway_output
825                .as_deref()
826                .is_some_and(|gateway| gateway != admitted)
827        {
828            mark_project_redaction(&mut admission);
829        }
830    } else if policy_withheld {
831        mark_policy_withheld(&mut admission, "policy.content_withheld");
832    }
833
834    let capture = capture::current();
835    if let Some(capture) = &capture {
836        capture.bind_policy(
837            policy.gateway.mode,
838            fingerprint_digest(&policy.fingerprint()),
839        );
840        capture.record_as(
841            &admission.decision,
842            admission.counts,
843            class.is_external_or_unknown(),
844        );
845    }
846    let mut notice = admission.hud_line_placed(policy.gateway.hud.redaction_counts_in_band());
847    if policy_withheld {
848        notice.get_or_insert_with(|| "[lean-ctx policy: content withheld]".to_string());
849    }
850    ToolOutputAdmission { text, notice }
851}
852
853fn mark_project_redaction(admission: &mut Admission) {
854    admission.decision.disposition = admission
855        .decision
856        .disposition
857        .most_restrictive(ContextDispositionV1::AllowRedacted);
858    let reason = reason("policy.content_redacted");
859    if !admission.decision.reason_codes.contains(&reason) {
860        admission.decision.reason_codes.push(reason);
861    }
862    if !admission
863        .decision
864        .required_transformations
865        .contains(&TransformationKindV1::Redaction)
866    {
867        admission
868            .decision
869            .required_transformations
870            .push(TransformationKindV1::Redaction);
871    }
872}
873
874fn mark_policy_withheld(admission: &mut Admission, reason_code: &str) {
875    admission.text = None;
876    admission.decision.disposition = ContextDispositionV1::Deny;
877    let reason = reason(reason_code);
878    if !admission.decision.reason_codes.contains(&reason) {
879        admission.decision.reason_codes.push(reason);
880    }
881}
882
883/// Compose the project-policy and Gateway transformations without losing either
884/// detector's view of the original input. If their order changes the result,
885/// withholding is safer than publishing text whose provenance is ambiguous.
886pub(crate) fn compose_active_gateway_output(
887    project_original: &str,
888    gateway_output: &str,
889    class: &origin::SourceClass,
890    policy: &AdmissionPolicy,
891    completeness: OutputCompleteness,
892) -> Option<String> {
893    let project_after_gateway = crate::core::policy::content::protect_active(gateway_output)
894        .ok()?
895        .into_owned();
896    let mut gateway_after_project = admit(project_original, None, class, policy);
897    mark_capture_incomplete(&mut gateway_after_project, completeness, policy);
898    let gateway_after_project = gateway_after_project.text?;
899    (project_after_gateway == gateway_after_project).then_some(project_after_gateway)
900}
901
902pub(super) fn admit_output_for_storage(
903    text: &str,
904    completeness: OutputCompleteness,
905    policy: &AdmissionPolicy,
906) -> Option<String> {
907    // Incomplete process output is never cached or retained for later polls,
908    // even in Developer mode where the originating call may see a warning.
909    if !completeness.is_complete() {
910        return None;
911    }
912    let project_original = crate::core::policy::content::protect_active(text).ok()?;
913    let mut admission = admit(text, None, &origin::SourceClass::Project, policy);
914    mark_capture_incomplete(&mut admission, completeness, policy);
915    if !admission.storable() {
916        return None;
917    }
918    let gateway_output = admission.text?;
919    compose_active_gateway_output(
920        project_original.as_ref(),
921        &gateway_output,
922        &origin::SourceClass::Project,
923        policy,
924        completeness,
925    )
926}
927
928/// A finished background job's output, kept until a status poll delivers it
929/// (#2164). Only a held pipe (a process the command left running) is
930/// tolerated; deliveries still pass `admit_tool_output` with the real flags,
931/// and truncated, timed-out, cancelled or lossy captures stay unretained.
932pub(super) fn admit_output_for_poll(
933    text: &str,
934    completeness: OutputCompleteness,
935    policy: &AdmissionPolicy,
936) -> Option<String> {
937    let without_reader = OutputCompleteness {
938        reader_incomplete: false,
939        ..completeness
940    };
941    if !completeness.reader_incomplete {
942        return admit_output_for_storage(text, completeness, policy);
943    }
944    if !without_reader.is_complete() || (policy.enabled_effective() && policy.detectors_mandatory())
945    {
946        return None;
947    }
948    admit_output_for_storage(text, without_reader, policy)
949}
950
951fn mark_capture_incomplete(
952    admission: &mut Admission,
953    completeness: OutputCompleteness,
954    policy: &AdmissionPolicy,
955) {
956    if completeness.is_complete() || !policy.enabled_effective() {
957        return;
958    }
959    for code in completeness.reason_codes() {
960        let reason = reason(code);
961        if !admission.decision.reason_codes.contains(&reason) {
962            admission.decision.reason_codes.push(reason);
963        }
964    }
965    let partial_reason = reason("coverage.output_partial");
966    if !admission.decision.reason_codes.contains(&partial_reason) {
967        admission.decision.reason_codes.push(partial_reason.clone());
968    }
969    for signal in &mut admission.decision.signals {
970        if signal.coverage.kind != CoverageKindV1::Complete {
971            continue;
972        }
973        // The process capture knows only the prefix length. One unknown byte is
974        // the protocol-valid lower bound for the omitted tail; it is not a claim
975        // that the command emitted exactly one additional byte.
976        signal.coverage.kind = CoverageKindV1::Partial;
977        signal.coverage.bytes_total = signal.coverage.bytes_inspected.saturating_add(1);
978        signal.coverage.chunks_total = signal.coverage.chunks_inspected.saturating_add(1);
979        signal.coverage.reason = Some(partial_reason.clone());
980    }
981    admission.counts.incomplete = admission.counts.incomplete.max(1);
982    if policy.detectors_mandatory() {
983        admission.decision.disposition = ContextDispositionV1::Deny;
984        admission.text = None;
985    }
986}
987
988/// Source text admitted for delivery, with the original classification's
989/// persistence decision preserved for downstream caches and indexes.
990#[derive(Debug, Clone, PartialEq, Eq)]
991pub struct SourceAdmission {
992    pub text: String,
993    pub storable: bool,
994    /// Classification assigned by the original Gateway inspection.
995    pub(crate) classification: ClassificationV1,
996}
997
998/// Admit a source the agent is about to read, at the read choke point.
999///
1000/// Returns the admitted text, or a content-free `PermissionDenied` naming the
1001/// reason codes. With `preserve_bytes` (signed snapshots) any rewrite is
1002/// refused instead of silently changing a digest-bound source.
1003pub fn admit_source(
1004    text: &str,
1005    path: &str,
1006    preserve_bytes: bool,
1007    class: &origin::SourceClass,
1008) -> Result<String, std::io::Error> {
1009    admit_source_with_storage(
1010        text,
1011        path,
1012        preserve_bytes,
1013        OutputCompleteness::complete(),
1014        class,
1015    )
1016    .map(|admission| admission.text)
1017}
1018
1019/// [`admit_source`] for text the Instance assembled itself (protocol text,
1020/// its own knowledge store): origin Project (pz21 §1.4).
1021pub fn admit_instance_source(
1022    text: &str,
1023    label: &str,
1024    preserve_bytes: bool,
1025) -> Result<String, std::io::Error> {
1026    admit_source(text, label, preserve_bytes, &origin::SourceClass::Project)
1027}
1028
1029/// [`admit_context_source`] for text the Instance assembled from its own
1030/// project and records (a checkout diff, receipts, an engine source):
1031/// origin Project (pz21 §1.4).
1032pub fn admit_instance_context_source(text: &str) -> Result<SourceAdmission, std::io::Error> {
1033    admit_context_source(text, &origin::SourceClass::Project)
1034}
1035
1036/// [`admit_source_with_storage`] for a rooted read of a project file (the
1037/// rooted reader and the read cache it fills): origin Project (pz21 §1.4).
1038pub(crate) fn admit_project_file_with_storage(
1039    text: &str,
1040    path: &str,
1041    preserve_bytes: bool,
1042    completeness: OutputCompleteness,
1043) -> Result<SourceAdmission, std::io::Error> {
1044    admit_source_with_storage(
1045        text,
1046        path,
1047        preserve_bytes,
1048        completeness,
1049        &origin::SourceClass::Project,
1050    )
1051}
1052
1053/// Admit a source and preserve whether its original Gateway classification may
1054/// enter derived stores. Incomplete reads never seed the clean memo or stores.
1055pub(crate) fn admit_source_with_storage(
1056    text: &str,
1057    path: &str,
1058    preserve_bytes: bool,
1059    completeness: OutputCompleteness,
1060    class: &origin::SourceClass,
1061) -> Result<SourceAdmission, std::io::Error> {
1062    admit_source_inner(text, Some(path), preserve_bytes, completeness, None, class)
1063}
1064
1065/// Admit an in-memory source of origin `class` without assigning it a
1066/// synthetic filesystem path.
1067pub fn admit_context_source(
1068    text: &str,
1069    class: &origin::SourceClass,
1070) -> Result<SourceAdmission, std::io::Error> {
1071    admit_source_inner(
1072        text,
1073        None,
1074        false,
1075        OutputCompleteness::complete(),
1076        None,
1077        class,
1078    )
1079}
1080
1081/// [`admit_context_source`] for text that is bound by a digest or signature
1082/// and therefore cannot be delivered rewritten: a mask is a refusal, and it
1083/// is recorded as one (never as an admitted redaction of a copy that did not
1084/// leave).
1085pub(crate) fn admit_bound_context_source(
1086    text: &str,
1087    class: &origin::SourceClass,
1088) -> Result<SourceAdmission, std::io::Error> {
1089    admit_source_inner(
1090        text,
1091        None,
1092        true,
1093        OutputCompleteness::complete(),
1094        None,
1095        class,
1096    )
1097}
1098
1099/// Admit a rooted source with one caller-captured Gateway snapshot. Hosted
1100/// generation builders use this so a multi-file build cannot mix policies if
1101/// global configuration changes during the scan; publication must reauthorize
1102/// the same snapshot afterward.
1103pub(crate) fn admit_source_with_snapshot(
1104    text: &str,
1105    path: &str,
1106    preserve_bytes: bool,
1107    completeness: OutputCompleteness,
1108    snapshot: &stores::StoreAdmission,
1109) -> Result<SourceAdmission, std::io::Error> {
1110    admit_source_inner(
1111        text,
1112        Some(path),
1113        preserve_bytes,
1114        completeness,
1115        Some(snapshot.admission_policy()),
1116        &origin::SourceClass::Project,
1117    )
1118}
1119
1120fn admit_source_inner(
1121    text: &str,
1122    path: Option<&str>,
1123    preserve_bytes: bool,
1124    completeness: OutputCompleteness,
1125    policy_snapshot: Option<&AdmissionPolicy>,
1126    class: &origin::SourceClass,
1127) -> Result<SourceAdmission, std::io::Error> {
1128    capture::note_origin(class);
1129    admit_source_typed(
1130        text,
1131        path,
1132        preserve_bytes,
1133        completeness,
1134        policy_snapshot,
1135        class,
1136    )
1137    .map_err(|reasons| {
1138        let hint = withheld_remedy(&reasons);
1139        let reasons: Vec<&str> = reasons.iter().map(ReasonCodeV1::as_str).collect();
1140        std::io::Error::new(
1141            std::io::ErrorKind::PermissionDenied,
1142            format!(
1143                "source content withheld by the context gateway ({}){hint}",
1144                reasons.join(", ")
1145            ),
1146        )
1147    })
1148}
1149
1150/// The setting behind a withheld read, so the user can tell an intended policy
1151/// from a misconfiguration (814 refusals in 30 days carried only the code —
1152/// focus analysis 2026-10-15). Fixed text: never content, never a path.
1153fn withheld_remedy(reasons: &[ReasonCodeV1]) -> &'static str {
1154    let has = |code: &str| reasons.iter().any(|reason| reason.as_str() == code);
1155    if has("gateway.config_unloadable") {
1156        " — the global config.toml could not be loaded; fix it (lean-ctx doctor) to restore reads"
1157    } else if has("coverage.partial") || has("coverage.budget_exhausted") {
1158        " — the object exceeds [context_gateway] max_inspected_bytes and governed/sovereign mode \
1159         withholds what detectors cannot fully inspect"
1160    } else if has("detector.timed_out") {
1161        " — a detector exceeded [context_gateway] detector_timeout_ms in governed/sovereign mode"
1162    } else if has("classification.blocked") {
1163        " — a classification marking matched [context_gateway] classification = redact|block"
1164    } else if has("secret.blocked") {
1165        " — a secret matched [context_gateway] secrets = \"block\""
1166    } else if has("injection.blocked") {
1167        " — prompt-injection text matched [context_gateway] injection = \"block\""
1168    } else if has("redaction.incomplete") {
1169        " — a redaction left a detectable value behind, so nothing is delivered"
1170    } else if has("policy.content_withheld") {
1171        " — withheld by the project or organization policy"
1172    } else {
1173        ""
1174    }
1175}
1176
1177/// [`admit_source_inner`] with the refusal as typed reason codes, for carriers
1178/// that render their own content-free message (see `carrier`).
1179fn admit_source_typed(
1180    text: &str,
1181    path: Option<&str>,
1182    preserve_bytes: bool,
1183    completeness: OutputCompleteness,
1184    policy_snapshot: Option<&AdmissionPolicy>,
1185    class: &origin::SourceClass,
1186) -> Result<SourceAdmission, Vec<ReasonCodeV1>> {
1187    let external = class.is_external_or_unknown();
1188    // Inspect original content before a Gateway redaction or clean memo can
1189    // remove a signal required by the active project policy.
1190    let project_original = crate::core::policy::content::protect_active(text);
1191    let project_rewrote = project_original
1192        .as_ref()
1193        .is_ok_and(|admitted| admitted.as_ref() != text);
1194    let policy = policy_snapshot
1195        .cloned()
1196        .unwrap_or_else(carrier::current_policy);
1197    let fingerprint = policy.fingerprint();
1198    let capture = capture::current();
1199    if let Some(capture) = &capture {
1200        capture.bind_policy(policy.gateway.mode, fingerprint_digest(&fingerprint));
1201    }
1202    // Clean memo: only complete reads and built-in detectors are pure functions
1203    // of the input. Partial or lossy reads must be inspected with their flags.
1204    let memo_key = path.and_then(|path| {
1205        (completeness.is_complete()
1206            && project_original.is_ok()
1207            && !project_rewrote
1208            && policy.semantic.is_none()
1209            && !policy.config_unloadable()
1210            && policy.gateway_switch())
1211        .then(|| clean::key(&fingerprint, path, text))
1212    });
1213    if let Some(key) = &memo_key
1214        && let Some(decision) = clean::get_source(key)
1215    {
1216        if let Some(capture) = &capture {
1217            capture.record_as(&decision.decision, AdmissionCounts::default(), external);
1218        }
1219        return Ok(SourceAdmission {
1220            text: project_original
1221                .expect("memo key requires accepted project policy")
1222                .into_owned(),
1223            storable: decision.storable,
1224            classification: decision.classification,
1225        });
1226    }
1227
1228    let mut admission = admit(text, path.map(Path::new), class, &policy);
1229    mark_capture_incomplete(&mut admission, completeness, &policy);
1230    let storable = completeness.is_complete() && admission.storable();
1231    let gateway_admitted = admission.text.clone();
1232    let mut project_admitted = project_original
1233        .as_deref()
1234        .ok()
1235        .zip(gateway_admitted.as_deref())
1236        .and_then(|(project_original, gateway_admitted)| {
1237            compose_active_gateway_output(
1238                project_original,
1239                gateway_admitted,
1240                class,
1241                &policy,
1242                completeness,
1243            )
1244        });
1245    let mut refusal_reason = if project_original.is_err()
1246        || (gateway_admitted.is_some() && project_admitted.is_none())
1247    {
1248        Some("policy.content_withheld")
1249    } else {
1250        None
1251    };
1252
1253    if let Some(admitted) = &project_admitted {
1254        if project_rewrote
1255            || gateway_admitted
1256                .as_deref()
1257                .is_some_and(|gateway| gateway != admitted)
1258        {
1259            admission.text = Some(admitted.clone());
1260            mark_project_redaction(&mut admission);
1261        }
1262    }
1263    if preserve_bytes
1264        && let Some(gateway_admitted) = gateway_admitted.as_deref()
1265        && let Some(project_admitted_text) = project_admitted.as_deref()
1266        && preserve_bytes_rewrite_reason(
1267            text,
1268            gateway_admitted,
1269            project_admitted_text,
1270            project_rewrote,
1271        )
1272        .is_some()
1273    {
1274        project_admitted = None;
1275        refusal_reason = Some("source.bytes_not_preserved");
1276    }
1277    if let Some(reason_code) = refusal_reason {
1278        mark_policy_withheld(&mut admission, reason_code);
1279    }
1280    if let Some(capture) = &capture {
1281        capture.record_as(&admission.decision, admission.counts, external);
1282    }
1283
1284    let Some(project_admitted) = project_admitted else {
1285        return Err(admission.decision.reason_codes);
1286    };
1287
1288    if let Some(key) = memo_key
1289        && admission.disposition() == ContextDispositionV1::Allow
1290        && admission.decision.reason_codes.is_empty()
1291        && admission.text.as_deref() == Some(text)
1292        && project_admitted == text
1293    {
1294        clean::insert_source(
1295            key,
1296            admission.decision.clone(),
1297            admission.classification,
1298            admission.storable(),
1299        );
1300    }
1301    let redaction_counts = policy.gateway.hud.redaction_counts_in_band();
1302    if admission.hud_line_placed(redaction_counts).is_some() {
1303        notes::record(
1304            project_admitted.as_ref(),
1305            notes::Note {
1306                counts: admission.counts,
1307                decision: admission.decision.clone(),
1308                redaction_counts,
1309            },
1310        );
1311    }
1312    Ok(SourceAdmission {
1313        text: project_admitted,
1314        storable,
1315        classification: admission.classification,
1316    })
1317}
1318
1319fn preserve_bytes_rewrite_reason(
1320    source: &str,
1321    gateway_admitted: &str,
1322    project_admitted: &str,
1323    project_rewrote_original: bool,
1324) -> Option<&'static str> {
1325    if project_rewrote_original || project_admitted != gateway_admitted {
1326        Some("source content withheld: an active policy would rewrite a digest-bound source")
1327    } else if gateway_admitted != source {
1328        Some("source content withheld: the context gateway would rewrite a digest-bound source")
1329    } else {
1330        None
1331    }
1332}
1333
1334/// Admit an object no built-in detector can read (an image). Every enabled
1335/// detector reports `unsupported`; developer mode delivers it with a note,
1336/// governed and sovereign modes withhold it.
1337#[must_use]
1338pub fn admit_uninspectable(path: Option<&Path>, bytes: u64, policy: &AdmissionPolicy) -> Admission {
1339    let gateway = &policy.gateway;
1340    let object = content_digest(&format!("uninspectable:{bytes}"));
1341    let actions = policy.actions();
1342    let signals = detectors::unsupported_signals(&actions, bytes);
1343    let required = signals.iter().any(|signal| {
1344        signal.coverage.kind == lean_ctx_protocol::context_gateway::CoverageKindV1::Unsupported
1345    });
1346    if policy.config_unloadable() || !policy.gateway_switch() || !required {
1347        return admit("", path, &origin::SourceClass::Project, policy);
1348    }
1349    let restricted_path =
1350        path.is_some_and(|p| crate::core::io_boundary::is_secret_like(p).is_some());
1351    let mandatory = policy.detectors_mandatory();
1352    Admission {
1353        text: (!mandatory).then(String::new),
1354        classification: if restricted_path {
1355            ClassificationV1::Restricted
1356        } else {
1357            gateway.mode.unclassified()
1358        },
1359        trust: TrustLevelV1::Unknown,
1360        decision: ContextDecisionV1 {
1361            object,
1362            disposition: if mandatory {
1363                ContextDispositionV1::Deny
1364            } else {
1365                ContextDispositionV1::Allow
1366            },
1367            reason_codes: vec![reason("coverage.unsupported_media")],
1368            signals,
1369            required_transformations: Vec::new(),
1370        },
1371        counts: AdmissionCounts {
1372            incomplete: 1,
1373            ..AdmissionCounts::default()
1374        },
1375    }
1376}
1377
1378/// Media gate for the read path: `Ok(note)` to deliver with a visible note,
1379/// or a content-free `PermissionDenied` when the media must be withheld.
1380pub fn admit_media(path: &str, bytes: u64) -> Result<Option<String>, std::io::Error> {
1381    let policy = carrier::current_policy();
1382    let admission = admit_uninspectable(Some(Path::new(path)), bytes, &policy);
1383    if let Some(capture) = capture::current() {
1384        capture.bind_policy(
1385            policy.gateway.mode,
1386            fingerprint_digest(&policy.fingerprint()),
1387        );
1388        capture.record(&admission.decision, admission.counts);
1389    }
1390    if admission.text.is_none() {
1391        return Err(std::io::Error::new(
1392            std::io::ErrorKind::PermissionDenied,
1393            "media withheld by the context gateway (coverage.unsupported_media)",
1394        ));
1395    }
1396    Ok((admission.counts.incomplete > 0)
1397        .then(|| "[lean-ctx gateway: media not inspected (coverage.unsupported_media)]".to_owned()))
1398}
1399
1400/// Forget every memoized clean admission (measurements of cold reads).
1401#[cfg(any(test, feature = "test-support"))]
1402pub fn clear_clean_memo() {
1403    clean::clear();
1404}
1405
1406/// The HUD line recorded when exactly `admitted` was produced, stated for
1407/// `delivered`: the part of `admitted` a tool actually returns (a line
1408/// window, a compressed view). Masked values are counted from the markers
1409/// `delivered` carries, never above the object's own counts, so a window
1410/// without a masked value gets no redaction count — and no line when nothing
1411/// else applies (#2135). Every other part of the note describes the object.
1412#[must_use]
1413pub fn note_for(admitted: &str, delivered: &str) -> Option<String> {
1414    let note = notes::lookup(admitted)?;
1415    let mut counts = note.counts;
1416    if note.decision.disposition == ContextDispositionV1::AllowRedacted {
1417        let pii = crate::core::input_filters::pii::checksummed_marker_count(delivered);
1418        let other = delivered
1419            .matches("[REDACTED:")
1420            .count()
1421            .saturating_sub(pii + delivered.matches(INJECTION_MARKER).count());
1422        counts.pii = counts.pii.min(saturating_u32(pii));
1423        counts.secrets = counts.secrets.min(saturating_u32(other));
1424    }
1425    render_hud(counts, &note.decision, false, note.redaction_counts)
1426}
1427
1428const INJECTION_MARKER: &str = "[REDACTED:prompt-injection]";
1429
1430fn saturating_u32(n: usize) -> u32 {
1431    u32::try_from(n).unwrap_or(u32::MAX)
1432}
1433
1434fn reason(code: &str) -> ReasonCodeV1 {
1435    ReasonCodeV1::new(code).expect("built-in reason codes are valid")
1436}
1437
1438/// Record in the running call's receipt that a derived copy admitted before
1439/// (at its cache fill) was asked of its source again at this serve and
1440/// refused: the after side of the revocation boundary (C04). The decision is
1441/// a denial whose reason is the source state (`source.revoked`, …); its
1442/// object is one fixed digest for every such refusal, so the receipt names
1443/// neither the item nor its text and reads the same for every item withheld
1444/// this way (K02/S02). No capture: nothing is recorded.
1445pub(crate) fn record_recheck_refusal(
1446    admission: &stores::StoreAdmission,
1447    validity: lean_ctx_protocol::context_lineage::SourceValidityV1,
1448) {
1449    let Some(capture) = capture::current() else {
1450        return;
1451    };
1452    let policy = admission.admission_policy();
1453    capture.bind_policy(
1454        policy.gateway.mode,
1455        fingerprint_digest(&policy.fingerprint()),
1456    );
1457    let decision = ContextDecisionV1 {
1458        object: fingerprint_digest(b"source-recheck-refused"),
1459        disposition: ContextDispositionV1::Deny,
1460        reason_codes: vec![reason(validity.reason_code())],
1461        signals: Vec::new(),
1462        required_transformations: Vec::new(),
1463    };
1464    capture.record(&decision, AdmissionCounts::default());
1465}
1466
1467/// SHA-256 of the canonical policy fingerprint: the receipt's policy digest.
1468fn fingerprint_digest(fingerprint: &[u8]) -> Sha256Digest {
1469    let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(fingerprint));
1470    Sha256Digest::new(format!("sha256:{digest}")).expect("SHA-256 digest is canonical")
1471}
1472
1473fn content_digest(text: &str) -> Sha256Digest {
1474    let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(text.as_bytes()));
1475    Sha256Digest::new(format!("sha256:{digest}")).expect("SHA-256 digest is canonical")
1476}
1477
1478#[cfg(test)]
1479mod shell_admission_regression_tests;
1480
1481#[cfg(test)]
1482mod tests;
1483
1484#[cfg(test)]
1485mod operand_tests;
1486
1487#[cfg(test)]
1488mod receipt_tests;
1489
1490#[cfg(test)]
1491mod store_tests;
1492
1493#[cfg(test)]
1494mod egress_tests;
1495
1496#[cfg(test)]
1497mod egress_api_tests;