Skip to main content

zeph_core/agent/state/
mod.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Sub-struct definitions for the `Agent` struct.
5//!
6//! Each struct groups a related cluster of `Agent` fields.
7//! All types are `pub(crate)` — visible only within the `zeph-core` crate.
8//!
9//! `MemoryState` is decomposed into four concern-separated sub-structs, each in its own file:
10//!
11//! - [`MemoryPersistenceState`] — `SQLite` handles, conversation IDs, recall budgets, autosave
12//! - [`MemoryCompactionState`] — summarization thresholds, shutdown summary, digest, strategy
13//! - [`MemoryExtractionState`] — graph config, RPE router, document config, semantic labels
14//! - [`MemorySubsystemState`] — `TiMem`, `autoDream`, `MagicDocs`, microcompact
15
16pub(crate) mod compaction;
17pub(crate) mod extraction;
18pub(crate) mod persistence;
19pub(crate) mod subsystems;
20
21pub(crate) use self::compaction::MemoryCompactionState;
22pub(crate) use self::extraction::MemoryExtractionState;
23pub(crate) use self::persistence::MemoryPersistenceState;
24pub(crate) use self::subsystems::MemorySubsystemState;
25
26use std::collections::{HashMap, HashSet, VecDeque};
27use std::path::PathBuf;
28use std::sync::Arc;
29
30use parking_lot::RwLock;
31use std::time::Instant;
32
33use tokio::sync::{Notify, mpsc, watch};
34use tokio::task::JoinHandle;
35use tokio_util::sync::CancellationToken;
36use zeph_llm::any::AnyProvider;
37use zeph_llm::provider::Message;
38use zeph_llm::stt::SpeechToText;
39
40use crate::config::{ProviderEntry, SecurityConfig, SkillPromptMode, TimeoutConfig};
41use crate::config_watcher::ConfigEvent;
42use crate::context::EnvironmentContext;
43use crate::cost::CostTracker;
44use crate::file_watcher::FileChangedEvent;
45use crate::instructions::{InstructionBlock, InstructionEvent, InstructionReloadState};
46use crate::metrics::MetricsSnapshot;
47use crate::vault::Secret;
48use zeph_config;
49use zeph_memory::TokenCounter;
50use zeph_sanitizer::ContentSanitizer;
51use zeph_sanitizer::quarantine::QuarantinedSummarizer;
52use zeph_skills::matcher::SkillMatcherBackend;
53use zeph_skills::registry::SkillRegistry;
54use zeph_skills::watcher::SkillEvent;
55
56use super::message_queue::QueuedMessage;
57
58/// Coordinator struct holding four concern-separated sub-structs for memory management.
59///
60/// Each sub-struct groups fields by a single concern:
61/// - [`persistence`](MemoryPersistenceState) — `SQLite` handles, conversation IDs, recall budgets
62/// - [`compaction`](MemoryCompactionState) — summarization thresholds, shutdown summary, digest
63/// - [`extraction`](MemoryExtractionState) — graph config, RPE router, semantic labels
64/// - [`subsystems`](MemorySubsystemState) — `TiMem`, `autoDream`, `MagicDocs`, microcompact
65#[derive(Default)]
66pub(crate) struct MemoryState {
67    /// `SQLite` handles, conversation IDs, recall budgets, and autosave policy.
68    pub(crate) persistence: MemoryPersistenceState,
69    /// Summarization thresholds, shutdown summary, digest config, and context strategy.
70    pub(crate) compaction: MemoryCompactionState,
71    /// Graph extraction config, RPE router, document config, and semantic label configs.
72    pub(crate) extraction: MemoryExtractionState,
73    /// `TiMem`, `autoDream`, `MagicDocs`, and microcompact subsystem state.
74    pub(crate) subsystems: MemorySubsystemState,
75}
76
77pub(crate) struct SkillState {
78    pub(crate) registry: Arc<RwLock<SkillRegistry>>,
79    /// Per-turn trust snapshot written by `prepare_context` after `build_skill_trust_map`.
80    /// Shared with `SkillInvokeExecutor` so it can resolve trust without hitting `SQLite`
81    /// on every tool call. Refreshed once per turn — stale by at most one turn.
82    pub(crate) trust_snapshot: Arc<RwLock<HashMap<String, zeph_common::SkillTrustLevel>>>,
83    pub(crate) skill_paths: Vec<PathBuf>,
84    pub(crate) managed_dir: Option<PathBuf>,
85    pub(crate) trust_config: crate::config::TrustConfig,
86    pub(crate) matcher: Option<SkillMatcherBackend>,
87    pub(crate) max_active_skills: usize,
88    pub(crate) disambiguation_threshold: f32,
89    pub(crate) min_injection_score: f32,
90    pub(crate) embedding_model: String,
91    pub(crate) skill_reload_rx: Option<mpsc::Receiver<SkillEvent>>,
92    /// Resolves the current set of per-plugin skill dirs at reload time.
93    ///
94    /// Called inside `reload_skills()` so that plugins installed via `/plugins add` after
95    /// startup are discovered on the next watcher event without restarting the agent.
96    pub(crate) plugin_dirs_supplier: Option<Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>>,
97    pub(crate) active_skill_names: Vec<String>,
98    pub(crate) last_skills_prompt: String,
99    pub(crate) prompt_mode: SkillPromptMode,
100    /// Custom secrets available at runtime: key=hyphenated name, value=secret.
101    pub(crate) available_custom_secrets: HashMap<String, Secret>,
102    pub(crate) cosine_weight: f32,
103    pub(crate) hybrid_search: bool,
104    pub(crate) bm25_index: Option<zeph_skills::bm25::Bm25Index>,
105    pub(crate) two_stage_matching: bool,
106    /// Threshold for confusability warnings (0.0 = disabled).
107    pub(crate) confusability_threshold: f32,
108    /// `SkillOrchestra` RL routing head. `Some` when `rl_routing_enabled = true` and
109    /// weights are loaded or initialized. `None` when RL routing is disabled.
110    pub(crate) rl_head: Option<zeph_skills::rl_head::RoutingHead>,
111    /// Blend weight for RL routing: `final = (1-rl_weight)*cosine + rl_weight*rl_score`.
112    pub(crate) rl_weight: f32,
113    /// Skip RL blending for the first N updates (cold-start warmup).
114    pub(crate) rl_warmup_updates: u32,
115    /// Directory where `/skill create` writes generated skills.
116    /// Defaults to `managed_dir` if `None`.
117    pub(crate) generation_output_dir: Option<std::path::PathBuf>,
118    /// Provider name for `/skill create` generation. Empty = primary.
119    pub(crate) generation_provider_name: String,
120}
121
122pub(crate) struct McpState {
123    pub(crate) tools: Vec<zeph_mcp::McpTool>,
124    pub(crate) registry: Option<zeph_mcp::McpToolRegistry>,
125    pub(crate) manager: Option<std::sync::Arc<zeph_mcp::McpManager>>,
126    pub(crate) allowed_commands: Vec<String>,
127    pub(crate) max_dynamic: usize,
128    /// Receives elicitation requests from MCP server handlers during tool execution.
129    /// When `Some`, the agent loop must process these concurrently with tool result awaiting
130    /// to avoid deadlock (tool result waits for elicitation, elicitation waits for agent loop).
131    pub(crate) elicitation_rx: Option<tokio::sync::mpsc::Receiver<zeph_mcp::ElicitationEvent>>,
132    /// Shared with `McpToolExecutor` so native `tool_use` sees the current tool list.
133    ///
134    /// Two methods write to this `RwLock` — ordering matters:
135    /// - `sync_executor_tools()`: writes the **full** `self.tools` set.
136    /// - `apply_pruned_tools()`: writes the **pruned** subset (used after pruning).
137    ///
138    /// Within a turn, `sync_executor_tools` must always run **before**
139    /// `apply_pruned_tools`.  The normal call order guarantees this: tool-list
140    /// change events call `sync_executor_tools` (inside `check_tool_refresh`,
141    /// `handle_mcp_add`, `handle_mcp_remove`), and pruning runs later inside
142    /// `rebuild_system_prompt`.  See also: `apply_pruned_tools`.
143    pub(crate) shared_tools: Option<Arc<RwLock<Vec<zeph_mcp::McpTool>>>>,
144    /// Receives full flattened tool list after any `tools/list_changed` notification.
145    pub(crate) tool_rx: Option<tokio::sync::watch::Receiver<Vec<zeph_mcp::McpTool>>>,
146    /// Per-server connection outcomes from the initial `connect_all()` call.
147    pub(crate) server_outcomes: Vec<zeph_mcp::ServerConnectOutcome>,
148    /// Per-message cache for MCP tool pruning results (#2298).
149    ///
150    /// Reset at the start of each user turn and whenever the MCP tool list
151    /// changes (via `tools/list_changed`, `/mcp add`, or `/mcp remove`).
152    pub(crate) pruning_cache: zeph_mcp::PruningCache,
153    /// Dedicated provider for MCP tool pruning LLM calls.
154    ///
155    /// `None` means fall back to the agent's primary provider.
156    /// Resolved from `[[llm.providers]]` at build time using `pruning_provider`
157    /// from `ToolPruningConfig`.
158    pub(crate) pruning_provider: Option<zeph_llm::any::AnyProvider>,
159    /// Whether MCP tool pruning is enabled.  Mirrors `ToolPruningConfig::enabled`.
160    pub(crate) pruning_enabled: bool,
161    /// Pruning parameters snapshot.  Derived from `ToolPruningConfig` at build time.
162    pub(crate) pruning_params: zeph_mcp::PruningParams,
163    /// Pre-computed semantic tool index for embedding-based discovery (#2321).
164    ///
165    /// Built at connect time via `rebuild_semantic_index()`, rebuilt on tool list change.
166    /// `None` when strategy is not `Embedding` or when build failed (fallback to all tools).
167    pub(crate) semantic_index: Option<zeph_mcp::SemanticToolIndex>,
168    /// Active discovery strategy and parameters.  Derived from `ToolDiscoveryConfig`.
169    pub(crate) discovery_strategy: zeph_mcp::ToolDiscoveryStrategy,
170    /// Discovery parameters snapshot.  Derived from `ToolDiscoveryConfig` at build time.
171    pub(crate) discovery_params: zeph_mcp::DiscoveryParams,
172    /// Dedicated embedding provider for tool discovery.  `None` = fall back to the
173    /// agent's primary embedding provider.
174    pub(crate) discovery_provider: Option<zeph_llm::any::AnyProvider>,
175    /// When `true`, show a security warning before prompting for fields whose names
176    /// match sensitive patterns (password, token, secret, key, credential, etc.).
177    pub(crate) elicitation_warn_sensitive_fields: bool,
178    /// When `true`, semantic index and registry need to be rebuilt at the next opportunity.
179    ///
180    /// Set after `/mcp add` or `/mcp remove` when called via `AgentAccess::handle_mcp`,
181    /// which cannot call `rebuild_semantic_index` and `sync_mcp_registry` directly because
182    /// those are `async fn(&mut self)` and their futures are `!Send` (they hold `&mut Agent<C>`
183    /// across `.await`). The rebuild is deferred to `check_tool_refresh`, which runs at the
184    /// start of each turn without the `Box<dyn Future + Send>` constraint.
185    pub(crate) pending_semantic_rebuild: bool,
186}
187
188pub(crate) struct IndexState {
189    pub(crate) retriever: Option<std::sync::Arc<zeph_index::retriever::CodeRetriever>>,
190    pub(crate) repo_map_tokens: usize,
191    pub(crate) cached_repo_map: Option<(String, std::time::Instant)>,
192    pub(crate) repo_map_ttl: std::time::Duration,
193}
194
195/// Snapshot of adversarial policy gate configuration for status display.
196#[derive(Debug, Clone)]
197pub struct AdversarialPolicyInfo {
198    pub provider: String,
199    pub policy_count: usize,
200    pub fail_open: bool,
201}
202
203#[allow(clippy::struct_excessive_bools)]
204pub(crate) struct RuntimeConfig {
205    pub(crate) security: SecurityConfig,
206    pub(crate) timeouts: TimeoutConfig,
207    pub(crate) model_name: String,
208    /// Configured name from `[[llm.providers]]` (the `name` field), set at startup and on
209    /// `/provider` switch. Falls back to the provider type string when empty.
210    pub(crate) active_provider_name: String,
211    pub(crate) permission_policy: zeph_tools::PermissionPolicy,
212    pub(crate) redact_credentials: bool,
213    pub(crate) rate_limiter: super::rate_limiter::ToolRateLimiter,
214    pub(crate) semantic_cache_enabled: bool,
215    pub(crate) semantic_cache_threshold: f32,
216    pub(crate) semantic_cache_max_candidates: u32,
217    /// Dependency config snapshot stored for per-turn boost parameters.
218    pub(crate) dependency_config: zeph_tools::DependencyConfig,
219    /// Adversarial policy gate runtime info for /status display.
220    pub(crate) adversarial_policy_info: Option<AdversarialPolicyInfo>,
221    /// Current spawn depth of this agent instance (0 = top-level, 1 = first sub-agent, etc.).
222    /// Used by `build_spawn_context()` to propagate depth to children.
223    pub(crate) spawn_depth: u32,
224    /// Inject `<budget>` XML into the volatile system prompt section (#2267).
225    pub(crate) budget_hint_enabled: bool,
226    /// Per-channel skill allowlist. Skills not matching the allowlist are excluded from the
227    /// prompt. An empty `allowed` list means all skills are permitted (default).
228    pub(crate) channel_skills: zeph_config::ChannelSkillsConfig,
229    /// Runtime middleware layers for LLM calls and tool dispatch (#2286).
230    ///
231    /// Default: empty vec (zero-cost — loops never iterate).
232    pub(crate) layers: Vec<std::sync::Arc<dyn crate::runtime_layer::RuntimeLayer>>,
233    /// Background supervisor config snapshot for turn-boundary abort logic.
234    pub(crate) supervisor_config: crate::config::TaskSupervisorConfig,
235    /// Session recap config (#3064).
236    pub(crate) recap_config: zeph_config::RecapConfig,
237    /// Set to `true` after the auto-recap is emitted at session resume (#3144).
238    ///
239    /// Used by `/recap` to skip a redundant LLM call when no new messages have
240    /// been added since the auto-recap was shown.
241    pub(crate) auto_recap_shown: bool,
242    /// Number of non-system messages present when the session was resumed (#3144).
243    ///
244    /// Combined with `auto_recap_shown` to detect whether the user has added new
245    /// messages after the auto-recap was shown.
246    pub(crate) msg_count_at_resume: usize,
247}
248
249/// Groups feedback detection subsystems: correction detector, judge detector, and LLM classifier.
250pub(crate) struct FeedbackState {
251    pub(crate) detector: super::feedback_detector::FeedbackDetector,
252    pub(crate) judge: Option<super::feedback_detector::JudgeDetector>,
253    /// LLM-backed zero-shot classifier for `DetectorMode::Model`.
254    /// When `Some`, `spawn_judge_correction_check` uses this instead of `JudgeDetector`.
255    pub(crate) llm_classifier: Option<zeph_llm::classifier::llm::LlmClassifier>,
256}
257
258/// Groups security-related subsystems (sanitizer, quarantine, exfiltration guard).
259pub(crate) struct SecurityState {
260    pub(crate) sanitizer: ContentSanitizer,
261    pub(crate) quarantine_summarizer: Option<QuarantinedSummarizer>,
262    /// Whether this agent session is serving an ACP client.
263    /// When `true` and `mcp_to_acp_boundary` is enabled, MCP tool results
264    /// receive unconditional quarantine and cross-boundary audit logging.
265    pub(crate) is_acp_session: bool,
266    pub(crate) exfiltration_guard: zeph_sanitizer::exfiltration::ExfiltrationGuard,
267    pub(crate) flagged_urls: HashSet<String>,
268    /// URLs explicitly provided by the user across all turns in this session.
269    /// Populated from raw user message text; cleared on `/clear`.
270    /// Shared with `UrlGroundingVerifier` to check `fetch`/`web_scrape` calls at dispatch time.
271    pub(crate) user_provided_urls: Arc<RwLock<HashSet<String>>>,
272    pub(crate) pii_filter: zeph_sanitizer::pii::PiiFilter,
273    /// NER classifier for PII detection (`classifiers.ner_model`). When `Some`, the PII path
274    /// runs both regex (`pii_filter`) and NER, then merges spans before redaction.
275    /// `None` when `classifiers` feature is disabled or `classifiers.enabled = false`.
276    #[cfg(feature = "classifiers")]
277    pub(crate) pii_ner_backend: Option<std::sync::Arc<dyn zeph_llm::classifier::ClassifierBackend>>,
278    /// Per-call timeout for the NER PII classifier in milliseconds.
279    #[cfg(feature = "classifiers")]
280    pub(crate) pii_ner_timeout_ms: u64,
281    /// Maximum number of bytes passed to the NER PII classifier per call.
282    ///
283    /// Large tool outputs (e.g. `search_code`) can produce 150+ `DeBERTa` chunks and exceed
284    /// the per-call timeout. Input is truncated at a valid UTF-8 boundary before classification.
285    #[cfg(feature = "classifiers")]
286    pub(crate) pii_ner_max_chars: usize,
287    /// Circuit-breaker threshold: number of consecutive timeouts before NER is disabled.
288    /// `0` means the circuit breaker is disabled (NER is always attempted).
289    #[cfg(feature = "classifiers")]
290    pub(crate) pii_ner_circuit_breaker_threshold: u32,
291    /// Number of consecutive NER timeouts observed since the last successful call.
292    #[cfg(feature = "classifiers")]
293    pub(crate) pii_ner_consecutive_timeouts: u32,
294    /// Set to `true` when the circuit breaker trips. NER is skipped for the rest of the session.
295    #[cfg(feature = "classifiers")]
296    pub(crate) pii_ner_tripped: bool,
297    pub(crate) memory_validator: zeph_sanitizer::memory_validation::MemoryWriteValidator,
298    /// LLM-based prompt injection pre-screener (opt-in).
299    pub(crate) guardrail: Option<zeph_sanitizer::guardrail::GuardrailFilter>,
300    /// Post-LLM response verification layer.
301    pub(crate) response_verifier: zeph_sanitizer::response_verifier::ResponseVerifier,
302    /// Temporal causal IPI analyzer (opt-in, disabled when `None`).
303    pub(crate) causal_analyzer: Option<zeph_sanitizer::causal_ipi::TurnCausalAnalyzer>,
304    /// VIGIL pre-sanitizer gate. `None` for subagent sessions (subagents are exempt).
305    /// Set at agent build time for top-level agents; skipped for subagents (high FP rate).
306    pub(crate) vigil: Option<crate::agent::vigil::VigilGate>,
307}
308
309/// Groups debug/diagnostics subsystems (dumper, trace collector, anomaly detector, logging config).
310pub(crate) struct DebugState {
311    pub(crate) debug_dumper: Option<crate::debug_dump::DebugDumper>,
312    pub(crate) dump_format: crate::debug_dump::DumpFormat,
313    pub(crate) trace_collector: Option<crate::debug_dump::trace::TracingCollector>,
314    /// Monotonically increasing counter for `process_user_message` calls.
315    /// Used to key spans in `trace_collector.active_iterations`.
316    pub(crate) iteration_counter: usize,
317    pub(crate) anomaly_detector: Option<zeph_tools::AnomalyDetector>,
318    /// Whether to emit `reasoning_amplification` warnings for quality failures from reasoning
319    /// models. Mirrors `AnomalyConfig::reasoning_model_warning`. Default: `true`.
320    pub(crate) reasoning_model_warning: bool,
321    pub(crate) logging_config: crate::config::LoggingConfig,
322    /// Base dump directory — stored so `/dump-format trace` can create a `TracingCollector` (CR-04).
323    pub(crate) dump_dir: Option<PathBuf>,
324    /// Service name for `TracingCollector` created via runtime format switch (CR-04).
325    pub(crate) trace_service_name: String,
326    /// Whether to redact in `TracingCollector` created via runtime format switch (CR-04).
327    pub(crate) trace_redact: bool,
328    /// Span ID of the currently executing iteration — used by LLM/tool span wiring (CR-01).
329    /// Set to `Some` at the start of `process_user_message`, cleared at end.
330    pub(crate) current_iteration_span_id: Option<[u8; 8]>,
331}
332
333/// Snapshot of the shell-level overlay baked in at startup.
334///
335/// Used in `reload_config` to detect when a hot-reload would produce a different shell
336/// restriction set than the one baked into the live `ShellExecutor` (M4 warn-on-divergence).
337#[derive(Debug, Clone, Default, PartialEq, Eq)]
338pub struct ShellOverlaySnapshot {
339    /// Sorted `blocked_commands` contributed by plugins.
340    pub blocked: Vec<String>,
341    /// Sorted `allowed_commands` after plugin intersection (empty if base was empty).
342    pub allowed: Vec<String>,
343}
344
345/// Groups agent lifecycle state: shutdown signaling, timing, and I/O notification channels.
346pub(crate) struct LifecycleState {
347    pub(crate) shutdown: watch::Receiver<bool>,
348    pub(crate) start_time: Instant,
349    pub(crate) cancel_signal: Arc<Notify>,
350    pub(crate) cancel_token: CancellationToken,
351    /// Handle to the cancel bridge task spawned each turn. Aborted before a new one is created
352    /// to prevent unbounded task accumulation across turns.
353    pub(crate) cancel_bridge_handle: Option<JoinHandle<()>>,
354    pub(crate) config_path: Option<PathBuf>,
355    pub(crate) config_reload_rx: Option<mpsc::Receiver<ConfigEvent>>,
356    /// Path to the plugins directory; used to re-apply overlays on hot-reload.
357    pub(crate) plugins_dir: PathBuf,
358    /// Shell overlay snapshot baked in at startup. Used to detect divergence on hot-reload.
359    pub(crate) startup_shell_overlay: ShellOverlaySnapshot,
360    /// Handle for live-rebuilding the `ShellExecutor`'s `blocked_commands` policy on hot-reload.
361    /// `None` when no `ShellExecutor` is in the executor chain (test harnesses, daemon-only modes).
362    pub(crate) shell_policy_handle: Option<zeph_tools::ShellPolicyHandle>,
363    pub(crate) warmup_ready: Option<watch::Receiver<bool>>,
364    pub(crate) update_notify_rx: Option<mpsc::Receiver<String>>,
365    pub(crate) custom_task_rx: Option<mpsc::Receiver<String>>,
366    /// Last known process cwd. Compared after each tool call to detect changes.
367    pub(crate) last_known_cwd: PathBuf,
368    /// Receiver for file-change events from `FileChangeWatcher`. `None` when no paths configured.
369    pub(crate) file_changed_rx: Option<mpsc::Receiver<FileChangedEvent>>,
370    /// Keeps the `FileChangeWatcher` alive for the agent's lifetime. Dropping it aborts the watcher task.
371    pub(crate) file_watcher: Option<crate::file_watcher::FileChangeWatcher>,
372    /// Supervised background task manager. Owned by the agent; call `reap()` between turns
373    /// and `abort_all()` on shutdown.
374    pub(crate) supervisor: super::agent_supervisor::BackgroundSupervisor,
375}
376
377/// Minimal config snapshot needed to reconstruct a provider at runtime via `/provider <name>`.
378///
379/// Secrets are stored as plain strings because [`Secret`] intentionally does not implement
380/// `Clone`. They are re-wrapped in `Secret` when passed to `build_provider_for_switch`.
381pub struct ProviderConfigSnapshot {
382    pub claude_api_key: Option<String>,
383    pub openai_api_key: Option<String>,
384    pub gemini_api_key: Option<String>,
385    pub compatible_api_keys: std::collections::HashMap<String, String>,
386    pub llm_request_timeout_secs: u64,
387    pub embedding_model: String,
388}
389
390/// Groups provider-related state: alternate providers, runtime switching, and compaction flags.
391pub(crate) struct ProviderState {
392    pub(crate) summary_provider: Option<AnyProvider>,
393    /// Shared slot for runtime model switching; set by external caller (e.g. ACP).
394    pub(crate) provider_override: Option<Arc<RwLock<Option<AnyProvider>>>>,
395    pub(crate) judge_provider: Option<AnyProvider>,
396    /// Dedicated provider for compaction probe LLM calls. Falls back to `summary_provider`
397    /// (or primary) when `None`.
398    pub(crate) probe_provider: Option<AnyProvider>,
399    /// Dedicated provider for `compress_context` LLM calls (#2356).
400    /// Falls back to the primary provider when `None`.
401    pub(crate) compress_provider: Option<AnyProvider>,
402    pub(crate) cached_prompt_tokens: u64,
403    /// Whether the active provider has server-side compaction enabled (Claude compact-2026-01-12).
404    /// When true, client-side compaction is skipped.
405    pub(crate) server_compaction_active: bool,
406    pub(crate) stt: Option<Box<dyn SpeechToText>>,
407    /// Snapshot of `[[llm.providers]]` entries for runtime `/provider` switching.
408    pub(crate) provider_pool: Vec<ProviderEntry>,
409    /// Resolved secrets and timeout settings needed to reconstruct providers at runtime.
410    pub(crate) provider_config_snapshot: Option<ProviderConfigSnapshot>,
411}
412
413/// Groups metrics and cost tracking state.
414pub(crate) struct MetricsState {
415    pub(crate) metrics_tx: Option<watch::Sender<MetricsSnapshot>>,
416    pub(crate) cost_tracker: Option<CostTracker>,
417    pub(crate) token_counter: Arc<TokenCounter>,
418    /// Set to `true` when Claude extended context (`enable_extended_context = true`) is active.
419    /// Read from config at build time, not derived from provider internals.
420    pub(crate) extended_context: bool,
421    /// Shared classifier latency ring buffer. Populated by `ContentSanitizer` (injection, PII)
422    /// and `LlmClassifier` (feedback). `None` when classifiers are not configured.
423    pub(crate) classifier_metrics: Option<Arc<zeph_llm::ClassifierMetrics>>,
424    /// Rolling window of per-turn latency samples (last 10 turns).
425    pub(crate) timing_window: std::collections::VecDeque<crate::metrics::TurnTimings>,
426    /// Accumulator for the current turn's timings. Flushed at turn end via `flush_turn_timings`.
427    pub(crate) pending_timings: crate::metrics::TurnTimings,
428    /// Optional histogram recorder for per-event Prometheus observations.
429    /// `None` when the `prometheus` feature is disabled or metrics are not enabled.
430    pub(crate) histogram_recorder: Option<std::sync::Arc<dyn crate::metrics::HistogramRecorder>>,
431}
432
433/// Groups task orchestration and subagent state.
434#[derive(Default)]
435pub(crate) struct OrchestrationState {
436    /// On `OrchestrationState` (not `ProviderState`) because this provider is used exclusively
437    /// by `LlmPlanner` during orchestration, not shared across subsystems.
438    pub(crate) planner_provider: Option<AnyProvider>,
439    /// Provider for `PlanVerifier` LLM calls. `None` falls back to the primary provider.
440    /// On `OrchestrationState` for the same reason as `planner_provider`.
441    pub(crate) verify_provider: Option<AnyProvider>,
442    /// Graph waiting for `/plan confirm` before execution starts.
443    pub(crate) pending_graph: Option<zeph_orchestration::TaskGraph>,
444    /// Cancellation token for the currently executing plan. `None` when no plan is running.
445    /// Created fresh in `handle_plan_confirm()`, cancelled in `handle_plan_cancel()`.
446    ///
447    /// # Known limitation
448    ///
449    /// Token plumbing is ready; the delivery path requires the agent message loop to be
450    /// restructured so `/plan cancel` can be received while `run_scheduler_loop` holds
451    /// `&mut self`. See follow-up issue #1603 (SEC-M34-002).
452    pub(crate) plan_cancel_token: Option<CancellationToken>,
453    /// Manages spawned sub-agents.
454    pub(crate) subagent_manager: Option<zeph_subagent::SubAgentManager>,
455    pub(crate) subagent_config: crate::config::SubAgentConfig,
456    pub(crate) orchestration_config: crate::config::OrchestrationConfig,
457    /// Lazily initialized plan template cache. `None` until first use or when
458    /// memory (`SQLite`) is unavailable.
459    #[allow(dead_code)]
460    pub(crate) plan_cache: Option<zeph_orchestration::PlanCache>,
461    /// Goal embedding from the most recent `plan_with_cache()` call. Consumed by
462    /// `finalize_plan_execution()` to cache the completed plan template.
463    pub(crate) pending_goal_embedding: Option<Vec<f32>>,
464    /// `AdaptOrch` topology advisor — `None` when `[orchestration.adaptorch]` is disabled.
465    pub(crate) topology_advisor: Option<std::sync::Arc<zeph_orchestration::TopologyAdvisor>>,
466    /// Last `AdaptOrch` verdict; carried from `handle_plan_goal_as_string` to scheduler loop
467    /// for `record_outcome`.
468    #[allow(dead_code)] // read via .take() in plan.rs; clippy false positive
469    pub(crate) last_advisor_verdict: Option<zeph_orchestration::AdvisorVerdict>,
470    /// Task graph persistence handle. `None` when no `SemanticMemory` was
471    /// attached via `with_memory`, or when
472    /// `OrchestrationConfig::persistence_enabled` is `false`. When `Some`, the
473    /// scheduler loop snapshots the graph once per tick and `/plan resume <id>`
474    /// rehydrates from disk.
475    pub(crate) graph_persistence:
476        Option<zeph_orchestration::GraphPersistence<zeph_memory::store::graph_store::DbGraphStore>>,
477}
478
479/// Groups instruction hot-reload state.
480#[derive(Default)]
481pub(crate) struct InstructionState {
482    pub(crate) blocks: Vec<InstructionBlock>,
483    pub(crate) reload_rx: Option<mpsc::Receiver<InstructionEvent>>,
484    pub(crate) reload_state: Option<InstructionReloadState>,
485}
486
487/// Groups experiment feature state (gated behind `experiments` feature flag).
488pub(crate) struct ExperimentState {
489    pub(crate) config: crate::config::ExperimentConfig,
490    /// Cancellation token for a running experiment session. `Some` means an experiment is active.
491    pub(crate) cancel: Option<tokio_util::sync::CancellationToken>,
492    /// Pre-built config snapshot used as the experiment baseline (agent path).
493    pub(crate) baseline: zeph_experiments::ConfigSnapshot,
494    /// Dedicated judge provider for evaluation. When `Some`, the evaluator uses this provider
495    /// instead of the agent's primary provider, eliminating self-judge bias.
496    pub(crate) eval_provider: Option<AnyProvider>,
497    /// Receives completion/error messages from the background experiment engine task.
498    /// Always present so the select! branch compiles unconditionally.
499    pub(crate) notify_rx: Option<tokio::sync::mpsc::Receiver<String>>,
500    /// Sender end paired with `experiment_notify_rx`. Cloned into the background task.
501    pub(crate) notify_tx: tokio::sync::mpsc::Sender<String>,
502}
503
504/// Output of a background subgoal extraction LLM call.
505pub(crate) struct SubgoalExtractionResult {
506    /// Current subgoal the agent is working toward.
507    pub(crate) current: String,
508    /// Just-completed subgoal, if the LLM detected a transition (`COMPLETED:` non-NONE).
509    pub(crate) completed: Option<String>,
510}
511
512/// Groups context-compression feature state (gated behind `context-compression` feature flag).
513#[derive(Default)]
514pub(crate) struct CompressionState {
515    /// Cached task goal for TaskAware/MIG pruning. Set by `maybe_compact()`,
516    /// invalidated when the last user message hash changes.
517    pub(crate) current_task_goal: Option<String>,
518    /// Hash of the last user message when `current_task_goal` was populated.
519    pub(crate) task_goal_user_msg_hash: Option<u64>,
520    /// Pending background task for goal extraction. Spawned fire-and-forget when the user message
521    /// hash changes; result applied at the start of the next Soft compaction (#1909).
522    pub(crate) pending_task_goal: Option<tokio::task::JoinHandle<Option<String>>>,
523    /// Pending `SideQuest` eviction result from the background LLM call spawned last turn.
524    /// Applied at the START of the next turn before compaction (PERF-1 fix).
525    pub(crate) pending_sidequest_result: Option<tokio::task::JoinHandle<Option<Vec<usize>>>>,
526    /// In-memory subgoal registry for `Subgoal`/`SubgoalMig` pruning strategies (#2022).
527    pub(crate) subgoal_registry: crate::agent::compaction_strategy::SubgoalRegistry,
528    /// Pending background subgoal extraction task.
529    pub(crate) pending_subgoal: Option<tokio::task::JoinHandle<Option<SubgoalExtractionResult>>>,
530    /// Hash of the last user message when subgoal extraction was scheduled.
531    pub(crate) subgoal_user_msg_hash: Option<u64>,
532}
533
534/// Groups runtime tool filtering, dependency tracking, and iteration bookkeeping.
535#[derive(Default)]
536pub(crate) struct ToolState {
537    /// Dynamic tool schema filter: pre-computed tool embeddings for per-turn filtering (#2020).
538    pub(crate) tool_schema_filter: Option<zeph_tools::ToolSchemaFilter>,
539    /// Cached filtered tool IDs for the current user turn.
540    pub(crate) cached_filtered_tool_ids: Option<HashSet<String>>,
541    /// Tool dependency graph for sequential tool availability (#2024).
542    pub(crate) dependency_graph: Option<zeph_tools::ToolDependencyGraph>,
543    /// Always-on tool IDs, mirrored from the tool schema filter for dependency gate bypass.
544    pub(crate) dependency_always_on: HashSet<String>,
545    /// Tool IDs that completed successfully in the current session.
546    pub(crate) completed_tool_ids: HashSet<String>,
547    /// Current tool loop iteration index within the active user turn.
548    pub(crate) current_tool_iteration: usize,
549}
550
551/// Groups per-session I/O and policy state.
552pub(crate) struct SessionState {
553    pub(crate) env_context: EnvironmentContext,
554    /// Timestamp of the last assistant message appended to context.
555    /// Used by time-based microcompact to compute session idle gap (#2699).
556    /// `None` before the first assistant response.
557    pub(crate) last_assistant_at: Option<Instant>,
558    pub(crate) response_cache: Option<std::sync::Arc<zeph_memory::ResponseCache>>,
559    /// Parent tool call ID when this agent runs as a subagent inside another agent session.
560    /// Propagated into every `LoopbackEvent::ToolStart` / `ToolOutput` so the IDE can build
561    /// a subagent hierarchy.
562    pub(crate) parent_tool_use_id: Option<String>,
563    /// Current-turn intent snapshot for VIGIL. `None` between turns.
564    ///
565    /// Set at the top of `process_user_message` (before any tool call) to the first 1024 chars
566    /// of the user message. Cleared at `end_turn`, on `/clear`, and on any turn-abort path.
567    /// Never shared across turns or propagated into subagents.
568    pub(crate) current_turn_intent: Option<String>,
569    /// Optional status channel for sending spinner/status messages to TUI or stderr.
570    pub(crate) status_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
571    /// LSP context injection hooks. Fires after native tool execution, injects
572    /// diagnostics/hover notes as `Role::System` messages before the next LLM call.
573    pub(crate) lsp_hooks: Option<crate::lsp_hooks::LspHookRunner>,
574    /// Snapshot of the policy config for `/policy` command inspection.
575    pub(crate) policy_config: Option<zeph_tools::PolicyConfig>,
576    /// `CwdChanged` hook definitions extracted from `[hooks]` config.
577    pub(crate) hooks_config: HooksConfigSnapshot,
578}
579
580/// Extracted hook lists from `[hooks]` config, stored in `SessionState`.
581#[derive(Default)]
582pub(crate) struct HooksConfigSnapshot {
583    /// Hooks fired when working directory changes.
584    pub(crate) cwd_changed: Vec<zeph_config::HookDef>,
585    /// Hooks fired when a watched file changes.
586    pub(crate) file_changed_hooks: Vec<zeph_config::HookDef>,
587}
588
589// Groups message buffering and image staging state.
590pub(crate) struct MessageState {
591    pub(crate) messages: Vec<Message>,
592    // QueuedMessage is pub(super) in message_queue — same visibility as this struct; lint suppressed.
593    #[allow(private_interfaces)]
594    pub(crate) message_queue: VecDeque<QueuedMessage>,
595    /// Image parts staged by `/image` commands, attached to the next user message.
596    pub(crate) pending_image_parts: Vec<zeph_llm::provider::MessagePart>,
597    /// DB row ID of the most recently persisted message. Set by `persist_message`;
598    /// consumed by `push_message` call sites to populate `metadata.db_id` on in-memory messages.
599    pub(crate) last_persisted_message_id: Option<i64>,
600    /// DB message IDs pending hide after deferred tool pair summarization.
601    pub(crate) deferred_db_hide_ids: Vec<i64>,
602    /// Summary texts pending insertion after deferred tool pair summarization.
603    pub(crate) deferred_db_summaries: Vec<String>,
604}
605
606impl McpState {
607    /// Write the **full** `self.tools` set to the shared executor `RwLock`.
608    ///
609    /// This is the first of two writers to `shared_tools`. Within a turn this method must run
610    /// **before** `apply_pruned_tools`, which writes the pruned subset. The normal call order
611    /// guarantees this: tool-list change events call this method, and pruning runs later inside
612    /// `rebuild_system_prompt`. See also: `apply_pruned_tools`.
613    pub(crate) fn sync_executor_tools(&self) {
614        if let Some(ref shared) = self.shared_tools {
615            shared.write().clone_from(&self.tools);
616        }
617    }
618
619    /// Write the **pruned** tool subset to the shared executor `RwLock`.
620    ///
621    /// Must only be called **after** `sync_executor_tools` has established the full tool set for
622    /// the current turn. `self.tools` (the full set) is intentionally **not** modified.
623    ///
624    /// This method must **NOT** call `sync_executor_tools` internally — doing so would overwrite
625    /// the pruned subset with the full set. See also: `sync_executor_tools`.
626    pub(crate) fn apply_pruned_tools(&self, pruned: Vec<zeph_mcp::McpTool>) {
627        debug_assert!(
628            pruned.iter().all(|p| self
629                .tools
630                .iter()
631                .any(|t| t.server_id == p.server_id && t.name == p.name)),
632            "pruned set must be a subset of self.tools"
633        );
634        if let Some(ref shared) = self.shared_tools {
635            *shared.write() = pruned;
636        }
637    }
638
639    #[cfg(test)]
640    pub(crate) fn tool_count(&self) -> usize {
641        self.tools.len()
642    }
643}
644
645impl IndexState {
646    pub(crate) async fn fetch_code_rag(
647        &self,
648        query: &str,
649        token_budget: usize,
650    ) -> Result<Option<String>, crate::agent::error::AgentError> {
651        let Some(retriever) = &self.retriever else {
652            return Ok(None);
653        };
654        if token_budget == 0 {
655            return Ok(None);
656        }
657
658        let result = retriever
659            .retrieve(query, token_budget)
660            .await
661            .map_err(|e| crate::agent::error::AgentError::Other(format!("{e:#}")))?;
662        let context_text = zeph_index::retriever::format_as_context(&result);
663
664        if context_text.is_empty() {
665            Ok(None)
666        } else {
667            tracing::debug!(
668                strategy = ?result.strategy,
669                chunks = result.chunks.len(),
670                tokens = result.total_tokens,
671                "code context fetched"
672            );
673            Ok(Some(context_text))
674        }
675    }
676
677    /// Return `Some(self)` when code indexing is enabled, `None` otherwise.
678    ///
679    /// Used by `prepare_context` to pass an optional `IndexAccess` reference to
680    /// `zeph_context::assembler::ContextAssembler::gather` without wrapping the whole state.
681    pub(crate) fn as_index_access(&self) -> Option<&dyn zeph_context::input::IndexAccess> {
682        if self.retriever.is_some() {
683            Some(self)
684        } else {
685            None
686        }
687    }
688}
689
690impl DebugState {
691    pub(crate) fn start_iteration_span(&mut self, iteration_index: usize, text: &str) {
692        if let Some(ref mut tc) = self.trace_collector {
693            tc.begin_iteration(iteration_index, text);
694            self.current_iteration_span_id = tc.current_iteration_span_id(iteration_index);
695        }
696    }
697
698    pub(crate) fn end_iteration_span(
699        &mut self,
700        iteration_index: usize,
701        status: crate::debug_dump::trace::SpanStatus,
702    ) {
703        if let Some(ref mut tc) = self.trace_collector {
704            tc.end_iteration(iteration_index, status);
705        }
706        self.current_iteration_span_id = None;
707    }
708
709    pub(crate) fn switch_format(&mut self, new_format: crate::debug_dump::DumpFormat) {
710        let was_trace = self.dump_format == crate::debug_dump::DumpFormat::Trace;
711        let now_trace = new_format == crate::debug_dump::DumpFormat::Trace;
712
713        if now_trace
714            && !was_trace
715            && let Some(ref dump_dir) = self.dump_dir.clone()
716        {
717            let service_name = self.trace_service_name.clone();
718            let redact = self.trace_redact;
719            match crate::debug_dump::trace::TracingCollector::new(
720                dump_dir.as_path(),
721                &service_name,
722                redact,
723                None,
724            ) {
725                Ok(collector) => {
726                    self.trace_collector = Some(collector);
727                }
728                Err(e) => {
729                    tracing::warn!(error = %e, "failed to create TracingCollector on format switch");
730                }
731            }
732        }
733        if was_trace
734            && !now_trace
735            && let Some(mut tc) = self.trace_collector.take()
736        {
737            tc.finish();
738        }
739
740        self.dump_format = new_format;
741    }
742
743    pub(crate) fn write_chat_debug_dump(
744        &self,
745        dump_id: Option<u32>,
746        result: &zeph_llm::provider::ChatResponse,
747        pii_filter: &zeph_sanitizer::pii::PiiFilter,
748    ) {
749        let Some((d, id)) = self.debug_dumper.as_ref().zip(dump_id) else {
750            return;
751        };
752        let raw = match result {
753            zeph_llm::provider::ChatResponse::Text(t) => t.clone(),
754            zeph_llm::provider::ChatResponse::ToolUse {
755                text, tool_calls, ..
756            } => {
757                let calls = serde_json::to_string_pretty(tool_calls).unwrap_or_default();
758                format!(
759                    "{}\n\n---TOOL_CALLS---\n{calls}",
760                    text.as_deref().unwrap_or("")
761                )
762            }
763        };
764        let text = if pii_filter.is_enabled() {
765            pii_filter.scrub(&raw).into_owned()
766        } else {
767            raw
768        };
769        d.dump_response(id, &text);
770    }
771}
772
773impl Default for McpState {
774    fn default() -> Self {
775        Self {
776            tools: Vec::new(),
777            registry: None,
778            manager: None,
779            allowed_commands: Vec::new(),
780            max_dynamic: 10,
781            elicitation_rx: None,
782            shared_tools: None,
783            tool_rx: None,
784            server_outcomes: Vec::new(),
785            pruning_cache: zeph_mcp::PruningCache::new(),
786            pruning_provider: None,
787            pruning_enabled: false,
788            pruning_params: zeph_mcp::PruningParams::default(),
789            semantic_index: None,
790            discovery_strategy: zeph_mcp::ToolDiscoveryStrategy::default(),
791            discovery_params: zeph_mcp::DiscoveryParams::default(),
792            discovery_provider: None,
793            elicitation_warn_sensitive_fields: true,
794            pending_semantic_rebuild: false,
795        }
796    }
797}
798
799impl Default for IndexState {
800    fn default() -> Self {
801        Self {
802            retriever: None,
803            repo_map_tokens: 0,
804            cached_repo_map: None,
805            repo_map_ttl: std::time::Duration::from_mins(5),
806        }
807    }
808}
809
810impl Default for DebugState {
811    fn default() -> Self {
812        Self {
813            debug_dumper: None,
814            dump_format: crate::debug_dump::DumpFormat::default(),
815            trace_collector: None,
816            iteration_counter: 0,
817            anomaly_detector: None,
818            reasoning_model_warning: true,
819            logging_config: crate::config::LoggingConfig::default(),
820            dump_dir: None,
821            trace_service_name: String::new(),
822            trace_redact: true,
823            current_iteration_span_id: None,
824        }
825    }
826}
827
828impl Default for FeedbackState {
829    fn default() -> Self {
830        Self {
831            detector: super::feedback_detector::FeedbackDetector::new(0.6),
832            judge: None,
833            llm_classifier: None,
834        }
835    }
836}
837
838impl Default for RuntimeConfig {
839    fn default() -> Self {
840        Self {
841            security: SecurityConfig::default(),
842            timeouts: TimeoutConfig::default(),
843            model_name: String::new(),
844            active_provider_name: String::new(),
845            permission_policy: zeph_tools::PermissionPolicy::default(),
846            redact_credentials: true,
847            rate_limiter: super::rate_limiter::ToolRateLimiter::new(
848                super::rate_limiter::RateLimitConfig::default(),
849            ),
850            semantic_cache_enabled: false,
851            semantic_cache_threshold: 0.95,
852            semantic_cache_max_candidates: 10,
853            dependency_config: zeph_tools::DependencyConfig::default(),
854            adversarial_policy_info: None,
855            spawn_depth: 0,
856            budget_hint_enabled: true,
857            channel_skills: zeph_config::ChannelSkillsConfig::default(),
858            layers: Vec::new(),
859            supervisor_config: crate::config::TaskSupervisorConfig::default(),
860            recap_config: zeph_config::RecapConfig::default(),
861            auto_recap_shown: false,
862            msg_count_at_resume: 0,
863        }
864    }
865}
866
867impl SessionState {
868    pub(crate) fn new() -> Self {
869        Self {
870            env_context: EnvironmentContext::gather(""),
871            last_assistant_at: None,
872            response_cache: None,
873            parent_tool_use_id: None,
874            current_turn_intent: None,
875            status_tx: None,
876            lsp_hooks: None,
877            policy_config: None,
878            hooks_config: HooksConfigSnapshot::default(),
879        }
880    }
881}
882
883impl SkillState {
884    pub(crate) fn new(
885        registry: Arc<RwLock<SkillRegistry>>,
886        matcher: Option<SkillMatcherBackend>,
887        max_active_skills: usize,
888        last_skills_prompt: String,
889    ) -> Self {
890        Self {
891            registry,
892            trust_snapshot: Arc::new(RwLock::new(HashMap::new())),
893            skill_paths: Vec::new(),
894            managed_dir: None,
895            trust_config: crate::config::TrustConfig::default(),
896            matcher,
897            max_active_skills,
898            disambiguation_threshold: 0.20,
899            min_injection_score: 0.20,
900            embedding_model: String::new(),
901            skill_reload_rx: None,
902            plugin_dirs_supplier: None,
903            active_skill_names: Vec::new(),
904            last_skills_prompt,
905            prompt_mode: crate::config::SkillPromptMode::Auto,
906            available_custom_secrets: HashMap::new(),
907            cosine_weight: 0.7,
908            hybrid_search: false,
909            bm25_index: None,
910            two_stage_matching: false,
911            confusability_threshold: 0.0,
912            rl_head: None,
913            rl_weight: 0.3,
914            rl_warmup_updates: 50,
915            generation_output_dir: None,
916            generation_provider_name: String::new(),
917        }
918    }
919}
920
921impl LifecycleState {
922    pub(crate) fn new() -> Self {
923        let (_tx, rx) = watch::channel(false);
924        Self {
925            shutdown: rx,
926            start_time: Instant::now(),
927            cancel_signal: Arc::new(tokio::sync::Notify::new()),
928            cancel_token: tokio_util::sync::CancellationToken::new(),
929            cancel_bridge_handle: None,
930            config_path: None,
931            config_reload_rx: None,
932            plugins_dir: PathBuf::new(),
933            startup_shell_overlay: ShellOverlaySnapshot::default(),
934            shell_policy_handle: None,
935            warmup_ready: None,
936            update_notify_rx: None,
937            custom_task_rx: None,
938            last_known_cwd: std::env::current_dir().unwrap_or_default(),
939            file_changed_rx: None,
940            file_watcher: None,
941            supervisor: super::agent_supervisor::BackgroundSupervisor::new(
942                &crate::config::TaskSupervisorConfig::default(),
943                None,
944            ),
945        }
946    }
947}
948
949impl ProviderState {
950    pub(crate) fn new(initial_prompt_tokens: u64) -> Self {
951        Self {
952            summary_provider: None,
953            provider_override: None,
954            judge_provider: None,
955            probe_provider: None,
956            compress_provider: None,
957            cached_prompt_tokens: initial_prompt_tokens,
958            server_compaction_active: false,
959            stt: None,
960            provider_pool: Vec::new(),
961            provider_config_snapshot: None,
962        }
963    }
964}
965
966impl MetricsState {
967    pub(crate) fn new(token_counter: Arc<zeph_memory::TokenCounter>) -> Self {
968        Self {
969            metrics_tx: None,
970            cost_tracker: None,
971            token_counter,
972            extended_context: false,
973            classifier_metrics: None,
974            timing_window: std::collections::VecDeque::new(),
975            pending_timings: crate::metrics::TurnTimings::default(),
976            histogram_recorder: None,
977        }
978    }
979}
980
981impl ExperimentState {
982    pub(crate) fn new() -> Self {
983        let (notify_tx, notify_rx) = tokio::sync::mpsc::channel::<String>(4);
984        Self {
985            config: crate::config::ExperimentConfig::default(),
986            cancel: None,
987            baseline: zeph_experiments::ConfigSnapshot::default(),
988            eval_provider: None,
989            notify_rx: Some(notify_rx),
990            notify_tx,
991        }
992    }
993}
994
995pub(super) mod security;
996pub(super) mod skill;
997
998#[cfg(test)]
999mod tests;