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