Skip to main content

lean_ctx/core/policy/
runtime.rs

1//! Runtime view of the active context policy pack (GL #673 / #489 enforcement).
2//!
3//! [`active`] refreshes bounded policy and organization trust bytes on every
4//! admission. Identical snapshots reuse prepared rules; changed or unreadable
5//! inputs never reuse a stale authorization. One bounded worker serializes file
6//! resolution and compilation without accumulating timed-out reader threads.
7//!
8//! **Opt-in & backward-compatible:** with no project pack present, [`active`]
9//! returns `None` and nothing is gated — existing behavior is preserved
10//! exactly. An invalid local pack activates a deny-all policy so enforcement
11//! never fails open.
12//!
13//! **Local-Free Invariant:** enforcement derived from this view only ever
14//! constrains the *agent* pipeline; it never gates a human's own local reads.
15
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, Ordering};
19#[cfg(test)]
20use std::sync::{OnceLock, RwLock};
21
22use regex::Regex;
23
24use super::ResolvedPolicy;
25#[cfg(test)]
26use super::{parse_file, resolve};
27use crate::core::input_filters::{FilterAction, FilterConfig};
28
29mod refresh;
30/// Process-scoped pin set by explicit protected launchers; absent in Community.
31pub(crate) const REQUIRED_POLICY_ROOT_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_ROOT";
32pub(crate) const REQUIRED_POLICY_DIGEST_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_DIGEST";
33pub(crate) use refresh::{protected_authority_paths, protected_policy_digest};
34#[cfg(test)]
35mod held_horizon_tests;
36#[cfg(test)]
37mod refresh_tests;
38
39tokio::task_local! {
40    /// Per-request project authority; never mutate process CWD for MCP roots.
41    pub(crate) static REQUEST_PROJECT: std::cell::RefCell<Option<PathBuf>>;
42    /// Immutable policy view for one synchronous source-admission operation.
43    pub(crate) static SOURCE_VIEW: std::cell::RefCell<Option<SourceView>>;
44}
45
46#[derive(Clone)]
47pub(crate) struct SourceView {
48    project: PathBuf,
49    policy: Option<Arc<ActivePolicy>>,
50    fingerprint: blake3::Hash,
51    role: crate::core::roles::Role,
52    role_fingerprint: blake3::Hash,
53    /// Set when the pinned policy rests on a verifier's decision.
54    ///
55    /// Two different bounds, deliberately: the request deadline bounded the
56    /// decision itself — asking, recording, handing out — and ended with the
57    /// refresh that produced this view. The operation running on the view is
58    /// bounded by the signed horizon instead, checked on a fresh clock at
59    /// every use of the held policy, at every nested admission and last,
60    /// after all closing waits, before anything is published. A lifted
61    /// requirement has no horizon: it is durable marker state, and the view
62    /// stays bound to it through the fingerprint.
63    lifetime: Option<super::org::Lifetime>,
64    /// What the verifier's answer stated, from the same verification the
65    /// pinned policy rests on. Never read again for this view.
66    observation: Option<super::org::Observation>,
67    valid: Arc<AtomicBool>,
68    live: Arc<AtomicBool>,
69}
70
71impl SourceView {
72    /// Whether the signed horizon still holds; a view past it is invalid for
73    /// good, like one whose authority changed.
74    fn within_horizon(&self) -> bool {
75        let holds = self
76            .lifetime
77            .is_none_or(|lifetime| lifetime.check_horizon().is_ok());
78        if !holds {
79            self.valid.store(false, Ordering::Release);
80        }
81        holds
82    }
83
84    /// Invalidate the view for its owner — but only while it is still live.
85    /// A straggler that merely finds the view ended (a timed-out worker whose
86    /// result its caller already discarded) must not poison the owner's
87    /// closing check: that turned complete, unchanged `ctx_compose` results
88    /// into "source authority changed" refusals (~3 % of calls, focus
89    /// analysis 2026-10-15). Inconsistencies seen during the view's life
90    /// still invalidate it.
91    fn invalidate_if_live(&self) {
92        if self.live.load(Ordering::Acquire) {
93            self.valid.store(false, Ordering::Release);
94        }
95    }
96}
97
98struct SourceViewLifetime(Arc<AtomicBool>);
99
100/// Revalidate buffered CLI data at its output and persistence boundaries.
101/// This does not lock policy files against a concurrent administrator write.
102#[derive(Debug)]
103pub(crate) struct PublicationAuthority {
104    project: PathBuf,
105    fingerprint: blake3::Hash,
106    role_fingerprint: blake3::Hash,
107    /// The horizon of the view the buffered data was produced under.
108    lifetime: Option<super::org::Lifetime>,
109    valid: Arc<AtomicBool>,
110}
111
112impl PublicationAuthority {
113    pub(crate) fn capture() -> Result<Self, String> {
114        let view = current_source_view().ok_or("source authority unavailable")?;
115        if !view.within_horizon() {
116            return Err("source authority unavailable".into());
117        }
118        Ok(Self {
119            project: view.project,
120            fingerprint: view.fingerprint,
121            role_fingerprint: view.role_fingerprint,
122            lifetime: view.lifetime,
123            valid: view.valid,
124        })
125    }
126
127    pub(crate) fn verify(&self) -> Result<(), String> {
128        if !self.valid.load(Ordering::Acquire)
129            || REQUEST_PROJECT
130                .try_with(|slot| {
131                    slot.borrow()
132                        .as_ref()
133                        .is_some_and(|root| root != &self.project)
134                })
135                .unwrap_or(false)
136        {
137            return Err("source authority changed before publication".into());
138        }
139        REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(self.project.clone())), || {
140            SOURCE_VIEW.sync_scope(std::cell::RefCell::new(None), || {
141                let latest = refresh::current_verified(self.project.clone())?;
142                let role = role_fingerprint(&crate::core::roles::active_role())?;
143                if latest.fingerprint != self.fingerprint || role != self.role_fingerprint {
144                    return Err("source authority changed before publication".into());
145                }
146                // Last, after the waits above: the buffered data was made
147                // under a floor signed up to a horizon, and is not published
148                // past it even though the authority verifies afresh.
149                if let Some(lifetime) = &self.lifetime {
150                    lifetime.check_horizon()?;
151                }
152                Ok(())
153            })
154        })
155    }
156
157    /// Fingerprint used to bind derived decisions to this exact project and
158    /// policy snapshot without exposing any policy contents.
159    pub(crate) fn fingerprint_bytes(&self) -> [u8; 32] {
160        *self.fingerprint.as_bytes()
161    }
162
163    /// Role authorization is a separate part of source authority and must be
164    /// bound independently into persisted provenance metadata.
165    #[cfg(any(test, feature = "http-server"))]
166    pub(crate) fn role_fingerprint_bytes(&self) -> [u8; 32] {
167        *self.role_fingerprint.as_bytes()
168    }
169}
170
171impl Drop for SourceViewLifetime {
172    fn drop(&mut self) {
173        self.0.store(false, Ordering::Release);
174    }
175}
176
177fn current_source_view() -> Option<SourceView> {
178    SOURCE_VIEW
179        .try_with(|slot| slot.borrow().clone())
180        .ok()
181        .flatten()
182}
183
184/// Capture the pinned view when propagating a synchronous worker scope.
185pub(crate) fn inherited_source_view() -> Option<SourceView> {
186    current_source_view()
187}
188
189/// Resolve the project root for a detached worker without retaining request-
190/// lifetime policy or capture state. The worker must reopen a fresh source view
191/// from this root when it stores output.
192pub(crate) fn detached_project_root(fallback: &Path) -> Result<PathBuf, String> {
193    let request_project = REQUEST_PROJECT
194        .try_with(|slot| slot.borrow().clone())
195        .ok()
196        .flatten();
197    if let Some(view) = current_source_view() {
198        if !view.live.load(Ordering::Acquire)
199            || !view.valid.load(Ordering::Acquire)
200            || request_project.as_ref() != Some(&view.project)
201        {
202            view.invalidate_if_live();
203            return Err("source policy view is no longer active".into());
204        }
205        return Ok(view.project);
206    }
207    Ok(request_project.unwrap_or_else(|| fallback.to_path_buf()))
208}
209
210/// Restore a previously captured source view in a detached worker.
211pub(crate) fn with_inherited_source_view<T>(
212    view: Option<SourceView>,
213    operation: impl FnOnce() -> T,
214) -> T {
215    match view {
216        Some(view) => SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation),
217        None => operation(),
218    }
219}
220
221/// The role paired with the active source view. A closed or rebound inherited
222/// view returns a deny-all role instead of exposing its stale privileges.
223pub(crate) fn pinned_role() -> Option<crate::core::roles::Role> {
224    current_source_view().map(|view| {
225        let project = REQUEST_PROJECT
226            .try_with(|slot| slot.borrow().clone())
227            .ok()
228            .flatten();
229        if !view.live.load(Ordering::Acquire)
230            || !view.valid.load(Ordering::Acquire)
231            || project.as_ref() != Some(&view.project)
232        {
233            view.invalidate_if_live();
234            crate::core::roles::closed_source_view_role()
235        } else {
236            view.role
237        }
238    })
239}
240
241/// Run `operation` as part of a request for `project`.
242pub(crate) fn in_project<T>(project: impl Into<PathBuf>, operation: impl FnOnce() -> T) -> T {
243    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.into())), operation)
244}
245
246/// Start `operation` on its own thread as part of a request for `project`.
247/// A spawned thread inherits no task-local: without this it reads the
248/// configuration and admission state of the process's own project (AP04-G3).
249pub(crate) fn spawn_for_project<T: Send + 'static>(
250    project: impl Into<PathBuf>,
251    operation: impl FnOnce() -> T + Send + 'static,
252) -> std::thread::JoinHandle<T> {
253    let project = project.into();
254    std::thread::spawn(move || in_project(project, operation))
255}
256
257pub(crate) fn bind_request_project(project: Option<&str>) {
258    if current_source_view().is_some() {
259        return;
260    }
261    let _ = REQUEST_PROJECT.try_with(|slot| {
262        *slot.borrow_mut() = project.map(PathBuf::from);
263    });
264}
265
266/// The one spelling of a request project: resolved, and on Windows without
267/// the verbatim `\\?\` prefix (`pathutil::canonicalize_secure`), as the proxy
268/// (`request_project`) and the policy refresh resolve it. A source view
269/// pinned to another spelling of the same root no longer matched the request
270/// project and fell to deny-all on every governed Windows request.
271fn canonical_project_root(project: &Path) -> Result<PathBuf, String> {
272    let project = crate::core::pathutil::canonicalize_secure(project)
273        .map_err(|_| "policy project root unavailable")?;
274    if !project.is_dir() {
275        return Err("policy project root unavailable".into());
276    }
277    Ok(project)
278}
279
280/// Whether the bound request project (if any) is `root`, a root already in
281/// the one spelling of `canonical_project_root`. The bound side is resolved
282/// the same way first: a caller may have bound another spelling of the same
283/// directory (on Windows the verbatim `\\?\` form of `std::fs::canonicalize`).
284/// No bound request project: `true`, the operation's own root governs.
285pub(crate) fn request_project_is(root: &Path) -> bool {
286    match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
287        Ok(Some(bound)) => canonical_project_root(&bound).is_ok_and(|bound| bound == root),
288        _ => true,
289    }
290}
291
292/// Run a source operation with an explicit fallback project root. An existing
293/// request project remains authoritative; the fallback only fills an unbound
294/// request scope.
295pub(crate) fn with_project_source_view<T>(
296    project_root: &str,
297    operation: impl FnOnce() -> T,
298) -> Result<T, String> {
299    let project = REQUEST_PROJECT
300        .try_with(|slot| slot.borrow().clone())
301        .ok()
302        .flatten()
303        .or_else(|| current_source_view().map(|view| view.project))
304        .unwrap_or_else(|| PathBuf::from(project_root));
305    let project = canonical_project_root(&project)?;
306    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
307        with_source_view(operation)
308    })
309}
310
311/// Run an egress preparation for one explicitly selected project. Unlike the
312/// source-view fallback helper, this rejects a conflicting trusted request root
313/// and revalidates authority after the operation before its result is published.
314pub(crate) fn with_explicit_project_source_view<T>(
315    project_root: &Path,
316    operation: impl FnOnce(&PublicationAuthority) -> T,
317) -> Result<T, String> {
318    let project = canonical_project_root(project_root)?;
319
320    let bound = REQUEST_PROJECT
321        .try_with(|slot| slot.borrow().clone())
322        .ok()
323        .flatten();
324    if let Some(bound) = bound {
325        let bound = crate::core::pathutil::canonicalize_secure(&bound)
326            .map_err(|_| "request project authority unavailable")?;
327        if bound != project {
328            return Err("request project authority does not match egress root".into());
329        }
330    }
331    if let Some(view) = current_source_view()
332        && (!view.live.load(Ordering::Acquire)
333            || !view.valid.load(Ordering::Acquire)
334            || view.project != project)
335    {
336        view.invalidate_if_live();
337        return Err("source policy view does not match egress root".into());
338    }
339
340    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
341        with_source_view(|| {
342            let authority = PublicationAuthority::capture()?;
343            let result = operation(&authority);
344            authority.verify()?;
345            Ok(result)
346        })?
347    })
348}
349
350/// Run a synchronous source operation against one freshly verified policy
351/// snapshot. Publish the returned value only if the same authority still holds.
352/// Nested calls reuse the parent snapshot; they never refresh into a weaker view.
353pub(crate) fn with_source_view<T>(operation: impl FnOnce() -> T) -> Result<T, String> {
354    with_source_view_when(|_, _| true, operation)?
355        .ok_or_else(|| "source policy view is no longer active".into())
356}
357
358/// [`with_source_view`], entered only when the verification the view is
359/// pinned to established something to act under: a policy, or an observed
360/// organization decision (a signed unpin leaves no policy and is one all the
361/// same). `Ok(None)`: it established neither, no view was opened and
362/// `operation` did not run.
363///
364/// The decision whether to enter and the view are made of ONE verification:
365/// there is no probe first and a second resolution after, so what the caller
366/// branched on is what its view holds. Everything else is `with_source_view`
367/// — the nested-view rules, the closing recheck and the horizon. Inside,
368/// [`is_active`] and [`active_observed`] read the held view.
369#[cfg(feature = "http-server")]
370pub(crate) fn with_governed_source_view<T>(
371    operation: impl FnOnce() -> T,
372) -> Result<Option<T>, String> {
373    with_source_view_when(|policy, observed| policy || observed, operation)
374}
375
376/// `enter(policy present, organization decision observed)` is asked once, of
377/// the view that would be used; `false` leaves without running `operation`.
378fn with_source_view_when<T>(
379    enter: impl FnOnce(bool, bool) -> bool,
380    operation: impl FnOnce() -> T,
381) -> Result<Option<T>, String> {
382    if let Some(view) = current_source_view() {
383        let project = REQUEST_PROJECT
384            .try_with(|slot| slot.borrow().clone())
385            .ok()
386            .flatten()
387            .ok_or("source policy view is no longer active")?;
388        let project = canonical_project_root(&project)
389            .map_err(|_| "source policy view is no longer active")?;
390        if !view.live.load(Ordering::Acquire)
391            || !view.valid.load(Ordering::Acquire)
392            || project != view.project
393            || !view.within_horizon()
394        {
395            view.invalidate_if_live();
396            return Err("source policy view is no longer active".into());
397        }
398        if !enter(view.policy.is_some(), view.observation.is_some()) {
399            return Ok(None);
400        }
401        return REQUEST_PROJECT
402            .sync_scope(std::cell::RefCell::new(Some(view.project.clone())), || {
403                Ok(Some(operation()))
404            });
405    }
406
407    // A request bound to no project gets no source view: its project is not
408    // invented from the process's working directory (AP01 §3). Only work
409    // outside any request (the CLI) acts for the directory it runs in.
410    let project = match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
411        Ok(project) => project.ok_or("project_unresolved")?,
412        Err(_) => std::env::current_dir().map_err(|_| "policy project root unavailable")?,
413    };
414    let project = canonical_project_root(&project)?;
415    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.clone())), || {
416        let verified = refresh::current_verified_settled(&project)?;
417        let lifetime = verified.lifetime;
418        let observation = verified.observation;
419        let role = crate::core::roles::active_role();
420        let pinned_role_fingerprint = role_fingerprint(&role)?;
421        let view = SourceView {
422            project: project.clone(),
423            policy: source_view_policy(verified.policy),
424            fingerprint: verified.fingerprint,
425            role,
426            role_fingerprint: pinned_role_fingerprint,
427            lifetime,
428            observation,
429            valid: Arc::new(AtomicBool::new(true)),
430            live: Arc::new(AtomicBool::new(true)),
431        };
432
433        // The reads since the verification took time: the operation is not
434        // entered on a floor whose horizon has already passed.
435        if !view.within_horizon() {
436            return Err("source policy view is no longer active".into());
437        }
438        // Asked of this very verification, before anything runs on it.
439        if !enter(view.policy.is_some(), view.observation.is_some()) {
440            return Ok(None);
441        }
442        let view_lifetime = SourceViewLifetime(view.live.clone());
443        let value = SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view.clone())), operation);
444        drop(view_lifetime);
445
446        // SOURCE_VIEW has ended, while REQUEST_PROJECT still identifies the
447        // same request root; re-resolve the complete role before publishing.
448        let project_unchanged = REQUEST_PROJECT
449            .try_with(|slot| slot.borrow().as_ref() == Some(&view.project))
450            .unwrap_or(false);
451        let latest_role = crate::core::roles::active_role();
452        let latest_role_fingerprint = role_fingerprint(&latest_role)?;
453        let latest = refresh::current_verified_settled(&project)?;
454        if !project_unchanged
455            || latest.fingerprint != view.fingerprint
456            || latest_role_fingerprint != view.role_fingerprint
457            || !view.valid.load(Ordering::Acquire)
458        {
459            return Err("source policy view changed during operation".into());
460        }
461        // Last, after every closing wait: the operation ran on a floor signed
462        // up to a horizon. If that passed in the meantime its result is not
463        // published, whatever the fresh verification above said.
464        if !view.within_horizon() {
465            return Err("source policy view changed during operation".into());
466        }
467        Ok(Some(value))
468    })
469}
470
471pub(crate) fn role_fingerprint(role: &crate::core::roles::Role) -> Result<blake3::Hash, String> {
472    serde_json::to_vec(role)
473        .map(|bytes| blake3::hash(&bytes))
474        .map_err(|_| "source role view unavailable".into())
475}
476
477#[cfg(test)]
478fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
479    let state = test_override()
480        .read()
481        .unwrap_or_else(std::sync::PoisonError::into_inner);
482    match &*state {
483        OverrideState::Live => fresh,
484        OverrideState::Fixed(policy) => policy.clone(),
485    }
486}
487
488#[cfg(not(test))]
489fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
490    fresh
491}
492
493/// Project-local pack location, relative to the working directory (matches the
494/// `lean-ctx policy` CLI's `PROJECT_PACK_PATH`).
495const PROJECT_PACK_PATH: &str = ".lean-ctx/policy.toml";
496
497/// A resolved policy plus its precompiled redaction regexes — the cached,
498/// hot-path-ready form.
499pub struct ActivePolicy {
500    pub resolved: ResolvedPolicy,
501    /// `(label, compiled regex)` — labels are the pack's `[redaction]` keys.
502    /// Invalid/over-budget compilation makes the whole policy fail closed.
503    pub redaction: Vec<(String, Regex)>,
504    pub(crate) blocked_patterns: Vec<(String, Regex)>,
505    /// How many of `redaction` + `blocked_patterns` a Hive filter pack
506    /// added; they have their own budget next to the pack's.
507    pub(crate) hive_rules: usize,
508    pub(crate) content_valid: bool,
509    /// Compiled inbound content filters (GL #675), built once from the pack's
510    /// `[filters]` section.
511    pub filters: FilterConfig,
512    /// Compiled egress/output DLP config (GL #676), built once from the pack's
513    /// `[egress]` section.
514    pub egress: crate::core::egress::EgressConfig,
515    /// The signed instant this policy's organization floor runs out at, set
516    /// before the policy is shared and never changed. `None` for every policy
517    /// that rests on no verifier decision: local, version one, or a lifted
518    /// requirement. The fields above describe the policy; they authorize
519    /// nothing once this instant has passed — see [`Self::within_horizon`].
520    horizon: Option<chrono::DateTime<chrono::Utc>>,
521    /// Set the first time the horizon is observed to have passed, and never
522    /// cleared. It lives in the policy itself, so every holder of the same
523    /// shared policy sees it: once expired, a clock set back revives nothing.
524    expired: AtomicBool,
525}
526
527impl ActivePolicy {
528    /// Whether this policy may still be acted on: read on the real clock at
529    /// every use, so a policy that is kept — in a view, a snapshot or a
530    /// caller's variable — ends with its signed horizon and not with the
531    /// request that obtained it. Exclusive, like the verifier's own check.
532    /// An expiry once observed is final for this policy.
533    #[must_use]
534    pub fn within_horizon(&self) -> bool {
535        if self.expired.load(Ordering::Acquire) {
536            return false;
537        }
538        let holds = self
539            .horizon
540            .is_none_or(|horizon| chrono::Utc::now() < horizon);
541        if !holds {
542            self.expired.store(true, Ordering::Release);
543        }
544        holds
545    }
546
547    /// This policy, ending at `horizon`. Only for a policy not yet shared.
548    fn until(mut self, horizon: Option<chrono::DateTime<chrono::Utc>>) -> Self {
549        self.horizon = horizon;
550        self
551    }
552
553    pub(crate) fn from_resolved(resolved: ResolvedPolicy) -> Self {
554        Self::from_resolved_with_hive(resolved, &crate::core::hive::policy::FilterRules::default())
555    }
556
557    /// As [`Self::from_resolved`], with the rules of the installed Hive
558    /// filter packs added under their own budget. A Hive rule over its
559    /// bounds fails the policy closed like a pack rule; installation
560    /// refuses such sets, so this is defensive.
561    pub(crate) fn from_resolved_with_hive(
562        mut resolved: ResolvedPolicy,
563        hive: &crate::core::hive::policy::FilterRules,
564    ) -> Self {
565        use super::content::{MAX_REDACTION_RULES, MAX_RULE_LABEL_BYTES, MAX_RULE_PATTERN_BYTES};
566        let hive_rules = hive.redaction.len() + hive.blocked.len();
567        let hive_bounded = hive_rules <= crate::core::hive::policy::HIVE_MAX_RULES
568            && hive
569                .redaction
570                .iter()
571                .chain(&hive.blocked)
572                .all(|(label, pattern)| {
573                    label.starts_with(super::HIVE_LABEL_PREFIX)
574                        && label.len() <= MAX_RULE_LABEL_BYTES
575                        && !label.chars().any(char::is_control)
576                        && pattern.len() <= MAX_RULE_PATTERN_BYTES
577                });
578        let bounded = hive_bounded
579            && resolved.redaction.len() + resolved.filters.blocked_patterns.len()
580                <= MAX_REDACTION_RULES
581            && resolved.egress.forbidden_patterns.len() <= MAX_REDACTION_RULES
582            && resolved
583                .egress
584                .forbidden_patterns
585                .iter()
586                .all(|pattern| pattern.len() <= MAX_RULE_PATTERN_BYTES)
587            && resolved
588                .redaction
589                .iter()
590                .chain(&resolved.filters.blocked_patterns)
591                .all(|(label, pattern)| {
592                    !label.is_empty()
593                        && label.len() <= MAX_RULE_LABEL_BYTES
594                        && !label.chars().any(char::is_control)
595                        && pattern.len() <= MAX_RULE_PATTERN_BYTES
596                });
597        // Pack labels never start with the Hive prefix (pack validation), so
598        // a Hive rule neither replaces nor is replaced by a pack rule.
599        resolved.redaction.extend(hive.redaction.iter().cloned());
600        resolved
601            .filters
602            .blocked_patterns
603            .extend(hive.blocked.iter().cloned());
604        let compiled = bounded.then(|| {
605            resolved
606                .redaction
607                .iter()
608                .map(|(label, pattern)| {
609                    regex::RegexBuilder::new(pattern)
610                        .size_limit(1024 * 1024)
611                        .dfa_size_limit(1024 * 1024)
612                        .build()
613                        .map(|re| (label.clone(), re))
614                })
615                .collect::<Result<Vec<_>, _>>()
616        });
617        let content_valid = matches!(&compiled, Some(Ok(_)));
618        let redaction = compiled.and_then(Result::ok).unwrap_or_default();
619        let compiled_blocks = bounded.then(|| {
620            resolved
621                .filters
622                .blocked_patterns
623                .iter()
624                .map(|(label, pattern)| {
625                    regex::RegexBuilder::new(pattern)
626                        .size_limit(1024 * 1024)
627                        .dfa_size_limit(1024 * 1024)
628                        .build()
629                        .map(|re| (label.clone(), re))
630                })
631                .collect::<Result<Vec<_>, _>>()
632        });
633        let content_valid = content_valid && matches!(&compiled_blocks, Some(Ok(_)));
634        let blocked_patterns = compiled_blocks.and_then(Result::ok).unwrap_or_default();
635        let filters = FilterConfig::new(
636            filter_action(resolved.filters.pii.as_ref()),
637            filter_action(resolved.filters.classification.as_ref()),
638            filter_action(resolved.filters.injection.as_ref()),
639            &resolved.filters.blocked_labels,
640        );
641        let egress = crate::core::egress::EgressConfig::new(
642            &resolved.egress.forbidden_patterns,
643            resolved.egress.block_secrets.unwrap_or(false),
644            resolved.egress.max_writes_per_min,
645        );
646        Self {
647            resolved,
648            redaction,
649            blocked_patterns,
650            hive_rules,
651            content_valid,
652            filters,
653            egress,
654            horizon: None,
655            expired: AtomicBool::new(false),
656        }
657    }
658
659    /// Block every tool after a local policy pack fails to load.
660    pub(crate) fn deny_all() -> Self {
661        let mut active = Self::from_resolved(ResolvedPolicy {
662            name: "invalid-local-policy".into(),
663            version: "0.0.0".into(),
664            description: "deny all because the local policy pack is invalid".into(),
665            chain: Vec::new(),
666            default_read_mode: None,
667            allow_tools: Some(Vec::new()),
668            deny_tools: Vec::new(),
669            max_context_tokens: None,
670            audit_retention_days: None,
671            redaction: std::collections::BTreeMap::new(),
672            filters: crate::core::policy::FilterRules::default(),
673            egress: crate::core::policy::EgressRules::default(),
674            routing: crate::core::policy::RoutingPolicyRules::default(),
675            budgets: crate::core::policy::BudgetRules::default(),
676        });
677        active.content_valid = false;
678        active
679    }
680
681    /// Whether `tool` is permitted by this policy's allow/deny lists.
682    /// `deny_tools` always wins; an `allow_tools` allowlist, when set, is
683    /// exclusive (only listed tools pass).
684    #[must_use]
685    pub fn tool_allowed(&self, tool: &str) -> bool {
686        if !self.content_valid || !self.within_horizon() {
687            return false;
688        }
689        if self.resolved.deny_tools.iter().any(|t| t == tool) {
690            return false;
691        }
692        match &self.resolved.allow_tools {
693            Some(allow) => allow.iter().any(|t| t == tool),
694            None => true,
695        }
696    }
697}
698
699/// Map a resolved `[filters]` action string to a [`FilterAction`]. Absent or
700/// (defensively) unparseable ⇒ `Off`; validation already rejects bad tokens.
701fn filter_action(opt: Option<&String>) -> FilterAction {
702    opt.map(String::as_str)
703        .and_then(FilterAction::parse)
704        .unwrap_or(FilterAction::Off)
705}
706
707#[cfg(test)]
708fn load_from_disk() -> Option<Arc<ActivePolicy>> {
709    let local = match load_local_pack() {
710        Ok(local) => local,
711        Err(msg) => {
712            tracing::error!(
713                "policy: failed to load invalid {PROJECT_PACK_PATH} ({msg}); enforcing deny-all"
714            );
715            return Some(Arc::new(ActivePolicy::deny_all()));
716        }
717    };
718    apply_org_floor(
719        local,
720        crate::core::policy::org::active_resolved_checked(),
721        None,
722        &crate::core::hive::policy::FilterRules::default(),
723        None,
724    )
725}
726
727/// `horizon` is the signed end of the organization floor, when a verifier
728/// decided it; it is attached here, before the policy is shared.
729/// `hive_floor` is the Hive effective policy (Release B): folded under
730/// everything else, so nothing local can loosen it.
731fn apply_org_floor(
732    local: Option<ResolvedPolicy>,
733    org: Result<Option<ResolvedPolicy>, String>,
734    horizon: Option<chrono::DateTime<chrono::Utc>>,
735    hive: &crate::core::hive::policy::FilterRules,
736    hive_floor: Option<&ResolvedPolicy>,
737) -> Option<Arc<ActivePolicy>> {
738    // Invalid configured org policy must not silently remove the org floor.
739    let effective = match org {
740        Ok(Some(org)) => Some(crate::core::policy::floor::merge_floor(
741            &org,
742            local.as_ref(),
743        )),
744        Ok(None) => local,
745        Err(error) => {
746            tracing::error!("org policy rejected; enforcing deny-all: {error}");
747            return Some(Arc::new(ActivePolicy::deny_all()));
748        }
749    };
750    let effective = match hive_floor {
751        Some(floor) => Some(crate::core::hive::effective_floor::apply(
752            floor,
753            effective.as_ref(),
754        )),
755        None => effective,
756    };
757    let effective = match effective {
758        Some(effective) => effective,
759        None if hive.redaction.is_empty() && hive.blocked.is_empty() => return None,
760        // Hive filter packs alone: content rules only, no tool or path rule.
761        None => hive_filters_only(),
762    };
763    Some(Arc::new(
764        ActivePolicy::from_resolved_with_hive(effective, hive).until(horizon),
765    ))
766}
767
768/// The policy that carries nothing but the rules of Hive filter packs.
769fn hive_filters_only() -> ResolvedPolicy {
770    ResolvedPolicy {
771        name: "hive-filters".into(),
772        version: "1.0.0".into(),
773        description: "content rules of the installed Hive filter packs".into(),
774        chain: Vec::new(),
775        default_read_mode: None,
776        allow_tools: None,
777        deny_tools: Vec::new(),
778        max_context_tokens: None,
779        audit_retention_days: None,
780        redaction: std::collections::BTreeMap::new(),
781        filters: crate::core::policy::FilterRules::default(),
782        egress: crate::core::policy::EgressRules::default(),
783        routing: crate::core::policy::RoutingPolicyRules::default(),
784        budgets: crate::core::policy::BudgetRules::default(),
785    }
786}
787
788/// The project-local pack (`.lean-ctx/policy.toml`), resolved. `None` only when
789/// the file is absent; malformed packs return an error so callers fail closed.
790#[cfg(test)]
791fn load_local_pack() -> Result<Option<ResolvedPolicy>, String> {
792    let path = PathBuf::from(PROJECT_PACK_PATH);
793    load_local_pack_at(&path)
794}
795
796#[cfg(test)]
797fn load_local_pack_at(path: &Path) -> Result<Option<ResolvedPolicy>, String> {
798    match std::fs::symlink_metadata(path) {
799        Ok(_) => {}
800        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
801        Err(error) => return Err(format!("{}: {error}", path.display())),
802    }
803    match parse_file(path).and_then(|p| resolve(&p)) {
804        Ok(resolved) => Ok(Some(resolved)),
805        Err(e) => Err(format!("{}: {e}", path.display())),
806    }
807}
808
809/// Resolve the explicit runtime project without using the process-global cache.
810/// Configured local/org errors remain errors rather than granting admission.
811pub fn for_project(project_root: &Path) -> Result<Option<Arc<ActivePolicy>>, String> {
812    refresh::current(project_root.to_path_buf())
813}
814
815/// The active resolved policy, or `None` when no project or org pack exists.
816/// Fresh source bytes are mandatory even when compiled rules are cached.
817#[must_use]
818pub fn active() -> Option<Arc<ActivePolicy>> {
819    active_observed().0
820}
821
822/// [`active`], together with the organization decision the verifier stated
823/// in the very verification that policy comes from — one read, one answer,
824/// no second look at policy, trust store or marker. For whoever records what
825/// it decided under: the observation it files is the one of its own
826/// snapshot, never a later one.
827///
828/// The observation is `None` whenever no verifier was asked (no organization
829/// policy, a version-one one) and whenever the policy is the deny-all that
830/// stands for an authority that could not be established: a refusal records
831/// no organization decision it did not get. A lifted requirement is observed
832/// although it leaves no floor, and so possibly no policy at all.
833#[must_use]
834pub(crate) fn active_observed() -> (Option<Arc<ActivePolicy>>, Option<super::org::Observation>) {
835    let deny_all = || (Some(Arc::new(ActivePolicy::deny_all())), None);
836    if let Some(view) = current_source_view() {
837        if !view.live.load(Ordering::Acquire) || !view.valid.load(Ordering::Acquire) {
838            return deny_all();
839        }
840        let project = REQUEST_PROJECT
841            .try_with(|slot| slot.borrow().clone())
842            .ok()
843            .flatten();
844        if project.as_ref() != Some(&view.project) || !view.within_horizon() {
845            view.invalidate_if_live();
846            return deny_all();
847        }
848        return (view.policy, view.observation);
849    }
850    #[cfg(test)]
851    {
852        let state = test_override()
853            .read()
854            .unwrap_or_else(std::sync::PoisonError::into_inner);
855        if let OverrideState::Fixed(policy) = &*state {
856            return (policy.clone(), None);
857        }
858    }
859    let scoped = REQUEST_PROJECT
860        .try_with(|slot| slot.borrow().clone())
861        .ok()
862        .flatten();
863    match scoped
864        .map_or_else(std::env::current_dir, Ok)
865        .map_err(|_| "policy project root unavailable".into())
866        .and_then(refresh::current_verified)
867    {
868        Ok(verified) => (verified.policy, verified.observation),
869        Err(_) => deny_all(),
870    }
871}
872
873/// Run `operation` under a pinned view of `project` whose verification
874/// observed `observation` and left no policy — the state after a signed
875/// unpin on an endpoint without a project pack. Tests only: a real view comes
876/// from `with_source_view` and nowhere else.
877#[cfg(test)]
878pub(crate) fn with_observed_view_for_test<T>(
879    project: &Path,
880    observation: Option<super::org::Observation>,
881    operation: impl FnOnce() -> T,
882) -> T {
883    let project = canonical_project_root(project).expect("test project root");
884    let role = crate::core::roles::active_role();
885    // The authority as it really verifies for this root (no organization
886    // artifact in a test's data directory), so that a holder's own closing
887    // verification finds the same fingerprint; only the observation is given.
888    let verified = refresh::current_verified(project.clone()).expect("test authority");
889    let view = SourceView {
890        project: project.clone(),
891        policy: verified.policy,
892        fingerprint: verified.fingerprint,
893        role_fingerprint: role_fingerprint(&role).expect("test role"),
894        role,
895        lifetime: None,
896        observation,
897        valid: Arc::new(AtomicBool::new(true)),
898        live: Arc::new(AtomicBool::new(true)),
899    };
900    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
901        SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation)
902    })
903}
904
905/// What a source view that is already held says about the organization.
906pub(crate) enum HeldObservation {
907    /// No usable view is held here: nothing can be said, and nothing is.
908    NotHeld,
909    /// The held view's own observation (`None`: its verification asked no
910    /// verifier).
911    Held(Option<super::org::Observation>),
912}
913
914/// The organization observation of the source view the caller already runs
915/// under — and nothing else. It never resolves, refreshes or reads: without a
916/// held view that is live, valid, of the request's own project and within its
917/// signed horizon, the answer is [`HeldObservation::NotHeld`]. For a path
918/// that must not start a verification of its own but may record the decision
919/// its caller's view was verified with.
920pub(crate) fn held_observation() -> HeldObservation {
921    let Some(view) = current_source_view() else {
922        return HeldObservation::NotHeld;
923    };
924    let project = REQUEST_PROJECT
925        .try_with(|slot| slot.borrow().clone())
926        .ok()
927        .flatten();
928    if !view.live.load(Ordering::Acquire)
929        || !view.valid.load(Ordering::Acquire)
930        || project.as_ref() != Some(&view.project)
931        || !view.within_horizon()
932    {
933        return HeldObservation::NotHeld;
934    }
935    HeldObservation::Held(view.observation)
936}
937
938/// Current "is a policy active?" probe; refresh failure requires protection.
939#[must_use]
940pub fn is_active() -> bool {
941    active().is_some()
942}
943
944/// Re-read the project pack (e.g. after a `policy` edit). Idempotent.
945pub fn reload() {
946    let _ = active();
947}
948
949#[cfg(test)]
950enum OverrideState {
951    Live,
952    Fixed(Option<Arc<ActivePolicy>>),
953}
954
955#[cfg(test)]
956fn test_override() -> &'static RwLock<OverrideState> {
957    static OVERRIDE: OnceLock<RwLock<OverrideState>> = OnceLock::new();
958    OVERRIDE.get_or_init(|| RwLock::new(OverrideState::Live))
959}
960
961#[cfg(test)]
962fn test_override_lock() -> &'static std::sync::Mutex<()> {
963    static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
964    LOCK.get_or_init(|| std::sync::Mutex::new(()))
965}
966
967/// The policy-override lock together with the test environment lock, in the
968/// one order every test takes them: environment first, then policy. Held as
969/// one value so that neither outlives the other; the fields are declared in
970/// release order — policy before environment.
971#[cfg(test)]
972pub(crate) struct TestOverrideGuard {
973    _policy: std::sync::MutexGuard<'static, ()>,
974    _environment: crate::core::data_dir::TestEnvGuard,
975}
976
977#[cfg(test)]
978pub(crate) fn lock_test_override() -> TestOverrideGuard {
979    let environment = crate::core::data_dir::test_env_lock();
980    let policy = test_override_lock()
981        .lock()
982        .unwrap_or_else(std::sync::PoisonError::into_inner);
983    TestOverrideGuard {
984        _policy: policy,
985        _environment: environment,
986    }
987}
988
989/// Process-wide test override held under a shared lock for its whole lifetime.
990#[cfg(test)]
991pub struct TestPolicyOverride {
992    previous: OverrideState,
993    _lock: TestOverrideGuard,
994}
995
996#[cfg(test)]
997impl TestPolicyOverride {
998    pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
999        let lock = lock_test_override();
1000        let previous = std::mem::replace(
1001            &mut *test_override()
1002                .write()
1003                .unwrap_or_else(std::sync::PoisonError::into_inner),
1004            OverrideState::Fixed(
1005                resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
1006            ),
1007        );
1008        Self {
1009            previous,
1010            _lock: lock,
1011        }
1012    }
1013}
1014
1015#[cfg(test)]
1016impl Drop for TestPolicyOverride {
1017    fn drop(&mut self) {
1018        *test_override()
1019            .write()
1020            .unwrap_or_else(std::sync::PoisonError::into_inner) =
1021            std::mem::replace(&mut self.previous, OverrideState::Live);
1022    }
1023}
1024
1025#[cfg(test)]
1026#[path = "runtime/tests.rs"]
1027mod tests;