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