pub struct Config {Show 164 fields
pub ultra_compact: bool,
pub tee_mode: TeeMode,
pub recovery_hints: RecoveryHints,
pub output_density: OutputDensity,
pub checkpoint_interval: u32,
pub excluded_commands: Vec<String>,
pub passthrough_urls: Vec<String>,
pub custom_aliases: Vec<AliasEntry>,
pub preserve_compact_formats: Vec<String>,
pub crush_verbatim_json: bool,
pub slow_command_threshold_ms: u64,
pub theme: String,
pub telemetry: TelemetryConfig,
pub cloud: LegacyCloudConfig,
pub hive: HiveConfig,
pub cost: CostConfig,
pub decision_loop: DecisionLoopConfig,
pub protection: ProtectionConfig,
pub code_health: CodeHealthConfig,
pub autonomy: AutonomyConfig,
pub providers: ProvidersConfig,
pub knowledge_routing: KnowledgeRoutingConfig,
pub proxy: ProxyConfig,
pub conversation: ConversationConfig,
pub response_shaping: ResponseShapingConfig,
pub ocla: OclaConfig,
pub intelligence_runtime: IntelligenceRuntimeConfig,
pub shadow: ShadowConfig,
pub value_display: ValueDisplayConfig,
pub cache: CacheConfig,
pub agents: AgentsConfig,
pub proxy_enabled: Option<bool>,
pub proxy_port: Option<u16>,
pub proxy_timeout_ms: Option<u64>,
pub proxy_require_token: bool,
pub proxy_loopback_open: bool,
pub proxy_bind_host: Option<String>,
pub proxy_allowed_hosts: Vec<String>,
pub proxy_max_rps: Option<u32>,
pub dashboard_auth: bool,
pub dashboard_cache_hit_rate: Option<f64>,
pub buddy_enabled: bool,
pub enable_wakeup_ctx: bool,
pub redirect_exclude: Vec<String>,
pub disabled_tools: Vec<String>,
pub prefer_native_editor: bool,
pub default_tool_categories: Vec<String>,
pub no_degrade: bool,
pub delta_explicit: bool,
pub profile: Option<String>,
pub active_kit: Option<String>,
pub config_profile: Option<String>,
pub profiles: BTreeMap<String, Table>,
pub tool_profile: Option<String>,
pub tools_enabled: Vec<String>,
pub persona: Option<String>,
pub loop_detection: LoopDetectionConfig,
pub rules_scope: Option<String>,
pub rules_injection: Option<String>,
pub permission_inheritance: Option<String>,
pub extra_ignore_patterns: Vec<String>,
pub terse_agent: TerseAgent,
pub compression_level: CompressionLevel,
pub compression_aggressiveness: Option<f64>,
pub archive: ArchiveConfig,
pub memory: MemoryPolicy,
pub allow_paths: Vec<String>,
pub allow_ide_config_dirs: Option<bool>,
pub extra_roots: Vec<String>,
pub read_only_roots: Vec<String>,
pub allow_symlink_roots: Vec<String>,
pub content_defined_chunking: bool,
pub minimal_overhead: bool,
pub symbol_map_auto: bool,
pub structure_first: bool,
pub progressive_disclosure: bool,
pub progressive_threshold_lines: u32,
pub progressive_signatures_max: u32,
pub auto_mode_learning: bool,
pub team_share_content: bool,
pub journal_enabled: bool,
pub auto_capture: bool,
pub search: HybridConfig,
pub index: IndexConfig,
pub skillify: SkillifyConfig,
pub summaries: SummariesConfig,
pub llm: LlmConfig,
pub embedding: EmbeddingConfig,
pub shell_hook_disabled: bool,
pub shadow_mode: bool,
pub shell_hook_mode: Option<String>,
pub prompt_reinject: Option<String>,
pub hook_mode: Option<String>,
pub tool_surface: Option<String>,
pub debug_log: bool,
pub shell_activation: ShellActivation,
pub skip_agent_aliases: bool,
pub read_redirect: ReadRedirect,
pub read_dedup: ReadDedup,
pub shell_approval: ShellApproval,
pub execute_allowed_languages: Vec<String>,
pub update_check_disabled: bool,
pub updates: UpdatesConfig,
pub context: ContextConfig,
pub bm25_max_cache_mb: u64,
pub graph_index_max_files: u64,
pub bm25_max_files: u64,
pub memory_profile: MemoryProfile,
pub memory_cleanup: MemoryCleanup,
pub semantic_mode: SemanticMode,
pub max_ram_percent: u8,
pub mcp_max_rss_mb: u64,
pub daemon_max_rss_mb: u64,
pub mcp_idle_exit_minutes: u64,
pub max_disk_mb: u64,
pub max_staleness_days: u32,
pub session_retention_days: u32,
pub max_index_threads: usize,
pub savings_footer: SavingsFooter,
pub compression_annotation: CompressionAnnotation,
pub annotation_threshold_pct: u8,
pub behavior_nudges: String,
pub turn_fresh_limit: usize,
pub turn_fresh_limit_verbatim: usize,
pub project_root: Option<String>,
pub lsp: HashMap<String, String>,
pub ide_paths: HashMap<String, Vec<String>>,
pub model_context_windows: HashMap<String, usize>,
pub response_verbosity: ResponseVerbosity,
pub bypass_hints: Option<String>,
pub cache_policy: Option<String>,
pub cache_max_tokens: usize,
pub boundary_policy: BoundaryPolicy,
pub secret_detection: SecretDetectionConfig,
pub sensitivity: SensitivityConfig,
pub context_gateway: ContextGatewayConfig,
pub load_failure: Option<ConfigLoadFailure>,
pub a2a_accept_untrusted_signers: bool,
pub mcp_import_allow_unverified: bool,
pub gateway: GatewayConfig,
pub gateway_server: GatewayServerConfig,
pub enterprise: EnterpriseConfig,
pub hook_binary: Option<String>,
pub path_jail: Option<bool>,
pub path_jail_scope: Option<String>,
pub sandbox_level: u8,
pub reference_results: bool,
pub agent_token_budget: usize,
pub shell_allowlist: Vec<String>,
pub shell_allowlist_extra: Vec<String>,
pub shell_strict_mode: bool,
pub shell_allowlist_subcommand_scoping: bool,
pub shell_security: Option<String>,
pub shell_timeout_secs: Option<u64>,
pub shell_heavy_timeout_secs: Option<u64>,
pub shell_heavy_prefixes: Vec<String>,
pub shell_allow_writes: bool,
pub write_allow_paths: Vec<String>,
pub shell_allow_inline_scripts: bool,
pub setup: SetupConfig,
pub solution: SolutionConfig,
pub governor: GovernorConfig,
pub provenance: ProvenanceConfig,
pub cross_agent: CrossAgentConfig,
}Expand description
Global lean-ctx configuration loaded from config.toml, merged with project-local overrides.
Fields§
§ultra_compact: bool§tee_mode: TeeMode§recovery_hints: RecoveryHintsVerbosity of the reactive recovery footer on compressed output
(off|minimal|full, default minimal). See RecoveryHints.
output_density: OutputDensity§checkpoint_interval: u32§excluded_commands: Vec<String>§passthrough_urls: Vec<String>§custom_aliases: Vec<AliasEntry>§preserve_compact_formats: Vec<String>Output formats that are already compact/token-oriented and must be
preserved verbatim instead of being recompressed (#342). Matched against
the output shape (not the command name), so any tool emitting the
format is covered without enumerating commands in excluded_commands.
Default: ["toon"]. Set to [] to disable and always recompress.
crush_verbatim_json: boolOpt-in: apply the lossless JSON crusher to verbatim data commands
(gh api, jq, kubectl get -o json, curl JSON). Off by default, so
those outputs stay byte-for-byte verbatim. When on, an array-heavy JSON
payload the crusher can at least halve is reshaped into a compact, fully
reconstructible form; everything else stays verbatim. See
Config::crush_verbatim_json_enabled (#936).
slow_command_threshold_ms: u64Commands taking longer than this threshold (ms) are recorded in the slow log. Set to 0 to disable slow logging.
theme: String§telemetry: TelemetryConfigPrivacy-safe default-on telemetry with explicit and environment opt-outs.
cloud: LegacyCloudConfigLegacy [cloud] opt-in, migrated on load; never written back.
hive: HiveConfigLeanCTX | Hive connector ([hive]).
cost: CostConfigModel declaration for measured-vs-estimated cost reporting (MCP-only IDEs).
decision_loop: DecisionLoopConfig§protection: ProtectionConfigUser-controlled never-lossy zones (#1570 P4): protected file globs
and <protect> span handling.
code_health: CodeHealthConfigCode-health engine: cognitive complexity, naming, coupling, edit-gate.
autonomy: AutonomyConfig§providers: ProvidersConfig§knowledge_routing: KnowledgeRoutingConfig§proxy: ProxyConfig§conversation: ConversationConfigConversation-history compression ([conversation], opt-in; #1123).
response_shaping: ResponseShapingConfigProxy-layer response shaping ([response_shaping], #1125).
ocla: OclaConfig§intelligence_runtime: IntelligenceRuntimeConfigGlobal-only, explicit consent and independent pins for optional local code.
shadow: ShadowConfigCounterfactual Shadow Mode reporting ([shadow]), opt-in.
value_display: ValueDisplayConfigUser-only value display ([value_display]): status line, recaps,
prompt segment, milestones. Never reaches the model context.
cache: CacheConfigGeneralized L1/L2/L3 cache settings ([cache]).
agents: AgentsConfig§proxy_enabled: Option<bool>Whether the API proxy is enabled. Tri-state:
- None: undecided (fresh install, will prompt on interactive setup)
- Some(true): user opted in, proxy managed by lean-ctx
- Some(false): user opted out, never touch proxy or endpoints
proxy_port: Option<u16>§proxy_timeout_ms: Option<u64>Proxy reachability timeout in milliseconds. Default: 200. Override via LEAN_CTX_PROXY_TIMEOUT_MS env var.
proxy_require_token: boolStrict proxy auth: when true, authenticate ONLY via the Bearer token
(LEAN_CTX_PROXY_TOKEN) and disable the provider-API-key fallback. Default
false keeps the loopback-friendly behavior where any local AI tool’s own
provider key authenticates (the proxy never injects upstream credentials —
it forwards the caller’s key verbatim). Enable on shared/multi-user hosts to
require the token; clients must then send `Authorization: Bearer [REDACTED:Authorization header]
proxy_loopback_open: boolSkip ALL proxy authentication on loopback-bound listeners (#755).
When true and the proxy binds a loopback address, every request is
accepted without a Bearer token or provider API key — MCP clients,
browser dashboards, and CLI tools all work without auth setup.
Ignored on non-loopback binds (gateway mode always requires auth).
Env override: LEAN_CTX_PROXY_LOOPBACK_OPEN.
proxy_bind_host: Option<String>Bind address for the proxy listener (gateway mode, enterprise#8).
Default None = 127.0.0.1 — local-safe, nothing changes for existing
installs. Set "0.0.0.0" (or a specific interface IP) to serve a whole
org from one host; any non-loopback bind hard-disables the provider-key
auth fallback (Bearer token becomes mandatory) and enables the
proxy_allowed_hosts Host-header allowlist. Env override:
LEAN_CTX_PROXY_BIND_HOST. An unparseable value falls back to loopback,
never to an open bind.
proxy_allowed_hosts: Vec<String>Host-header allowlist for a non-loopback proxy bind (gateway mode):
DNS-rebinding protection. Entries are hostnames or IPs without port
(e.g. "gateway.example.com"). Loopback names are always allowed.
Ignored (loopback-only guard, today’s behavior) while the bind is
loopback. Empty + non-loopback bind = only loopback Host headers pass,
so configure this when exposing the gateway.
proxy_max_rps: Option<u32>Proxy-wide request rate limit in requests/second (token bucket, burst =
2x). None (default) = unlimited on a loopback bind — today’s behavior —
and 50 rps with burst 100 on a non-loopback bind (gateway mode ships a
sane floor, enterprise#37). 0 disables the limiter even in gateway
mode (explicit opt-out).
dashboard_auth: boolRequire Bearer-token authentication for the dashboard. Default true:
the dashboard generates (or uses the pinned) token and rejects /api/*
and /metrics without it. Set to false to run the dashboard with no
auth token — useful for a local/Docker setup where managing a token is
inconvenient. No-auth mode is not unprotected: cross-origin and CSRF
attacks from a malicious local website are blocked by request-header
validation instead (Sec-Fetch-Site, Origin/Host same-origin, and a
Host allowlist against DNS rebinding — see dashboard::no_auth_request_ok).
Override per-run via the --no-auth / --auth=<bool> flag or the
LEAN_CTX_DASHBOARD_AUTH env var.
dashboard_cache_hit_rate: Option<f64>Provider prompt-cache hit rate for net-of-injection calculation (#1104).
Share of turns whose prefix is served from the provider cache; an
estimate, default 0.75. Prices: context_overhead::prefix_cost_factor.
buddy_enabled: bool§enable_wakeup_ctx: bool§redirect_exclude: Vec<String>File globs delivered verbatim: native reads skip the hook redirect and
automatic ctx_read modes return them in full (#60).
disabled_tools: Vec<String>Tools to exclude from the MCP tool list returned by list_tools.
Accepts exact tool names (e.g. ["ctx_graph", "ctx_agent"]).
Empty by default — all tools listed, no behaviour change.
prefer_native_editor: boolPrefer the host agent’s native editor over lean-ctx edit operations (#454).
When true, the lean-ctx edit tool(s) (see EDIT_TOOL_NAMES) are neither
advertised in list_tools nor dispatchable (direct or via ctx_call), so
the agent falls back to the host’s built-in editing UI. Reads / search /
shell / memory tools are unaffected. Override via
LEAN_CTX_PREFER_NATIVE_EDITOR=1.
default_tool_categories: Vec<String>Tool categories to activate by default for dynamic-tool-capable clients.
Values: “core” (always on), “arch”, “debug”, “memory”, “metrics”, “session”.
Example: default_tool_categories = ["core", "arch", "memory"]
Override via LCTX_DEFAULT_CATEGORIES env var (comma-separated).
Empty = lean-ctx default (core). Add session explicitly to evaluate
experimental local collaboration tools.
no_degrade: boolDisable all automatic read-mode degradation (auto_degrade + context_gate pressure). When true, lean-ctx never downgrades requested read modes regardless of pressure. Override via LCTX_NO_DEGRADE=1 env var.
delta_explicit: boolLegacy opt-in delta preference. Concrete per-call full/lines requests take precedence and stay fresh; this cannot replace their content with a delta. Use mode=auto or mode=diff for reduced re-reads. Retained for configuration compatibility. LCTX_DELTA_EXPLICIT=1/0 overrides.
profile: Option<String>Persistent profile name. Checked after LEAN_CTX_PROFILE env var.
Set via lean-ctx config set profile passthrough or editing config.toml.
active_kit: Option<String>Active task-specific Context Kit. LEAN_CTX_KIT takes precedence.
Set with lean-ctx kit load <name>.
config_profile: Option<String>Named configuration overlay selected from [profiles.<name>].
LEAN_CTX_CONFIG_PROFILE takes precedence over this persisted selector.
profiles: BTreeMap<String, Table>Partial configuration overlays keyed by profile name. Each overlay is recursively merged over the base configuration at load time.
tool_profile: Option<String>Tool visibility profile: “minimal” (5), “standard” (15), or “power” (all). Override via LEAN_CTX_TOOL_PROFILE env var. Existing installs default to “power” (backward compat).
tools_enabled: Vec<String>Explicit list of enabled tool names. Used only when no tool_profile is pinned (tool_profile takes precedence); leave tool_profile unset to apply this list.
The universal invoker ctx_call stays advertised so unlisted tools remain
reachable — add ctx_call to disabled_tools to make this allowlist authoritative.
Example: tools_enabled = ["ctx_read", "ctx_shell", "ctx_search"]
persona: Option<String>Active context persona (persona-spec-v1). Selects the domain bundle —
tool surface, read-mode/compressor/chunker defaults, intent taxonomy,
sensitivity floor. Override via LEAN_CTX_PERSONA. Defaults to coding.
loop_detection: LoopDetectionConfig§rules_scope: Option<String>Controls where lean-ctx installs agent rule files. Values: “both” (default), “global” (home-dir only), “project” (repo-local only). Override via LEAN_CTX_RULES_SCOPE env var.
rules_injection: Option<String>Controls how rules are injected for shared-instruction-file agents. Values: “shared” (default, marker block in CLAUDE.md/CODEBUDDY.md/AGENTS.md/GEMINI.md), “dedicated” (never touch those files; use each agent’s config-driven auto-load: SessionStart hook / instructions[] / context.fileName, #343), or “off” (write no rules file at all — for hosts that supply their own tool-steering workflow or phase-isolated/non-caching harnesses, #361). Override via LEAN_CTX_RULES_INJECTION env var.
permission_inheritance: Option<String>Mirror the host IDE’s tool-permission rules onto lean-ctx’s own MCP tools.
Values: “on” (default, GH #1428) or “off”. When “on”, lean-ctx reads the active
IDE’s permission config (v1: OpenCode) and applies the equivalent
deny/ask/allow decision to the matching lean-ctx tool — so ctx_shell
honors your bash/rm * rules instead of bypassing them.
Override via LEAN_CTX_PERMISSION_INHERITANCE env var.
extra_ignore_patterns: Vec<String>Extra glob patterns to ignore in graph/overview/preload (repo-local).
Example: ["externals/**", "target/**", "temp/**"]
terse_agent: TerseAgentControls agent output verbosity via instructions injection. Values: “off” (default), “lite”, “full”, “ultra”. Override via LEAN_CTX_TERSE_AGENT env var.
compression_level: CompressionLevelUnified compression level (replaces separate terse_agent + output_density). Values: “off” (default), “lite”, “standard”, “max”. Override via LEAN_CTX_COMPRESSION env var.
compression_aggressiveness: Option<f64>Global compression intensity 0.0 (lossless) – 1.0 (max), mapped onto the
read modes / entropy / IB stages (see core::aggressiveness). None
(default) keeps each mode’s built-in default. Override via the
LEAN_CTX_AGGRESSIVENESS env var or the ctx_read aggressiveness arg.
archive: ArchiveConfigArchive configuration for zero-loss compression.
memory: MemoryPolicyMemory policy (knowledge/lifecycle budgets & thresholds; the episodic and procedural sections are retired and have no effect).
allow_paths: Vec<String>Additional paths allowed by PathJail (absolute). Useful for multi-project workspaces where the jail root is a parent directory. Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
allow_ide_config_dirs: Option<bool>Allow jailed tool access to home-level IDE config dirs (~/.cursor, VS Code,
Cline/Roo, JetBrains, …). Tri-state: None = not asked yet (setup prompts
once), Some(false) = declined, Some(true) = opted in. Those dirs can
expose other agents’ sessions, MCP configs and credentials, so the effective
default is off. ~/.lean-ctx (own data dir) is always allowed. The opt-in
set is registry-derived, covering every supported editor. Override via
LEAN_CTX_ALLOW_IDE_DIRS=1.
extra_roots: Vec<String>Extra project roots for multi-root workspaces. Tools like ctx_tree and ctx_search can scan across all roots in a single call. These paths are automatically added to PathJail’s allow-list. Override via LEAN_CTX_EXTRA_ROOTS env var (path-list separator).
read_only_roots: Vec<String>Read-only roots: sibling subtrees the agent may READ but never WRITE. Reads resolve as if they were extra_roots; every write tool (edit, refactor, handoff/session export, memory compaction) is default-denied inside these paths. Useful for reference repos mounted next to the project. Override via LEAN_CTX_READ_ONLY_ROOTS env var (path-list separator).
allow_symlink_roots: Vec<String>Extra trusted roots OUTSIDE $HOME that lean-ctx may follow when an agent
config file/dir (~/.claude.json, ~/.codex/config.toml, …) is a symlink
pointing there (#596). Empty by default → the strict $HOME-only boundary
stays in force (a planted symlink can never redirect a config write out of
the user’s home, preserving the GL#442 symlink-hijack protection). Add a
parent like /opt/dotfiles only for a location you own and trust. Like
extra_roots, security-sensitive: stripped from untrusted project-local
configs. Override via LEAN_CTX_ALLOW_SYMLINK_ROOTS env var (path-list sep).
content_defined_chunking: boolEnable content-defined chunking (Rabin-Karp) for cache-optimal output ordering. Stable chunks are emitted first to maximize prompt cache hits.
minimal_overhead: boolSkip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead. Override via LEAN_CTX_MINIMAL env var.
Default true (deliberate): initialize-time instructions stay byte-stable
across sessions, which keeps the provider prompt-cache prefix warm (#498)
and holds the fixed per-session cost at the doctor overhead --gate
budget. Session continuity is NOT lost — the wakeup briefing (task,
findings, knowledge) is delivered through the first tool call’s
--- AUTO CONTEXT --- block instead, which only bills when the agent
actually works. Set to false to additionally inject the ACTIVE SESSION
/ PROJECT MEMORY blocks directly into the MCP initialize instructions.
#1540: this key never disables the archive/ephemeral firewall — only
the LEAN_CTX_MINIMAL env escape hatch skips that safety net.
default_true, not default: a field-level #[serde(default)] made
every config.toml without this key read false (bool’s default), so
the documented default true only held for users with no config file
(focus analysis 2026-10-15).
symbol_map_auto: boolOpt-in: substitute long identifiers with short α-codes (+ a §MAP table)
in aggressive reads for projects with >50 source files. Off by default —
the abbreviated form is confusing for editing/refactoring, where the agent
needs the real package and symbol names. Enable for max exploration savings.
structure_first: boolOpt-in: bias auto toward structure-first reads (map) for medium code
files on a cold read. Off by default — interactive sessions keep the
conservative full floor that avoids a follow-up body read. Enable for
phase-isolated harnesses (no warm-session cache payback), where a cold
full read is pure overhead and structure-first reads aid localization.
Override via the LEAN_CTX_STRUCTURE_FIRST env var.
progressive_disclosure: boolProgressive disclosure for first-time reads (LCLM arXiv 2606.09659). When true (default), large files default to compact overviews on first read: - Below progressive_threshold_lines: full content - Below progressive_signatures_max_lines: signatures mode - Above: map (manifest) mode Models can always bypass with explicit mode= or lines= parameters. Override via LEAN_CTX_PROGRESSIVE_DISCLOSURE env var.
progressive_threshold_lines: u32Files with fewer lines than this threshold are always delivered in full. Default: 100 lines.
progressive_signatures_max: u32Files between threshold and this limit get signatures mode. Files above get map (manifest) mode. Default: 500 lines.
auto_mode_learning: boolRetired, no effect (kept so existing configs load; DEPRECATIONS.toml).
The learned auto signals it switched on are gone: auto is always the
deterministic capability-guard and size/task cascade (#498). The
LEAN_CTX_AUTO_MODE_LEARNING env var is ignored as well.
Team content sharing (strategy 2026-10-14, acceptance T07). When false, nothing whose body is content leaves for the hosted Team service: no bus post, work-graph write, knowledge entry or artifact publication. Presence, leases and reads (metadata) keep working. On by default.
journal_enabled: boolEnable human-readable activity journal (~/.lean-ctx/journal.md).
auto_capture: boolOpt-in: auto-persist interesting findings as knowledge facts.
search: HybridConfigHybrid search weights (BM25/dense/candidates).
index: IndexConfigIndex-time file filters (#735): include/exclude globs + gitignore
handling, applied by every index builder via core::index_filter.
skillify: SkillifyConfigSkillify miner settings (#290): codify recurring patterns into rules.
summaries: SummariesConfigAI session-summary settings (#292): periodic, semantically-recallable summaries.
llm: LlmConfigRetired, no effect (kept so existing configs load; DEPRECATIONS.toml
config-llm): LeanCTX calls no model itself.
embedding: EmbeddingConfigSemantic-embedding engine settings (which local ONNX model to use).
shell_hook_disabled: boolDisable shell hook injection (the _lc() function that wraps CLI commands). Override via LEAN_CTX_NO_HOOK env var.
shadow_mode: boolShadow mode (default: true): lean-ctx steers agents to ctx_* MCP tools,
and an explicit hook_mode = "replace" may deny native Grep/Glob.
shadow_mode = false caps every agent at Hybrid, so native tools are
never denied.
Native Shell/Bash coverage is governed separately by shell_hook_mode.
shell_hook_mode: Option<String>Shell hook mode (#1278): how the PreToolUse shell hook treats native Bash/Shell calls.
rewrite(default): rewrite known read/search/list commands to lean-ctx equivalents; anything unrecognized passes through raw.deny: block native shell calls outright so every command goes throughctx_shell(same fail-opens as the deny hook: lean-ctx disabled, MCP daemon dead, explicit shadow-only tool surface).auto: currently equalsrewrite; reserved for a future default flip.
Env override: LEAN_CTX_SHELL_HOOK_MODE. Lives in config.toml, so the
choice survives reinstalls and updates.
prompt_reinject: Option<String>Per-turn tool-routing reinjection (#1288): the UserPromptSubmit hook
emits a one-line additionalContext reminder of the ctx_* routing, so it
post-dates any session-level harness instruction preferring native Bash.
on | off | auto (default: auto = off, since the host’s rules channel
already carries the routing once, A3). Env override:
LEAN_CTX_PROMPT_REINJECT. Costs ~45 tokens per turn when active.
hook_mode: Option<String>Global hook mode override. When set, overrides the per-agent auto-detection.
replace: native Grep/Glob (and non-rewritable shell where the host supports it) denied, lean-ctx MCP is the only path — opt-in onlyhybrid: MCP + shell hooks; native tools keep workingmcp: MCP server only, no hooksauto/unset: Hybrid for hook-capable agents, else MCP (recommend_hook_mode)
tool_surface: Option<String>MCP tool surface mode. Controls how many tools tools/list advertises.
auto(default): shadow-only (ctx_callonly) for hook-covered clients, full lazy-core surface for all others.mcp: always advertise the full lazy-core/profile surface.shadow: always advertise onlyctx_call(requires installed hooks).
debug_log: boolOpt-in (#520): write a human-readable debug log of intercepted MCP tool
calls and hook routing decisions (lean-ctx vs native, with reasons) to
<state_dir>/logs/debug.log. Override via the LEAN_CTX_DEBUG_LOG env var.
shell_activation: ShellActivationControls when the shell hook auto-activates aliases.
agents-only: (Default since #699) Aliases only active when an AI agent env var is detected — transparent in plain human terminals.always: Aliases active in every interactive shell (pre-#699 default).off: Aliases never auto-activate (user must calllean-ctx-onmanually).
Override via LEAN_CTX_SHELL_ACTIVATION env var.
skip_agent_aliases: boolDo not install agent CLI aliases (claude, codex, gemini,
codebuddy) into ~/.zshrc / ~/.bashrc during onboard / setup.
Existing alias blocks are removed when this is toggled on (#754).
Does NOT affect the shell compression hook (_lc()) — use
shell_hook_disabled for that. Orthogonal to shell_activation which
controls when aliases activate, not whether they are installed.
read_redirect: ReadRedirectControls the native-Read → ctx_read redirect hook (#637).
auto: (Default) redirect everywhere except hosts with a native read-before-write guard (Claude Code / CodeBuddy), where the path-swap would break native Write/Edit.on: always redirect (legacy behavior).off: never redirect native Read.
Override via the LEAN_CTX_READ_REDIRECT env var.
read_dedup: ReadDedupControls the PostToolUse native-Read re-read dedup (GL #1140).
auto: (Default) replace only re-reads of unchanged files, and only on guard hosts (Claude Code / CodeBuddy) where the PreToolUse redirect is disabled — the guard-safe way to win the dedup savings back.on: dedup wherever the PostToolUse hook fires.off: never replace a Read result.
Override via the LEAN_CTX_READ_DEDUP env var.
shell_approval: ShellApprovalAsk the user to approve a command the shell allowlist does not name,
when the MCP client supports elicitation (ask, default) or refuse
it without asking (off). Global only. Override via the
LEAN_CTX_SHELL_APPROVAL env var.
execute_allowed_languages: Vec<String>Languages ctx_execute runs without asking (python, javascript,
…): what “Always allow” in its approval prompt writes. Global only.
update_check_disabled: boolDisable the daily version check against api.github.com/repos/yvgude/lean-ctx/releases/latest. Override via LEAN_CTX_NO_UPDATE_CHECK env var.
updates: UpdatesConfig§context: ContextConfigFixed-context budget accounting for doctor overhead / gain (#964).
bm25_max_cache_mb: u64Maximum BM25 cache file size in MB. Indexes exceeding this are quarantined on load and refused on save. Override via LEAN_CTX_BM25_MAX_CACHE_MB env var.
graph_index_max_files: u64Maximum number of files scanned by the lightweight JSON graph index. 0 = unlimited (default). Set >0 to cap for constrained systems.
bm25_max_files: u64Maximum number of files indexed into the BM25 corpus; the semantic index chunks the same corpus (#737), so this bounds semantic coverage too. 0 = unlimited. Default 5000 (MAX_BM25_FILES).
memory_profile: MemoryProfileControls RAM vs feature trade-off. Values: “low”, “balanced” (default), “performance”. Override via LEAN_CTX_MEMORY_PROFILE env var.
memory_cleanup: MemoryCleanupControls how aggressively memory is freed when idle. Values: “shared” (default, 1h TTL), “aggressive” (5 min TTL for low-memory devices). Override via LEAN_CTX_MEMORY_CLEANUP env var.
semantic_mode: SemanticModeHow the code graph uses local semantic backends (language servers, a live JetBrains IDE). Values: “off”, “auto” (default: only backends that are already running), “eager” (may start language servers). Override via LEAN_CTX_SEMANTIC_MODE env var.
max_ram_percent: u8Soft process-RSS target as a percentage of system RAM (default: 5). The guardian throttles and evicts above it, but this is not an OS hard cap. Use a cgroup/container MemoryMax when strict isolation is required. Override via LEAN_CTX_MAX_RAM_PERCENT env var.
mcp_max_rss_mb: u64Per-process RSS target (MB) of each stdio MCP server; the guardian uses
the lower of this and max_ram_percent (default 512, 0 = percent only).
Hosts like the Codex app-server keep one server per loaded thread alive
for days, so a percentage of a large machine’s RAM alone is too loose.
Override via LEAN_CTX_MCP_MAX_RSS_MB env var.
daemon_max_rss_mb: u64Process RSS target (MB) of the background daemon; the guardian uses the
lower of this and max_ram_percent (default 2048, 0 = percent only).
One daemon serves every session and project root on the machine for
days, so a percentage of a large machine’s RAM alone is too loose (#2075).
Override via LEAN_CTX_DAEMON_MAX_RSS_MB env var.
mcp_idle_exit_minutes: u64Exit a stdio MCP server after this many minutes without a tool call
(0 = never, the default). Off by default because some hosts (Codex)
do not restart an exited server: the resumed thread then loses
lean-ctx until the host restarts. Idle servers release their caches
either way (memory_cleanup). Override via LEAN_CTX_MCP_IDLE_EXIT_MINUTES.
max_disk_mb: u64Simplified disk budget (MB). When set and detail values are at defaults, distributes proportionally: archive=25%, bm25=10%, remainder for stores. 0 = disabled (use individual settings). Override via LEAN_CTX_MAX_DISK_MB.
max_staleness_days: u32Auto-purge data older than this many days. 0 = disabled. Flows into archive.max_age_hours and lifecycle idle TTL.
session_retention_days: u32Retention window for explicit session cleanup. This is independent from archive retention and always preserves the newest session per project. Override via LEAN_CTX_SESSION_RETENTION_DAYS.
max_index_threads: usizeCap on the rayon worker threads used by the CPU-heavy index build (call graph etc.). 0 = rayon default (all cores). Set >0 to bound per-instance CPU so a fleet of concurrent sessions can’t saturate the host on startup. Override via LEANCTX_INDEX_THREADS env var.
Controls visibility of token savings footers in tool output. Values: “never” (default), “always” (show on every response), “auto” (legacy compatibility). Override via LEAN_CTX_SAVINGS_FOOTER or LEAN_CTX_SHOW_SAVINGS=1|0 env var.
compression_annotation: CompressionAnnotationControls compression annotation style in savings footers. Values: “quantized” (default, round to 10% buckets), “full” (exact %), “none” (suppress all). Override via LEAN_CTX_COMPRESSION_ANNOTATION env var.
annotation_threshold_pct: u8Minimum savings percentage to emit a footer annotation. Below this threshold, annotations are suppressed (the savings are too small to be worth the token cost). Default: 5 (suppress annotations for savings below 5%).
behavior_nudges: StringIn-band behavior hints (heavy full/raw reads, search→read→search
chains): “auto” (default, one hint per pattern per session) or “off”.
Detections are always counted for tools health, hints or not.
“off” also drops the OUTPUT-HINT line from a task-filtered
ctx_overview: that line shapes the assistant’s answer rather than
reporting a retrieval result, so it belongs to the same switch (#1763).
turn_fresh_limit: usizeMaximum fresh tokens per single tool response (turn budget). 0 = unlimited. Default: 4096. Prevents context bloat from oversized responses. Override via LEAN_CTX_TURN_FRESH_LIMIT env var.
turn_fresh_limit_verbatim: usizeTurn budget for a response the caller explicitly asked to be verbatim
(ctx_read with raw=true or mode="raw"). 0 = unlimited.
Default: 32768. Override via LEAN_CTX_TURN_FRESH_LIMIT_VERBATIM.
The ordinary turn_fresh_limit is a compression backstop for output the
agent did not size itself. A verbatim read is the documented recovery
path out of compression (#1582); capping it at the same 4096 tokens made
that path unreachable for any file above ~16 KB.
project_root: Option<String>Explicit project root override. When set, lean-ctx uses this instead of auto-detection. This prevents accidental home-directory scans when running from $HOME. Override via LEAN_CTX_PROJECT_ROOT env var.
lsp: HashMap<String, String>LSP server overrides. Map language name to custom binary path.
Example: [lsp]\nrust = "/opt/rust-analyzer"\npython = "~/.venvs/main/bin/pylsp"
ide_paths: HashMap<String, Vec<String>>Per-IDE allowed paths. Restricts which directories lean-ctx will scan/index for each IDE.
Example: [ide_paths]\ncursor = ["/home/user/projects/app1"]\ncodex = ["/home/user/codex"]
When set, only these paths are indexed for the matching agent. Global allow_paths still applies.
model_context_windows: HashMap<String, usize>Custom model context window overrides.
Example: [model_context_windows]\n"my-custom-model" = 500000
response_verbosity: ResponseVerbosityControls how much detail tool responses include.
full(default): complete compressed outputheaders_only: metadata line only (path, mode, token count)
Override via LEAN_CTX_RESPONSE_VERBOSITY env var.
bypass_hints: Option<String>Bypass hint mode. When agents use native Read/Grep instead of lean-ctx tools, a hint is appended to the next tool response. Values: “on” (default), “off”, “aggressive” (hint on every call, no cooldown). Override via LEAN_CTX_BYPASS_HINTS env var.
cache_policy: Option<String>Cache policy for ctx_read. Controls behavior on cache hits. Values: “aggressive” (default, 13-tok stubs + compaction-aware reset), “safe” (delivers map instead of stub), “off” (no caching, always disk read). Override via LEAN_CTX_CACHE_POLICY env var.
cache_max_tokens: usizeToken budget for the in-memory ctx_read cache. When the cached total
plus an incoming read would exceed this, lean-ctx evicts the least-valuable
entries immediately (RRF: recency × frequency × size) so the read always
proceeds — eviction is never deferred to the staleness TTL. 0 uses the
built-in default (2M). LEAN_CTX_CACHE_MAX_TOKENS env var overrides this.
boundary_policy: BoundaryPolicyCross-project boundary policy. Controls whether cross-project search/import is allowed and whether access is audited.
secret_detection: SecretDetectionConfig§sensitivity: SensitivityConfigPer-item sensitivity model with a uniform policy floor (#212).
Disabled by default → fully no-op until sensitivity.enabled = true.
context_gateway: ContextGatewayConfigContext Gateway admission ([context_gateway]): built-in detectors
that run on every governed source before caching or compression.
On by default. Global-only: a project-local file cannot weaken it.
load_failure: Option<ConfigLoadFailure>Set by the loader when the global config.toml exists but could not be
read or parsed, so this snapshot holds built-in defaults instead of the
operator’s settings. It travels with exactly this Config value: an
earlier failed snapshot stays marked after a later successful load.
Never read from or written to a file.
a2a_accept_untrusted_signers: boolAccept A2A handoff bundles and context packages whose signature
verifies but whose signer key is not anchored in trusted-signers.toml
(GHSA-gvg8-285q-m62g). Off by default: anyone can mint a key, so an
untrusted signature proves nothing about the sender. Global-only
(never merged from project-local config).
mcp_import_allow_unverified: boolLet MCP tools (ctx_handoff import, ctx_pack import) import handoff
bundles and context packages that are unsigned or signed by a key not
anchored in trusted-signers.toml (GHSA-gvg8-285q-m62g). A tool
argument cannot grant this — the model could set it under prompt
injection. Off by default; global-only. CLI imports keep their own
human opt-in (--allow-unsigned).
gateway: GatewayConfigMCP Tool-Catalog Gateway (#210): aggregate + query-route downstream MCP
servers. Global-only (never merged from project-local config) and a full
no-op until gateway.enabled = true.
gateway_server: GatewayServerConfigSelf-hosted org gateway server ([gateway_server], enterprise#20):
deployment parameters for the usage cockpit — seat count for the
org-wide projection, display label, and the central admin API the local
cockpit may read from. All optional; absent = local-only behavior.
enterprise: EnterpriseConfigEnterprise Suite connection ([enterprise]): connects this Runtime to
a LeanCTX Enterprise Gateway for economics tracking and model routing.
hook_binary: Option<String>Verbatim binary path/expression for generated agent-hook commands
(#708). Users who sync agent settings (~/.claude/settings.json, …)
across machines with different usernames need an env-based form like
$HOME/.local/bin/lean-ctx — agent hosts run hook commands through a
shell, which expands it. When set (env LEAN_CTX_HOOK_BINARY wins,
then this key), every hook writer emits the value verbatim instead of
the machine-absolute exe path, so init/doctor --fix/update stop
rewriting synced files into sync ping-pong. Autostart plists/services
and daemon spawns are NOT affected — launchd/systemd do not expand
shell variables, so those keep the real absolute path. Empty (default)
= automatic absolute-path resolution (#367).
path_jail: Option<bool>Disable PathJail entirely by setting path_jail = false in config.toml.
Useful in container/Docker environments where the sandbox is the boundary.
(The former LEAN_CTX_NO_JAIL=1 env override was removed in v3.7.3.)
path_jail_scope: Option<String>What the enforced jail admits besides the project + allow-lists:
projects (default — every project below $HOME readable, writes only
in the session’s project), home (all of $HOME read and write, except
dot entries, ~/Library, ~/AppData) or project. See core::pathjail_scope.
sandbox_level: u8Sandbox level for code execution (ctx_exec). 0 = subprocess only (current), 1 = OS-level restriction (Seatbelt/Landlock). Override via LEAN_CTX_SANDBOX_LEVEL env var.
reference_results: boolWhen true, large tool outputs (>4000 chars) are stored as references and a short URI is returned instead of the full content. Override via LEAN_CTX_REFERENCE_RESULTS env var.
agent_token_budget: usizeDefault per-agent token budget. 0 means unlimited. Override per-agent via ctx_session or programmatically.
shell_allowlist: Vec<String>Optional shell command allowlist. When non-empty, only commands whose base binary
is in this list are permitted by ctx_shell. Empty = disable allowlist (allow all).
Default includes common dev tools. Set to [] to disable.
Override via LEAN_CTX_SHELL_ALLOWLIST env var (comma-separated).
shell_allowlist_extra: Vec<String>Extra commands MERGED on top of the effective shell_allowlist without replacing
the defaults. Setting shell_allowlist replaces the whole built-in list (a common
footgun); entries here are purely additive, which is what lean-ctx allow <cmd>
writes. Only applied in restricted mode (when the base allowlist is non-empty).
shell_strict_mode: boolWhen true, block command substitution ($(), backticks) and process substitution (<(), >()) in shell arguments. When false (default), only warn via tracing. Default false preserves backward compatibility — set true for maximum security.
shell_allowlist_subcommand_scoping: boolGH #1419 follow-up: scope a multi-word shell_allowlist/
shell_allowlist_extra entry to the exact subcommand/prefix it names
("git status" no longer grants the whole git binary). Default
true (the secure grammar); set false to fall back to the old
base-binary-only matching as a compat/rollback path. Trust-gated: an
untrusted workspace cannot weaken this via a local override. Override
via LEAN_CTX_SHELL_ALLOWLIST_SUBCOMMAND_SCOPING.
shell_security: Option<String>Shell-security mode for ctx_shell / lean-ctx -c command gating (GL #788):
enforce (default, secure), warn (run checks, log violations, never
block) or off (skip the allowlist + dangerous-pattern blocks entirely —
a deliberate opt-out; compression stays active). Override via
LEAN_CTX_SHELL_SECURITY. None resolves to enforce.
shell_timeout_secs: Option<u64>Default shell-command timeout in seconds for normal commands. None
resolves to the built-in 2-minute default; heavy builds/tests use
Config::shell_heavy_timeout_secs. Override via
LEAN_CTX_SHELL_TIMEOUT_SECS (LEAN_CTX_SHELL_TIMEOUT_MS still wins over
both, in milliseconds).
shell_heavy_timeout_secs: Option<u64>Shell-command timeout in seconds for heavy commands (cargo build/test,
make, docker build, git commit/push, …). None resolves to the built-in
10-minute ceiling. Override via LEAN_CTX_SHELL_HEAVY_TIMEOUT_SECS.
shell_heavy_prefixes: Vec<String>Extra command prefixes that get the heavy timeout ceiling. Merged with
the built-in list. Useful for project-specific long-running scripts.
Example: shell_heavy_prefixes = ["python3 ", "./scripts/"]
shell_allow_writes: boolWhen true, ctx_shell accepts shell file-write redirects (>, >>,
tee, heredoc-to-file, curl -o, wget default mode). Default false —
the native Write/Edit tool is preferred. Opt-in for power users who want
classic shell syntax; the real command gating (allowlist,
dangerous-pattern and interpreter-eval blocks) still applies. Override
via LEAN_CTX_SHELL_ALLOW_WRITES=1.
write_allow_paths: Vec<String>Absolute paths where shell redirects and tee may capture output.
Empty uses the operating system’s temporary directories. Project files
remain denied even when a configured path overlaps the project root.
shell_allow_inline_scripts: bool#814: opt-in to allow python3 -c, node -e, etc. in ctx_shell.
Default false — inline code is blocked because it leaves no auditable
artifact. Override via LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS=1.
setup: SetupConfigSetup behavior: controls what gets injected during setup and updates.
solution: SolutionConfig§governor: GovernorConfigClaude Code governor rule modes ([governor]; env overrides win).
provenance: ProvenanceConfig§cross_agent: CrossAgentConfigImplementations§
Source§impl Config
impl Config
Sourcepub fn path() -> Option<PathBuf>
pub fn path() -> Option<PathBuf>
Returns the path to the global config file ($XDG_CONFIG_HOME/lean-ctx/config.toml).
Resolves the canonical config category without creating directories or repairing permissions; existing single-dir installations retain their path.
Sourcepub fn missing_config_path() -> Option<PathBuf>
pub fn missing_config_path() -> Option<PathBuf>
Some(path) when the global config the runtime resolves does not exist,
so lean-ctx is silently on built-in defaults. None when a config file is
present (or HOME is unresolvable).
The directory is layout-dependent (XDG ~/.config/lean-ctx vs legacy
~/.lean-ctx vs $LEAN_CTX_DATA_DIR) and an MCP client may launch the
server in a sandbox/container with a different $HOME. An edit made to a
different config.toml than this one is silently ignored; the block
messages use this to say so out loud over MCP, where the stderr path is
invisible (#540).
Sourcepub fn local_path(project_root: &str) -> PathBuf
pub fn local_path(project_root: &str) -> PathBuf
Returns the path to the project-local config override file.
Sourcepub fn find_project_root() -> Option<String>
pub fn find_project_root() -> Option<String>
Resolves the active project root (env override → session → git toplevel →
cwd), cached for the process. Exposed crate-wide so workspace-trust and the
CLI agree with config loading on which directory a .lean-ctx.toml
belongs to (GH security audit, finding 4).
Inside a request the request’s bound project is the root, uncached: a
server serving several projects must apply each one’s own
.lean-ctx.toml and trust, never the first one it happened to resolve
(AP04-G3).
Sourcepub fn load() -> Self
pub fn load() -> Self
Loads config from disk with caching, merging global + project-local overrides.
The cache is keyed on a content hash of the global + project-local
files, not their mtime. mtime-only invalidation silently served a stale
Config whenever a content edit preserved the mtime (coarse filesystem
mtime resolution, cp -p, atomic save-then-rename, two edits within the
same second). A long-lived MCP server then kept the old value (e.g.
path_jail) while a fresh lean-ctx doctor process — with an empty
cache — saw the new one (#406). Config files are tiny, so reading +
hashing them on every load is negligible and guarantees liveness.
Sourcepub fn generation() -> u64
pub fn generation() -> u64
Shared-ownership variant of load: returns the cached
Arc<Config> so the per-dispatch hot path bumps a refcount instead of
deep-cloning the whole struct. Liveness is identical to load — the
global and project-local files are still read and content-hashed on
every call (#406); only the cache payload became an Arc, so a cache
hit is a cheap Arc::clone.
The config generation: it advances whenever a load sees a changed
config (content, project, profile or trust), so a cache derived from
the config can key on it instead of re-reading the config (#2195).
pub fn load_arc() -> Arc<Self> ⓘ
Sourcepub fn load_for_project_root(project_root: &str) -> Self
pub fn load_for_project_root(project_root: &str) -> Self
Global config merged with the .lean-ctx.toml of project_root — not
of the process’s own project. A daemon serving several repositories
must evaluate per-project settings (and their workspace trust) against
the project being processed. Uncached; same merge + trust rules as
load_arc.
Sourcepub fn load_global() -> Self
pub fn load_global() -> Self
Loads ONLY the global config file — never merging project-local
.lean-ctx.toml overrides, and bypassing the in-memory cache. Every
PERSIST path must use this (or Config::update_global): Config::load
folds per-project overrides into the struct, and Config::save writes
the whole struct back to the GLOBAL file — so a load → mutate → save
round-trip silently leaks per-project values (and, historically, reset
customized keys) into the global config (#443). Reading global-only makes
the save leak-free by construction.
Sourcepub fn try_load_global() -> Result<Self, LeanCtxError>
pub fn try_load_global() -> Result<Self, LeanCtxError>
Strict variant of Config::load_global: an unreadable or unparseable
global config is an error instead of silently becoming the defaults.
Consent-gated paths (telemetry send) must use this so a corrupt file
never turns into default-on behaviour.
Source§impl Config
impl Config
Sourcepub fn crush_verbatim_json_enabled(&self) -> bool
pub fn crush_verbatim_json_enabled(&self) -> bool
Whether opt-in lossless JSON crushing of verbatim data commands (#936) is
active. LEAN_CTX_CRUSH_VERBATIM_JSON (any value) wins, then the
crush_verbatim_json config flag, else false.
Sourcepub fn resolved_proxy_bind_host(&self) -> IpAddr
pub fn resolved_proxy_bind_host(&self) -> IpAddr
Effective proxy bind address (gateway mode, enterprise#8). Precedence:
LEAN_CTX_PROXY_BIND_HOST env > proxy_bind_host config > loopback.
The value must parse as an IP address; anything else (including a blank)
resolves to 127.0.0.1 — a typo can only ever narrow exposure, never
silently open the listener.
Sourcepub fn rules_scope_effective(&self) -> RulesScope
pub fn rules_scope_effective(&self) -> RulesScope
Returns the effective rules scope, preferring env var over config file.
Sourcepub fn rules_injection_effective(&self) -> RulesInjection
pub fn rules_injection_effective(&self) -> RulesInjection
Returns the effective rules injection mode, preferring env var over config.
Default is Shared (zero-config discovery via a CLAUDE.md/CODEBUDDY.md/AGENTS.md block).
Sourcepub fn declines_rule_steering(&self) -> bool
pub fn declines_rule_steering(&self) -> bool
#1754: has the user declined lean-ctx steering their agent?
rules_injection = off is the #1599 rule — off means off, on every
channel, including text lean-ctx appends inside a tool result. Under
Off such a reminder is also unclearable: inject_all_rules
early-returns, and the lean-ctx setup it suggests removes the rules
block rather than writing it, so the reminder returns next session.
An explicit setup.auto_inject_rules = false says the same thing in the
setup section. None (auto — rules simply not present yet) is not a
refusal and still gets the reminder.
Sourcepub fn dashboard_cache_hit_rate(&self) -> Option<f64>
pub fn dashboard_cache_hit_rate(&self) -> Option<f64>
Provider prompt-cache hit rate for net-of-injection (#1104). Returns the configured value or None (caller picks the default).
Sourcepub fn hook_mode_override(&self) -> Option<HookMode>
pub fn hook_mode_override(&self) -> Option<HookMode>
Returns the user-configured hook mode override, or None for auto-detect.
Env var LEAN_CTX_HOOK_MODE takes priority over config.
Sourcepub fn permission_inheritance_effective(&self) -> PermissionInheritance
pub fn permission_inheritance_effective(&self) -> PermissionInheritance
Returns the effective permission-inheritance mode, preferring the
LEAN_CTX_PERMISSION_INHERITANCE env var over config. Default is Off.
Accepts on/true/1 as enabled.
Sourcepub fn dedicated_session_context_active(&self) -> bool
pub fn dedicated_session_context_active(&self) -> bool
True when lean-ctx should inject its rules via each agent’s dedicated, non-polluting auto-load path and global rules are in scope.
Gates the Claude/Codex SessionStart additionalContext summary: it
stands in for the (now-skipped) shared CLAUDE.md/CODEBUDDY.md/AGENTS.md block, so it
only fires when injection is Dedicated and the scope isn’t project-only.
Sourcepub fn disabled_tools_effective(&self) -> Vec<String>
pub fn disabled_tools_effective(&self) -> Vec<String>
Returns the effective disabled tools list, preferring env var over config
file. When prefer_native_editor is active, the lean-ctx edit tools are
folded in so they are hidden from list_tools (#454).
Sourcepub fn prefer_native_editor_effective(&self) -> bool
pub fn prefer_native_editor_effective(&self) -> bool
Whether lean-ctx edit operations are disabled in favour of the host’s
native editor (#454). LEAN_CTX_PREFER_NATIVE_EDITOR wins over config.
Sourcepub fn max_index_threads_effective(&self) -> usize
pub fn max_index_threads_effective(&self) -> usize
Cap on the rayon index-build worker threads. LEANCTX_INDEX_THREADS wins
over config; 0 means “no cap” — rayon’s all-cores default is kept.
Sourcepub fn edit_tool_blocked(&self, name: &str) -> bool
pub fn edit_tool_blocked(&self, name: &str) -> bool
Whether name is a lean-ctx edit operation that must be blocked from
dispatch (direct and via ctx_call) when Self::prefer_native_editor_effective
is set (#454). Read/search/shell/memory tools are never blocked.
Sourcepub fn minimal_overhead_effective(&self) -> bool
pub fn minimal_overhead_effective(&self) -> bool
Returns true if minimal overhead is enabled via env var or config.
Sourcepub fn minimal_escape_hatch() -> bool
pub fn minimal_escape_hatch() -> bool
The LEAN_CTX_MINIMAL env var is the documented do-not-touch-anything
escape hatch (3.9.19 triage incident): only IT may skip the pipeline’s
archive + ephemeral-firewall safety net. The minimal_overhead config
key (default true) trims MCP instruction overhead only and must never
disable archiving (#1540).
Sourcepub fn structure_first_effective(&self) -> bool
pub fn structure_first_effective(&self) -> bool
Returns true if structure-first auto reads are enabled.
The LEAN_CTX_STRUCTURE_FIRST env var wins over the config field, and
accepts the usual truthy/falsy spellings so a harness can flip it per run
(LEAN_CTX_STRUCTURE_FIRST=0 forces it off even if config enables it).
Sourcepub fn turn_fresh_limit_effective(&self) -> usize
pub fn turn_fresh_limit_effective(&self) -> usize
Effective turn budget (fresh token limit per response). 0 = unlimited.
Sourcepub fn turn_fresh_limit_verbatim_effective(&self) -> usize
pub fn turn_fresh_limit_verbatim_effective(&self) -> usize
Effective turn budget for an explicitly verbatim response (#1582).
0 = unlimited. Never below turn_fresh_limit_effective(): raising the
ordinary budget above the verbatim one must not make raw=true deliver
less than a compressed read of the same file. An unlimited ordinary
budget stays unlimited here.
Sourcepub fn progressive_disclosure_effective(&self) -> bool
pub fn progressive_disclosure_effective(&self) -> bool
Whether progressive disclosure is active. Default true. The env var
LEAN_CTX_PROGRESSIVE_DISCLOSURE overrides the config field.
Sourcepub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool
pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool
Returns true if minimal overhead should be enabled for this MCP client.
This is a superset of minimal_overhead_effective():
LEAN_CTX_OVERHEAD_MODE=minimalforces minimal overheadLEAN_CTX_OVERHEAD_MODE=fulldisables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)- In auto mode (default), certain low-context clients/models are treated as minimal to prevent large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
Sourcepub fn shell_hook_disabled_effective(&self) -> bool
pub fn shell_hook_disabled_effective(&self) -> bool
Returns true if shell hook injection is disabled via env var or config.
Sourcepub fn shell_activation_effective(&self) -> ShellActivation
pub fn shell_activation_effective(&self) -> ShellActivation
Returns the effective shell activation mode (env var > config > default).
Sourcepub fn shell_allow_writes_effective(&self) -> bool
pub fn shell_allow_writes_effective(&self) -> bool
Returns true if ctx_shell may accept shell file-write redirects.
LEAN_CTX_SHELL_ALLOW_WRITES (1/true/yes/on) overrides
config.toml. The real command gating still applies either way.
Sourcepub fn shell_write_allow_paths_effective(&self) -> Vec<String>
pub fn shell_write_allow_paths_effective(&self) -> Vec<String>
Returns the effective paths where shell output capture may write. Empty configuration intentionally falls back to OS temp directories.
Sourcepub fn shell_allow_inline_scripts_effective(&self) -> bool
pub fn shell_allow_inline_scripts_effective(&self) -> bool
#814: returns true if ctx_shell may accept inline interpreter scripts
(python3 -c "...", node -e "...", etc.).
LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS (1/true/yes/on) overrides
config.toml. The real command gating (allowlist) still applies.
Sourcepub fn update_check_disabled_effective(&self) -> bool
pub fn update_check_disabled_effective(&self) -> bool
Returns true if the daily update check is disabled via env var or config.
pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String>
Sourcepub fn default_tool_categories_effective(&self) -> Vec<String>
pub fn default_tool_categories_effective(&self) -> Vec<String>
Returns the effective set of default tool categories. Priority: LCTX_DEFAULT_CATEGORIES env var > config.toml > hardcoded default.
Sourcepub fn tool_profile_effective(&self) -> ToolProfile
pub fn tool_profile_effective(&self) -> ToolProfile
Returns the effective tool profile. Priority: LEAN_CTX_TOOL_PROFILE env > config tool_profile > config tools_enabled > active persona’s tool surface > power.
Explicit settings win (backward compatible); when none are set, the
active persona supplies the tool surface (the coding default resolves
to power, so existing installs are unaffected).
Sourcepub fn sensitivity_effective(&self) -> SensitivityConfig
pub fn sensitivity_effective(&self) -> SensitivityConfig
The [sensitivity] config with the active persona’s floor folded in
(persona-spec-v1). Enforcement chokepoints use this instead of the raw
field so a persona like lead-gen (sensitivity_floor = "confidential")
protects PII out of the box. The coding default (public) passes the
config through unchanged.
Sourcepub fn no_degrade_effective(&self) -> bool
pub fn no_degrade_effective(&self) -> bool
Returns true if all automatic read-mode degradation is disabled.
Checks LCTX_NO_DEGRADE env var first, then config.toml field.
Sourcepub fn delta_explicit_effective(&self) -> bool
pub fn delta_explicit_effective(&self) -> bool
Returns true if explicit full/lines:N-M re-reads of
cached-but-changed files should be served as deltas (mode=diff)
instead of re-emitting full content.
Checks the LCTX_DELTA_EXPLICIT env var first, then the config.toml
field. Unlike a presence-only knob, an explicit 0/false in the env
forces the feature OFF even when the config field is true, so the env
can fully override config in both directions.
Sourcepub fn max_disk_mb_effective(&self) -> u64
pub fn max_disk_mb_effective(&self) -> u64
Effective max_disk_mb from env or config.
Sourcepub fn mcp_max_rss_mb_effective(&self) -> u64
pub fn mcp_max_rss_mb_effective(&self) -> u64
Effective per-process RSS target of a stdio MCP server (MB) from env or config.
Sourcepub fn daemon_max_rss_mb_effective(&self) -> u64
pub fn daemon_max_rss_mb_effective(&self) -> u64
Effective process RSS target of the background daemon (MB) from env or config.
Sourcepub fn mcp_idle_exit_minutes_effective(&self) -> u64
pub fn mcp_idle_exit_minutes_effective(&self) -> u64
Effective idle-exit window of a stdio MCP server (minutes, 0 = never).
Sourcepub fn max_staleness_days_effective(&self) -> u32
pub fn max_staleness_days_effective(&self) -> u32
Effective max_staleness_days from env or config.
Sourcepub fn session_retention_days_effective(&self) -> u32
pub fn session_retention_days_effective(&self) -> u32
Effective retention window for explicit session cleanup, independent of the archive staleness policy.
Sourcepub fn context_budget_tokens_effective(&self) -> usize
pub fn context_budget_tokens_effective(&self) -> usize
Effective fixed-context budget (tokens) from env or config (#964). 0
(env or config) disables the warning; otherwise the per-session footprint
is checked against this in doctor overhead and gain.
Sourcepub fn proactive_expansion_effective(&self) -> bool
pub fn proactive_expansion_effective(&self) -> bool
Whether later tool calls may receive matching CCR context.
Sourcepub fn proactive_expansion_budget_tokens_effective(&self) -> usize
pub fn proactive_expansion_budget_tokens_effective(&self) -> usize
Per-response token budget for proactive CCR expansion.
Sourcepub fn proactive_expansion_threshold_effective(&self) -> f64
pub fn proactive_expansion_threshold_effective(&self) -> f64
Normalized BM25 score threshold for proactive CCR expansion.
Sourcepub fn proactive_expansion_max_age_secs_effective(&self) -> u64
pub fn proactive_expansion_max_age_secs_effective(&self) -> u64
Maximum archive age considered for proactive expansion.
Sourcepub fn archive_max_disk_mb_effective(&self) -> u64
pub fn archive_max_disk_mb_effective(&self) -> u64
Archive max_disk_mb derived from simplified max_disk_mb if the detail value is still at its default. Explicit overrides take priority.
Sourcepub fn archive_max_age_hours_effective(&self) -> u64
pub fn archive_max_age_hours_effective(&self) -> u64
Archive max_age_hours derived from max_staleness_days if the detail value is still at its default. Explicit overrides take priority.
Sourcepub fn gateway_store_max_mb_effective(&self) -> u64
pub fn gateway_store_max_mb_effective(&self) -> u64
Effective on-disk ceiling (MB) of the Context Gateway evidence store
(<data>/gateway: receipts, trace sidecars, observations, egress
records). 0 means no ceiling. Retention keeps the store below it
(receipt_store::retention); a new receipt is refused only while the
store stays full (receipt_store::capacity, G09).
Priority: LEAN_CTX_GATEWAY_STORE_MAX_MB › max_disk_mb budget (10%) ›
receipt_store::capacity::DEFAULT_STORE_MB.
Deliberately not a [context_gateway] key: that table is hashed into
every receipt’s policy digest, and a storage ceiling decides no
admission.
Sourcepub fn bm25_max_cache_mb_effective(&self) -> u64
pub fn bm25_max_cache_mb_effective(&self) -> u64
Effective on-disk ceiling (MB) for the persisted BM25 index. Single source
of truth for save/load, cache prune, and the doctor health check.
Priority: explicit bm25_max_cache_mb › max_disk_mb budget (10%) ›
generous default (DEFAULT_BM25_PERSIST_MB). The default is decoupled
from the RAM profile so large repos persist instead of rebuilding forever
(issue #249).
Source§impl Config
impl Config
Sourcepub fn update_global<F>(f: F) -> Result<Self, LeanCtxError>where
F: FnOnce(&mut Self),
pub fn update_global<F>(f: F) -> Result<Self, LeanCtxError>where
F: FnOnce(&mut Self),
Safely mutate and persist the GLOBAL config. Reads the global file only
(no project-local merge), applies f, then writes minimally. Refuses
(returns Err) when the file exists but is unparseable, so a typo can
never clobber a customized config (#443). Returns the saved Config.
This is the canonical persistence entry point: prefer it over
Config::load() followed by save(), which leaks project-local
overrides into the global file.
Sourcepub fn try_update_global<F>(f: F) -> Result<Self, LeanCtxError>
pub fn try_update_global<F>(f: F) -> Result<Self, LeanCtxError>
Fallible mutation using the same preserving writer; refusal never saves.
Sourcepub fn save(&self) -> Result<(), LeanCtxError>
pub fn save(&self) -> Result<(), LeanCtxError>
Persists the current config to the global config file.
Preserves user comments, formatting, and unknown keys, keeps the file
minimal (defaults that were never set on disk stay implicit), and writes
atomically with a .bak backup so customizations are always recoverable.
Source§impl Config
impl Config
Sourcepub fn provenance() -> ConfigProvenance
pub fn provenance() -> ConfigProvenance
Snapshot the provenance of the editable settings (GH #450).
Reads the same sources as Config::load (honoring the #356 TCC guard
for the project-local file) plus the live environment, so the result
matches what a fresh load() would resolve. Pure: it never mutates the
config cache or writes to disk.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Config
impl<'de> Deserialize<'de> for Config
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Auto Trait Implementations§
impl Forget for Config
impl Freeze for Config
impl Move for Config
impl RefUnwindSafe for Config
impl Send for Config
impl Sync for Config
impl Unpin for Config
impl UnsafeUnpin for Config
impl UnwindSafe for Config
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
impl<A, B, T> HttpServerConnExec<A, B> for Twhere
B: Body,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more