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(super)` — visible only within the `agent` module.
8
9use std::collections::{HashMap, HashSet, VecDeque};
10use std::path::PathBuf;
11use std::sync::{Arc, RwLock};
12use std::time::Instant;
13
14use tokio::sync::{Notify, mpsc, watch};
15use tokio_util::sync::CancellationToken;
16use zeph_llm::any::AnyProvider;
17use zeph_llm::provider::Message;
18use zeph_llm::stt::SpeechToText;
19
20use crate::config::{ProviderEntry, SecurityConfig, SkillPromptMode, TimeoutConfig};
21use crate::config_watcher::ConfigEvent;
22use crate::context::EnvironmentContext;
23use crate::cost::CostTracker;
24use crate::file_watcher::FileChangedEvent;
25use crate::instructions::{InstructionBlock, InstructionEvent, InstructionReloadState};
26use crate::metrics::MetricsSnapshot;
27use crate::vault::Secret;
28use zeph_config;
29use zeph_memory::TokenCounter;
30use zeph_memory::semantic::SemanticMemory;
31use zeph_sanitizer::ContentSanitizer;
32use zeph_sanitizer::quarantine::QuarantinedSummarizer;
33use zeph_skills::matcher::SkillMatcherBackend;
34use zeph_skills::registry::SkillRegistry;
35use zeph_skills::watcher::SkillEvent;
36
37use super::message_queue::QueuedMessage;
38
39pub(crate) struct MemoryState {
40    pub(crate) memory: Option<Arc<SemanticMemory>>,
41    pub(crate) conversation_id: Option<zeph_memory::ConversationId>,
42    pub(crate) history_limit: u32,
43    pub(crate) recall_limit: usize,
44    pub(crate) summarization_threshold: usize,
45    pub(crate) cross_session_score_threshold: f32,
46    pub(crate) autosave_assistant: bool,
47    pub(crate) autosave_min_length: usize,
48    pub(crate) tool_call_cutoff: usize,
49    pub(crate) unsummarized_count: usize,
50    pub(crate) document_config: crate::config::DocumentConfig,
51    pub(crate) graph_config: crate::config::GraphConfig,
52    pub(crate) compression_guidelines_config: zeph_memory::CompressionGuidelinesConfig,
53    pub(crate) shutdown_summary: bool,
54    pub(crate) shutdown_summary_min_messages: usize,
55    pub(crate) shutdown_summary_max_messages: usize,
56    pub(crate) shutdown_summary_timeout_secs: u64,
57    /// When `true`, hard compaction uses `AnchoredSummary` (structured JSON) instead of
58    /// free-form prose. Falls back to prose on any LLM or validation failure.
59    pub(crate) structured_summaries: bool,
60    /// Top-1 semantic recall score from the most recent `prepare_context` cycle.
61    /// Used by MAR (Memory-Augmented Routing) to bias the bandit toward cheap providers
62    /// when memory confidence is high. Reset to `None` at the start of each turn.
63    pub(crate) last_recall_confidence: Option<f32>,
64    /// Session digest configuration (#2289).
65    pub(crate) digest_config: crate::config::DigestConfig,
66    /// Cached session digest text and its token count, loaded at session start.
67    pub(crate) cached_session_digest: Option<(String, usize)>,
68    /// Context assembly strategy (#2288).
69    pub(crate) context_strategy: crate::config::ContextStrategy,
70    /// Turn threshold for `Adaptive` strategy crossover (#2288).
71    pub(crate) crossover_turn_threshold: u32,
72    /// D-MEM RPE router. `Some` when `graph_config.rpe.enabled = true`.
73    /// Protected by `std::sync::Mutex` for non-async access from `maybe_spawn_graph_extraction`.
74    pub(crate) rpe_router: Option<std::sync::Mutex<zeph_memory::RpeRouter>>,
75    /// Goal text for the current user turn, derived from raw user input (#2483).
76    /// Passed to A-MAC admission control to enable goal-conditioned write gating.
77    /// Reset at the start of each user turn. `None` only before the first user message.
78    pub(crate) goal_text: Option<String>,
79}
80
81pub(crate) struct SkillState {
82    pub(crate) registry: std::sync::Arc<std::sync::RwLock<SkillRegistry>>,
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    pub(crate) active_skill_names: Vec<String>,
93    pub(crate) last_skills_prompt: String,
94    pub(crate) prompt_mode: SkillPromptMode,
95    /// Custom secrets available at runtime: key=hyphenated name, value=secret.
96    pub(crate) available_custom_secrets: HashMap<String, Secret>,
97    pub(crate) cosine_weight: f32,
98    pub(crate) hybrid_search: bool,
99    pub(crate) bm25_index: Option<zeph_skills::bm25::Bm25Index>,
100    pub(crate) two_stage_matching: bool,
101    /// Threshold for confusability warnings (0.0 = disabled).
102    pub(crate) confusability_threshold: f32,
103}
104
105pub(crate) struct McpState {
106    pub(crate) tools: Vec<zeph_mcp::McpTool>,
107    pub(crate) registry: Option<zeph_mcp::McpToolRegistry>,
108    pub(crate) manager: Option<std::sync::Arc<zeph_mcp::McpManager>>,
109    pub(crate) allowed_commands: Vec<String>,
110    pub(crate) max_dynamic: usize,
111    /// Receives elicitation requests from MCP server handlers during tool execution.
112    /// When `Some`, the agent loop must process these concurrently with tool result awaiting
113    /// to avoid deadlock (tool result waits for elicitation, elicitation waits for agent loop).
114    pub(crate) elicitation_rx: Option<tokio::sync::mpsc::Receiver<zeph_mcp::ElicitationEvent>>,
115    /// Shared with `McpToolExecutor` so native `tool_use` sees the current tool list.
116    ///
117    /// Two methods write to this `RwLock` — ordering matters:
118    /// - `sync_mcp_executor_tools()`: writes the **full** `self.mcp.tools` set.
119    /// - `apply_pruned_mcp_tools()`: writes the **pruned** subset (used after pruning).
120    ///
121    /// Within a turn, `sync_mcp_executor_tools` must always run **before**
122    /// `apply_pruned_mcp_tools`.  The normal call order guarantees this: tool-list
123    /// change events call `sync_mcp_executor_tools` (inside `check_tool_refresh`,
124    /// `handle_mcp_add`, `handle_mcp_remove`), and pruning runs later inside
125    /// `rebuild_system_prompt`.  See also: `apply_pruned_mcp_tools`.
126    pub(crate) shared_tools: Option<std::sync::Arc<std::sync::RwLock<Vec<zeph_mcp::McpTool>>>>,
127    /// Receives full flattened tool list after any `tools/list_changed` notification.
128    pub(crate) tool_rx: Option<tokio::sync::watch::Receiver<Vec<zeph_mcp::McpTool>>>,
129    /// Per-server connection outcomes from the initial `connect_all()` call.
130    pub(crate) server_outcomes: Vec<zeph_mcp::ServerConnectOutcome>,
131    /// Per-message cache for MCP tool pruning results (#2298).
132    ///
133    /// Reset at the start of each user turn and whenever the MCP tool list
134    /// changes (via `tools/list_changed`, `/mcp add`, or `/mcp remove`).
135    pub(crate) pruning_cache: zeph_mcp::PruningCache,
136    /// Dedicated provider for MCP tool pruning LLM calls.
137    ///
138    /// `None` means fall back to the agent's primary provider.
139    /// Resolved from `[[llm.providers]]` at build time using `pruning_provider`
140    /// from `ToolPruningConfig`.
141    pub(crate) pruning_provider: Option<zeph_llm::any::AnyProvider>,
142    /// Whether MCP tool pruning is enabled.  Mirrors `ToolPruningConfig::enabled`.
143    pub(crate) pruning_enabled: bool,
144    /// Pruning parameters snapshot.  Derived from `ToolPruningConfig` at build time.
145    pub(crate) pruning_params: zeph_mcp::PruningParams,
146    /// Pre-computed semantic tool index for embedding-based discovery (#2321).
147    ///
148    /// Built at connect time via `rebuild_semantic_index()`, rebuilt on tool list change.
149    /// `None` when strategy is not `Embedding` or when build failed (fallback to all tools).
150    pub(crate) semantic_index: Option<zeph_mcp::SemanticToolIndex>,
151    /// Active discovery strategy and parameters.  Derived from `ToolDiscoveryConfig`.
152    pub(crate) discovery_strategy: zeph_mcp::ToolDiscoveryStrategy,
153    /// Discovery parameters snapshot.  Derived from `ToolDiscoveryConfig` at build time.
154    pub(crate) discovery_params: zeph_mcp::DiscoveryParams,
155    /// Dedicated embedding provider for tool discovery.  `None` = fall back to the
156    /// agent's primary embedding provider.
157    pub(crate) discovery_provider: Option<zeph_llm::any::AnyProvider>,
158    /// When `true`, show a security warning before prompting for fields whose names
159    /// match sensitive patterns (password, token, secret, key, credential, etc.).
160    pub(crate) elicitation_warn_sensitive_fields: bool,
161}
162
163pub(crate) struct IndexState {
164    pub(crate) retriever: Option<std::sync::Arc<zeph_index::retriever::CodeRetriever>>,
165    pub(crate) repo_map_tokens: usize,
166    pub(crate) cached_repo_map: Option<(String, std::time::Instant)>,
167    pub(crate) repo_map_ttl: std::time::Duration,
168}
169
170/// Snapshot of adversarial policy gate configuration for status display.
171#[cfg(feature = "policy-enforcer")]
172#[derive(Debug, Clone)]
173pub struct AdversarialPolicyInfo {
174    pub provider: String,
175    pub policy_count: usize,
176    pub fail_open: bool,
177}
178
179pub(crate) struct RuntimeConfig {
180    pub(crate) security: SecurityConfig,
181    pub(crate) timeouts: TimeoutConfig,
182    pub(crate) model_name: String,
183    /// Configured name from `[[llm.providers]]` (the `name` field), set at startup and on
184    /// `/provider` switch. Falls back to the provider type string when empty.
185    pub(crate) active_provider_name: String,
186    pub(crate) permission_policy: zeph_tools::PermissionPolicy,
187    pub(crate) redact_credentials: bool,
188    pub(crate) rate_limiter: super::rate_limiter::ToolRateLimiter,
189    pub(crate) semantic_cache_enabled: bool,
190    pub(crate) semantic_cache_threshold: f32,
191    pub(crate) semantic_cache_max_candidates: u32,
192    /// Dependency config snapshot stored for per-turn boost parameters.
193    pub(crate) dependency_config: zeph_tools::DependencyConfig,
194    /// Adversarial policy gate runtime info for /status display.
195    #[cfg(feature = "policy-enforcer")]
196    pub(crate) adversarial_policy_info: Option<AdversarialPolicyInfo>,
197}
198
199/// Groups feedback detection subsystems: correction detector, judge detector, and LLM classifier.
200pub(crate) struct FeedbackState {
201    pub(crate) detector: super::feedback_detector::FeedbackDetector,
202    pub(crate) judge: Option<super::feedback_detector::JudgeDetector>,
203    /// LLM-backed zero-shot classifier for `DetectorMode::Model`.
204    /// When `Some`, `spawn_judge_correction_check` uses this instead of `JudgeDetector`.
205    pub(crate) llm_classifier: Option<zeph_llm::classifier::llm::LlmClassifier>,
206}
207
208/// Groups security-related subsystems (sanitizer, quarantine, exfiltration guard).
209pub(crate) struct SecurityState {
210    pub(crate) sanitizer: ContentSanitizer,
211    pub(crate) quarantine_summarizer: Option<QuarantinedSummarizer>,
212    /// Whether this agent session is serving an ACP client.
213    /// When `true` and `mcp_to_acp_boundary` is enabled, MCP tool results
214    /// receive unconditional quarantine and cross-boundary audit logging.
215    pub(crate) is_acp_session: bool,
216    pub(crate) exfiltration_guard: zeph_sanitizer::exfiltration::ExfiltrationGuard,
217    pub(crate) flagged_urls: HashSet<String>,
218    /// URLs explicitly provided by the user across all turns in this session.
219    /// Populated from raw user message text; cleared on `/clear`.
220    /// Shared with `UrlGroundingVerifier` to check `fetch`/`web_scrape` calls at dispatch time.
221    pub(crate) user_provided_urls: Arc<RwLock<HashSet<String>>>,
222    pub(crate) pii_filter: zeph_sanitizer::pii::PiiFilter,
223    /// NER classifier for PII detection (`classifiers.ner_model`). When `Some`, the PII path
224    /// runs both regex (`pii_filter`) and NER, then merges spans before redaction.
225    /// `None` when `classifiers` feature is disabled or `classifiers.enabled = false`.
226    #[cfg(feature = "classifiers")]
227    pub(crate) pii_ner_backend: Option<std::sync::Arc<dyn zeph_llm::classifier::ClassifierBackend>>,
228    /// Per-call timeout for the NER PII classifier in milliseconds.
229    #[cfg(feature = "classifiers")]
230    pub(crate) pii_ner_timeout_ms: u64,
231    /// Maximum number of bytes passed to the NER PII classifier per call.
232    ///
233    /// Large tool outputs (e.g. `search_code`) can produce 150+ `DeBERTa` chunks and exceed
234    /// the per-call timeout. Input is truncated at a valid UTF-8 boundary before classification.
235    #[cfg(feature = "classifiers")]
236    pub(crate) pii_ner_max_chars: usize,
237    pub(crate) memory_validator: zeph_sanitizer::memory_validation::MemoryWriteValidator,
238    /// LLM-based prompt injection pre-screener (opt-in).
239    #[cfg(feature = "guardrail")]
240    pub(crate) guardrail: Option<zeph_sanitizer::guardrail::GuardrailFilter>,
241    /// Post-LLM response verification layer.
242    pub(crate) response_verifier: zeph_sanitizer::response_verifier::ResponseVerifier,
243    /// Temporal causal IPI analyzer (opt-in, disabled when `None`).
244    pub(crate) causal_analyzer: Option<zeph_sanitizer::causal_ipi::TurnCausalAnalyzer>,
245}
246
247/// Groups debug/diagnostics subsystems (dumper, trace collector, anomaly detector, logging config).
248pub(crate) struct DebugState {
249    pub(crate) debug_dumper: Option<crate::debug_dump::DebugDumper>,
250    pub(crate) dump_format: crate::debug_dump::DumpFormat,
251    pub(crate) trace_collector: Option<crate::debug_dump::trace::TracingCollector>,
252    /// Monotonically increasing counter for `process_user_message` calls.
253    /// Used to key spans in `trace_collector.active_iterations`.
254    pub(crate) iteration_counter: usize,
255    pub(crate) anomaly_detector: Option<zeph_tools::AnomalyDetector>,
256    /// Whether to emit `reasoning_amplification` warnings for quality failures from reasoning
257    /// models. Mirrors `AnomalyConfig::reasoning_model_warning`. Default: `true`.
258    pub(crate) reasoning_model_warning: bool,
259    pub(crate) logging_config: crate::config::LoggingConfig,
260    /// Base dump directory — stored so `/dump-format trace` can create a `TracingCollector` (CR-04).
261    pub(crate) dump_dir: Option<PathBuf>,
262    /// Service name for `TracingCollector` created via runtime format switch (CR-04).
263    pub(crate) trace_service_name: String,
264    /// Whether to redact in `TracingCollector` created via runtime format switch (CR-04).
265    pub(crate) trace_redact: bool,
266    /// Span ID of the currently executing iteration — used by LLM/tool span wiring (CR-01).
267    /// Set to `Some` at the start of `process_user_message`, cleared at end.
268    pub(crate) current_iteration_span_id: Option<[u8; 8]>,
269}
270
271/// Groups agent lifecycle state: shutdown signaling, timing, and I/O notification channels.
272pub(crate) struct LifecycleState {
273    pub(crate) shutdown: watch::Receiver<bool>,
274    pub(crate) start_time: Instant,
275    pub(crate) cancel_signal: Arc<Notify>,
276    pub(crate) cancel_token: CancellationToken,
277    pub(crate) config_path: Option<PathBuf>,
278    pub(crate) config_reload_rx: Option<mpsc::Receiver<ConfigEvent>>,
279    pub(crate) warmup_ready: Option<watch::Receiver<bool>>,
280    pub(crate) update_notify_rx: Option<mpsc::Receiver<String>>,
281    pub(crate) custom_task_rx: Option<mpsc::Receiver<String>>,
282    /// Last known process cwd. Compared after each tool call to detect changes.
283    pub(crate) last_known_cwd: PathBuf,
284    /// Receiver for file-change events from `FileChangeWatcher`. `None` when no paths configured.
285    pub(crate) file_changed_rx: Option<mpsc::Receiver<FileChangedEvent>>,
286    /// Keeps the `FileChangeWatcher` alive for the agent's lifetime. Dropping it aborts the watcher task.
287    pub(crate) file_watcher: Option<crate::file_watcher::FileChangeWatcher>,
288}
289
290/// Minimal config snapshot needed to reconstruct a provider at runtime via `/provider <name>`.
291///
292/// Secrets are stored as plain strings because [`Secret`] intentionally does not implement
293/// `Clone`. They are re-wrapped in `Secret` when passed to `build_provider_for_switch`.
294pub struct ProviderConfigSnapshot {
295    pub claude_api_key: Option<String>,
296    pub openai_api_key: Option<String>,
297    pub gemini_api_key: Option<String>,
298    pub compatible_api_keys: std::collections::HashMap<String, String>,
299    pub llm_request_timeout_secs: u64,
300    pub embedding_model: String,
301}
302
303/// Groups provider-related state: alternate providers, runtime switching, and compaction flags.
304pub(crate) struct ProviderState {
305    pub(crate) summary_provider: Option<AnyProvider>,
306    /// Shared slot for runtime model switching; set by external caller (e.g. ACP).
307    pub(crate) provider_override: Option<Arc<std::sync::RwLock<Option<AnyProvider>>>>,
308    pub(crate) judge_provider: Option<AnyProvider>,
309    /// Dedicated provider for compaction probe LLM calls. Falls back to `summary_provider`
310    /// (or primary) when `None`.
311    pub(crate) probe_provider: Option<AnyProvider>,
312    /// Dedicated provider for `compress_context` LLM calls (#2356).
313    /// Falls back to the primary provider when `None`.
314    #[cfg(feature = "context-compression")]
315    pub(crate) compress_provider: Option<AnyProvider>,
316    pub(crate) cached_prompt_tokens: u64,
317    /// Whether the active provider has server-side compaction enabled (Claude compact-2026-01-12).
318    /// When true, client-side compaction is skipped.
319    pub(crate) server_compaction_active: bool,
320    pub(crate) stt: Option<Box<dyn SpeechToText>>,
321    /// Snapshot of `[[llm.providers]]` entries for runtime `/provider` switching.
322    pub(crate) provider_pool: Vec<ProviderEntry>,
323    /// Resolved secrets and timeout settings needed to reconstruct providers at runtime.
324    pub(crate) provider_config_snapshot: Option<ProviderConfigSnapshot>,
325}
326
327/// Groups metrics and cost tracking state.
328pub(crate) struct MetricsState {
329    pub(crate) metrics_tx: Option<watch::Sender<MetricsSnapshot>>,
330    pub(crate) cost_tracker: Option<CostTracker>,
331    pub(crate) token_counter: Arc<TokenCounter>,
332    /// Set to `true` when Claude extended context (`enable_extended_context = true`) is active.
333    /// Read from config at build time, not derived from provider internals.
334    pub(crate) extended_context: bool,
335    /// Shared classifier latency ring buffer. Populated by `ContentSanitizer` (injection, PII)
336    /// and `LlmClassifier` (feedback). `None` when classifiers are not configured.
337    pub(crate) classifier_metrics: Option<Arc<zeph_llm::ClassifierMetrics>>,
338}
339
340/// Groups task orchestration and subagent state.
341pub(crate) struct OrchestrationState {
342    /// On `OrchestrationState` (not `ProviderState`) because this provider is used exclusively
343    /// by `LlmPlanner` during orchestration, not shared across subsystems.
344    pub(crate) planner_provider: Option<AnyProvider>,
345    /// Provider for `PlanVerifier` LLM calls. `None` falls back to the primary provider.
346    /// On `OrchestrationState` for the same reason as `planner_provider`.
347    pub(crate) verify_provider: Option<AnyProvider>,
348    /// Graph waiting for `/plan confirm` before execution starts.
349    pub(crate) pending_graph: Option<crate::orchestration::TaskGraph>,
350    /// Cancellation token for the currently executing plan. `None` when no plan is running.
351    /// Created fresh in `handle_plan_confirm()`, cancelled in `handle_plan_cancel()`.
352    ///
353    /// # Known limitation
354    ///
355    /// Token plumbing is ready; the delivery path requires the agent message loop to be
356    /// restructured so `/plan cancel` can be received while `run_scheduler_loop` holds
357    /// `&mut self`. See follow-up issue #1603 (SEC-M34-002).
358    pub(crate) plan_cancel_token: Option<CancellationToken>,
359    /// Manages spawned sub-agents.
360    pub(crate) subagent_manager: Option<crate::subagent::SubAgentManager>,
361    pub(crate) subagent_config: crate::config::SubAgentConfig,
362    pub(crate) orchestration_config: crate::config::OrchestrationConfig,
363    /// Lazily initialized plan template cache. `None` until first use or when
364    /// memory (`SQLite`) is unavailable.
365    pub(crate) plan_cache: Option<crate::orchestration::PlanCache>,
366    /// Goal embedding from the most recent `plan_with_cache()` call. Consumed by
367    /// `finalize_plan_execution()` to cache the completed plan template.
368    pub(crate) pending_goal_embedding: Option<Vec<f32>>,
369}
370
371/// Groups instruction hot-reload state.
372pub(crate) struct InstructionState {
373    pub(crate) blocks: Vec<InstructionBlock>,
374    pub(crate) reload_rx: Option<mpsc::Receiver<InstructionEvent>>,
375    pub(crate) reload_state: Option<InstructionReloadState>,
376}
377
378/// Groups experiment feature state (gated behind `experiments` feature flag).
379pub(crate) struct ExperimentState {
380    #[cfg(feature = "experiments")]
381    pub(crate) config: crate::config::ExperimentConfig,
382    /// Cancellation token for a running experiment session. `Some` means an experiment is active.
383    #[cfg(feature = "experiments")]
384    pub(crate) cancel: Option<tokio_util::sync::CancellationToken>,
385    /// Pre-built config snapshot used as the experiment baseline (agent path).
386    #[cfg(feature = "experiments")]
387    pub(crate) baseline: crate::experiments::ConfigSnapshot,
388    /// Dedicated judge provider for evaluation. When `Some`, the evaluator uses this provider
389    /// instead of the agent's primary provider, eliminating self-judge bias.
390    #[cfg(feature = "experiments")]
391    pub(crate) eval_provider: Option<AnyProvider>,
392    /// Receives completion/error messages from the background experiment engine task.
393    /// Always present so the select! branch compiles unconditionally.
394    pub(crate) notify_rx: Option<tokio::sync::mpsc::Receiver<String>>,
395    /// Sender end paired with `experiment_notify_rx`. Cloned into the background task.
396    #[cfg(feature = "experiments")]
397    pub(crate) notify_tx: tokio::sync::mpsc::Sender<String>,
398}
399
400/// Output of a background subgoal extraction LLM call.
401#[cfg(feature = "context-compression")]
402pub(crate) struct SubgoalExtractionResult {
403    /// Current subgoal the agent is working toward.
404    pub(crate) current: String,
405    /// Just-completed subgoal, if the LLM detected a transition (`COMPLETED:` non-NONE).
406    pub(crate) completed: Option<String>,
407}
408
409/// Groups context-compression feature state (gated behind `context-compression` feature flag).
410#[cfg(feature = "context-compression")]
411pub(crate) struct CompressionState {
412    /// Cached task goal for TaskAware/MIG pruning. Set by `maybe_compact()`,
413    /// invalidated when the last user message hash changes.
414    pub(crate) current_task_goal: Option<String>,
415    /// Hash of the last user message when `current_task_goal` was populated.
416    pub(crate) task_goal_user_msg_hash: Option<u64>,
417    /// Pending background task for goal extraction. Spawned fire-and-forget when the user message
418    /// hash changes; result applied at the start of the next Soft compaction (#1909).
419    pub(crate) pending_task_goal: Option<tokio::task::JoinHandle<Option<String>>>,
420    /// Pending `SideQuest` eviction result from the background LLM call spawned last turn.
421    /// Applied at the START of the next turn before compaction (PERF-1 fix).
422    pub(crate) pending_sidequest_result: Option<tokio::task::JoinHandle<Option<Vec<usize>>>>,
423    /// In-memory subgoal registry for `Subgoal`/`SubgoalMig` pruning strategies (#2022).
424    pub(crate) subgoal_registry: crate::agent::compaction_strategy::SubgoalRegistry,
425    /// Pending background subgoal extraction task.
426    pub(crate) pending_subgoal: Option<tokio::task::JoinHandle<Option<SubgoalExtractionResult>>>,
427    /// Hash of the last user message when subgoal extraction was scheduled.
428    pub(crate) subgoal_user_msg_hash: Option<u64>,
429}
430
431/// Groups per-session I/O and policy state.
432pub(crate) struct SessionState {
433    pub(crate) env_context: EnvironmentContext,
434    pub(crate) response_cache: Option<std::sync::Arc<zeph_memory::ResponseCache>>,
435    /// Parent tool call ID when this agent runs as a subagent inside another agent session.
436    /// Propagated into every `LoopbackEvent::ToolStart` / `ToolOutput` so the IDE can build
437    /// a subagent hierarchy.
438    pub(crate) parent_tool_use_id: Option<String>,
439    /// Optional status channel for sending spinner/status messages to TUI or stderr.
440    pub(crate) status_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
441    /// LSP context injection hooks. Fires after native tool execution, injects
442    /// diagnostics/hover notes as `Role::System` messages before the next LLM call.
443    #[cfg(feature = "lsp-context")]
444    pub(crate) lsp_hooks: Option<crate::lsp_hooks::LspHookRunner>,
445    /// Snapshot of the policy config for `/policy` command inspection.
446    #[cfg(feature = "policy-enforcer")]
447    pub(crate) policy_config: Option<zeph_tools::PolicyConfig>,
448    /// `CwdChanged` hook definitions extracted from `[hooks]` config.
449    pub(crate) hooks_config: HooksConfigSnapshot,
450}
451
452/// Extracted hook lists from `[hooks]` config, stored in `SessionState`.
453#[derive(Default)]
454pub(crate) struct HooksConfigSnapshot {
455    /// Hooks fired when working directory changes.
456    pub(crate) cwd_changed: Vec<zeph_config::HookDef>,
457    /// Hooks fired when a watched file changes.
458    pub(crate) file_changed_hooks: Vec<zeph_config::HookDef>,
459}
460
461// Groups message buffering and image staging state.
462pub(crate) struct MessageState {
463    pub(crate) messages: Vec<Message>,
464    // QueuedMessage is pub(super) in message_queue — same visibility as this struct; lint suppressed.
465    #[allow(private_interfaces)]
466    pub(crate) message_queue: VecDeque<QueuedMessage>,
467    /// Image parts staged by `/image` commands, attached to the next user message.
468    pub(crate) pending_image_parts: Vec<zeph_llm::provider::MessagePart>,
469}
470
471#[cfg(test)]
472mod tests;