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;
59use zeroize::Zeroizing;
60
61use super::message_queue::QueuedMessage;
62
63/// Coordinator struct holding four concern-separated sub-structs for memory management.
64///
65/// Each sub-struct groups fields by a single concern:
66/// - [`persistence`](MemoryPersistenceState) — `SQLite` handles, conversation IDs, recall budgets
67/// - [`compaction`](MemoryCompactionState) — summarization thresholds, shutdown summary, digest
68/// - [`extraction`](MemoryExtractionState) — graph config, RPE router, semantic labels
69/// - [`subsystems`](MemorySubsystemState) — `TiMem`, `autoDream`, `MagicDocs`, microcompact
70#[derive(Default)]
71pub(crate) struct MemoryState {
72 /// `SQLite` handles, conversation IDs, recall budgets, and autosave policy.
73 pub(crate) persistence: MemoryPersistenceState,
74 /// Summarization thresholds, shutdown summary, digest config, and context strategy.
75 pub(crate) compaction: MemoryCompactionState,
76 /// Graph extraction config, RPE router, document config, and semantic label configs.
77 pub(crate) extraction: MemoryExtractionState,
78 /// `TiMem`, `autoDream`, `MagicDocs`, and microcompact subsystem state.
79 pub(crate) subsystems: MemorySubsystemState,
80}
81
82#[allow(clippy::struct_excessive_bools)]
83pub(crate) struct SkillState {
84 pub(crate) registry: Arc<RwLock<SkillRegistry>>,
85 /// Per-turn trust snapshot written by `prepare_context` after `build_skill_trust_map`.
86 /// Shared with `SkillInvokeExecutor` so it can resolve trust without hitting `SQLite`
87 /// on every tool call. Refreshed once per turn — stale by at most one turn.
88 /// Carries full `SkillTrustSnapshot` (level + `requires_trust_check` + `blake3_hash`) so
89 /// `SkillInvokeExecutor` can perform per-invocation re-hash when the flag is set.
90 pub(crate) trust_snapshot:
91 Arc<RwLock<HashMap<String, crate::skill_invoker::SkillTrustSnapshot>>>,
92 pub(crate) skill_paths: Vec<PathBuf>,
93 pub(crate) managed_dir: Option<PathBuf>,
94 pub(crate) trust_config: crate::config::TrustConfig,
95 pub(crate) matcher: Option<SkillMatcherBackend>,
96 pub(crate) max_active_skills: usize,
97 pub(crate) disambiguation_threshold: f32,
98 pub(crate) min_injection_score: f32,
99 pub(crate) embedding_model: String,
100 pub(crate) skill_reload_rx: Option<mpsc::Receiver<SkillEvent>>,
101 /// Resolves the current set of per-plugin skill dirs at reload time.
102 ///
103 /// Called inside `reload_skills()` so that plugins installed via `/plugins add` after
104 /// startup are discovered on the next watcher event without restarting the agent.
105 pub(crate) plugin_dirs_supplier: Option<Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>>,
106 pub(crate) active_skill_names: Vec<String>,
107 pub(crate) last_skills_prompt: String,
108 pub(crate) prompt_mode: SkillPromptMode,
109 /// Custom secrets available at runtime: key=hyphenated name, value=secret.
110 pub(crate) available_custom_secrets: HashMap<String, Secret>,
111 pub(crate) cosine_weight: f32,
112 pub(crate) hybrid_search: bool,
113 /// Linear blend weight for BM25 hybrid fusion: `fused = bm25_alpha * cosine + (1-bm25_alpha) * bm25_norm`.
114 /// Clamped to `[0.0, 1.0]` at config load. Default: `0.7`.
115 pub(crate) bm25_alpha: f32,
116 pub(crate) bm25_index: Option<zeph_skills::bm25::Bm25Index>,
117 pub(crate) two_stage_matching: bool,
118 /// Threshold for confusability warnings (0.0 = disabled).
119 pub(crate) confusability_threshold: f32,
120 /// `SkillOrchestra` RL routing head. `Some` when `rl_routing_enabled = true` and
121 /// weights are loaded or initialized. `None` when RL routing is disabled.
122 pub(crate) rl_head: Option<zeph_skills::rl_head::RoutingHead>,
123 /// Blend weight for RL routing: `final = (1-rl_weight)*cosine + rl_weight*rl_score`.
124 pub(crate) rl_weight: f32,
125 /// Skip RL blending for the first N updates (cold-start warmup).
126 pub(crate) rl_warmup_updates: u32,
127 /// Directory where `/skill create` writes generated skills.
128 /// Defaults to `managed_dir` if `None`.
129 pub(crate) generation_output_dir: Option<std::path::PathBuf>,
130 /// Provider name for query rewriting before skill matching. Empty = disabled.
131 pub(crate) query_rewrite_provider_name: String,
132 /// Provider name for `/skill create` generation. Empty = primary.
133 pub(crate) generation_provider_name: String,
134 /// Provider name for skill disambiguation LLM calls. Empty = primary.
135 pub(crate) disambiguate_provider_name: String,
136 /// Timeout in milliseconds for `/skill create` LLM generation. Default: 60 000.
137 pub(crate) generation_timeout_ms: u64,
138 /// Optional quality-gate evaluator for generated SKILL.md files (#3319).
139 ///
140 /// When `Some`, the evaluator is attached to every `SkillGenerator` instance so that
141 /// generated skills are scored before being written to disk.
142 pub(crate) skill_evaluator: Option<std::sync::Arc<zeph_skills::evaluator::SkillEvaluator>>,
143 /// Weights for the evaluator composite score — forwarded to `SkillGenerator::with_evaluator`.
144 pub(crate) eval_weights: zeph_skills::evaluator::EvaluationWeights,
145 /// Minimum composite score required to accept a generated skill (forwarded to the generator).
146 pub(crate) eval_threshold: f32,
147 /// Enable `GoSkills` group-structured skill injection.
148 pub(crate) group_structured: bool,
149 /// Inter-skill cosine similarity threshold for `GoSkills` grouping.
150 pub(crate) support_similarity_threshold: f32,
151 /// Whether Stage-2 LLM semantic compliance scan is enabled on `plugin add`.
152 pub(crate) semantic_scan: bool,
153 /// Provider name for the semantic scan LLM. Empty = use primary provider.
154 pub(crate) semantic_scan_provider: String,
155}
156
157pub(crate) struct McpState {
158 pub(crate) tools: Vec<zeph_mcp::McpTool>,
159 pub(crate) registry: Option<zeph_mcp::McpToolRegistry>,
160 pub(crate) manager: Option<std::sync::Arc<zeph_mcp::McpManager>>,
161 pub(crate) allowed_commands: Vec<String>,
162 pub(crate) max_dynamic: usize,
163 /// Receives elicitation requests from MCP server handlers during tool execution.
164 /// When `Some`, the agent loop must process these concurrently with tool result awaiting
165 /// to avoid deadlock (tool result waits for elicitation, elicitation waits for agent loop).
166 pub(crate) elicitation_rx: Option<tokio::sync::mpsc::Receiver<zeph_mcp::ElicitationEvent>>,
167 /// Shared with `McpToolExecutor` so native `tool_use` sees the current tool list.
168 ///
169 /// Two methods write to this `RwLock` — ordering matters:
170 /// - `sync_executor_tools()`: writes the **full** `self.tools` set.
171 /// - `apply_pruned_tools()`: writes the **pruned** subset (used after pruning).
172 ///
173 /// Within a turn, `sync_executor_tools` must always run **before**
174 /// `apply_pruned_tools`. The normal call order guarantees this: tool-list
175 /// change events call `sync_executor_tools` (inside `check_tool_refresh`,
176 /// `handle_mcp_add`, `handle_mcp_remove`), and pruning runs later inside
177 /// `rebuild_system_prompt`. See also: `apply_pruned_tools`.
178 pub(crate) shared_tools: Option<Arc<RwLock<Vec<zeph_mcp::McpTool>>>>,
179 /// Receives full flattened tool list after any `tools/list_changed` notification.
180 pub(crate) tool_rx: Option<tokio::sync::watch::Receiver<Vec<zeph_mcp::McpTool>>>,
181 /// Per-server connection outcomes from the initial `connect_all()` call.
182 pub(crate) server_outcomes: Vec<zeph_mcp::ServerConnectOutcome>,
183 /// Per-message cache for MCP tool pruning results (#2298).
184 ///
185 /// Reset at the start of each user turn and whenever the MCP tool list
186 /// changes (via `tools/list_changed`, `/mcp add`, or `/mcp remove`).
187 pub(crate) pruning_cache: zeph_mcp::PruningCache,
188 /// Dedicated provider for MCP tool pruning LLM calls.
189 ///
190 /// `None` means fall back to the agent's primary provider.
191 /// Resolved from `[[llm.providers]]` at build time using `pruning_provider`
192 /// from `ToolPruningConfig`.
193 pub(crate) pruning_provider: Option<zeph_llm::any::AnyProvider>,
194 /// Whether MCP tool pruning is enabled. Mirrors `ToolPruningConfig::enabled`.
195 pub(crate) pruning_enabled: bool,
196 /// Pruning parameters snapshot. Derived from `ToolPruningConfig` at build time.
197 pub(crate) pruning_params: zeph_mcp::PruningParams,
198 /// Pre-computed semantic tool index for embedding-based discovery (#2321).
199 ///
200 /// Built at connect time via `rebuild_semantic_index()`, rebuilt on tool list change.
201 /// `None` when strategy is not `Embedding` or when build failed (fallback to all tools).
202 pub(crate) semantic_index: Option<zeph_mcp::SemanticToolIndex>,
203 /// Active discovery strategy and parameters. Derived from `ToolDiscoveryConfig`.
204 pub(crate) discovery_strategy: zeph_mcp::ToolDiscoveryStrategy,
205 /// Discovery parameters snapshot. Derived from `ToolDiscoveryConfig` at build time.
206 pub(crate) discovery_params: zeph_mcp::DiscoveryParams,
207 /// Dedicated embedding provider for tool discovery. `None` = fall back to the
208 /// agent's primary embedding provider.
209 pub(crate) discovery_provider: Option<zeph_llm::any::AnyProvider>,
210 /// When `true`, show a security warning before prompting for fields whose names
211 /// match sensitive patterns (password, token, secret, key, credential, etc.).
212 pub(crate) elicitation_warn_sensitive_fields: bool,
213 /// When `true`, semantic index and registry need to be rebuilt at the next opportunity.
214 ///
215 /// Set after `/mcp add` or `/mcp remove` when called via `AgentAccess::handle_mcp`,
216 /// which cannot call `rebuild_semantic_index` and `sync_mcp_registry` directly because
217 /// those are `async fn(&mut self)` and their futures are `!Send` (they hold `&mut Agent<C>`
218 /// across `.await`). The rebuild is deferred to `check_tool_refresh`, which runs at the
219 /// start of each turn without the `Box<dyn Future + Send>` constraint.
220 pub(crate) pending_semantic_rebuild: bool,
221}
222
223pub(crate) struct IndexState {
224 pub(crate) retriever: Option<std::sync::Arc<zeph_index::retriever::CodeRetriever>>,
225 pub(crate) repo_map_tokens: usize,
226 pub(crate) cached_repo_map: Option<(String, std::time::Instant)>,
227 pub(crate) repo_map_ttl: std::time::Duration,
228}
229
230/// Snapshot of adversarial policy gate configuration for status display.
231#[derive(Debug, Clone)]
232pub struct AdversarialPolicyInfo {
233 pub provider: String,
234 pub policy_count: usize,
235 pub fail_open: bool,
236}
237
238#[allow(clippy::struct_excessive_bools)] // independent boolean flags; bitflags or enum would obscure semantics without reducing complexity
239pub(crate) struct RuntimeConfig {
240 pub(crate) security: SecurityConfig,
241 pub(crate) timeouts: TimeoutConfig,
242 pub(crate) model_name: String,
243 /// Configured name from `[[llm.providers]]` (the `name` field), set at startup and on
244 /// `/provider` switch. Falls back to the provider type string when empty.
245 pub(crate) active_provider_name: String,
246 pub(crate) permission_policy: zeph_tools::PermissionPolicy,
247 pub(crate) redact_credentials: bool,
248 pub(crate) rate_limiter: super::rate_limiter::ToolRateLimiter,
249 pub(crate) semantic_cache_enabled: bool,
250 pub(crate) semantic_cache_threshold: f32,
251 pub(crate) semantic_cache_max_candidates: u32,
252 /// Dependency config snapshot stored for per-turn boost parameters.
253 pub(crate) dependency_config: zeph_tools::DependencyConfig,
254 /// Adversarial policy gate runtime info for /status display.
255 pub(crate) adversarial_policy_info: Option<AdversarialPolicyInfo>,
256 /// Current spawn depth of this agent instance (0 = top-level, 1 = first sub-agent, etc.).
257 /// Used by `build_spawn_context()` to propagate depth to children.
258 pub(crate) spawn_depth: u32,
259 /// Inject `<budget>` XML into the volatile system prompt section (#2267).
260 pub(crate) budget_hint_enabled: bool,
261 /// Per-channel skill allowlist. Skills not matching the allowlist are excluded from the
262 /// prompt. An empty `allowed` list means all skills are permitted (default).
263 pub(crate) channel_skills: zeph_config::ChannelSkillsConfig,
264 /// Per-channel tool allowlist. `None` = no restriction. `Some` = only listed tools permitted.
265 /// Populated from the active channel's `allowed_tools` config at agent build time.
266 pub(crate) channel_tool_allowlist: Option<Vec<String>>,
267 /// Minimum allowed interval for `/loop` ticks (seconds). Sourced from `[cli.loop] min_interval_secs`.
268 pub(crate) loop_min_interval_secs: u64,
269 /// Runtime middleware layers for LLM calls and tool dispatch (#2286).
270 ///
271 /// Default: empty vec (zero-cost — loops never iterate).
272 pub(crate) layers: Vec<std::sync::Arc<dyn crate::runtime_layer::RuntimeLayer>>,
273 /// Background supervisor config snapshot for turn-boundary abort logic.
274 pub(crate) supervisor_config: crate::config::TaskSupervisorConfig,
275 /// Session recap config (#3064).
276 pub(crate) recap_config: zeph_config::RecapConfig,
277 /// ACP server configuration snapshot for `/acp` slash-command display.
278 pub(crate) acp_config: zeph_config::AcpConfig,
279 /// Set to `true` after the auto-recap is emitted at session resume (#3144).
280 ///
281 /// Used by `/recap` to skip a redundant LLM call when no new messages have
282 /// been added since the auto-recap was shown.
283 pub(crate) auto_recap_shown: bool,
284 /// Number of non-system messages present when the session was resumed (#3144).
285 ///
286 /// Combined with `auto_recap_shown` to detect whether the user has added new
287 /// messages after the auto-recap was shown.
288 pub(crate) msg_count_at_resume: usize,
289 /// Callback that spawns an external ACP sub-agent process by shell command (#3302).
290 ///
291 /// Injected by the binary crate when the `acp` feature is enabled.
292 /// `None` in bare / non-ACP mode; callers must degrade gracefully.
293 pub(crate) acp_subagent_spawn_fn: Option<zeph_subagent::AcpSubagentSpawnFn>,
294 /// Channel type string used as part of the `(channel_type, channel_id)` persistence key.
295 ///
296 /// Set at build time from the active I/O channel (e.g. `"cli"`, `"tui"`, `"telegram"`).
297 /// Empty when channel identity has not been configured (persistence is skipped).
298 pub(crate) channel_type: String,
299 /// Whether provider preference persistence is enabled for this session (#3308).
300 ///
301 /// Controlled by `[session] provider_persistence = true` (the default). When `false`,
302 /// the stored provider preference is never read or written.
303 pub(crate) provider_persistence_enabled: bool,
304 /// Whether per-session provider override params (e.g. `reasoning_effort`) should be
305 /// persisted alongside the provider name (#4654).
306 ///
307 /// Only meaningful when `provider_persistence_enabled` is also `true`.
308 pub(crate) persist_provider_overrides_enabled: bool,
309 /// Guards against re-persisting during `restore_channel_provider` (#4654, F1).
310 ///
311 /// Set to `true` immediately before calling `provider_switch_as_string` inside the restore
312 /// path, cleared on every branch after the call. While `true`, `persist_channel_provider`
313 /// returns early without writing anything.
314 pub(crate) restoring_provider: bool,
315 /// Goal lifecycle feature configuration.
316 pub(crate) goals: GoalRuntimeConfig,
317 /// Set from the CLI `--bare` flag (#5551).
318 ///
319 /// Bare mode skips skill loading, memory init, MCP connections, scheduler startup, and
320 /// filesystem watchers at startup; this flag lets shutdown-path subsystems (autoDream
321 /// consolidation, skill trace-extraction, shutdown summary, session digest) apply the
322 /// same gating instead of firing unconditional LLM calls at session end.
323 pub(crate) bare: bool,
324}
325
326/// Groups feedback detection subsystems: correction detector, judge detector, and LLM classifier.
327pub(crate) struct FeedbackState {
328 pub(crate) detector: zeph_agent_feedback::FeedbackDetector,
329 pub(crate) judge: Option<zeph_agent_feedback::JudgeDetector>,
330 /// LLM-backed zero-shot classifier for `DetectorMode::Model`.
331 /// When `Some`, `spawn_judge_correction_check` uses this instead of `JudgeDetector`.
332 pub(crate) llm_classifier: Option<zeph_llm::classifier::llm::LlmClassifier>,
333}
334
335/// Groups security-related subsystems (sanitizer, quarantine, exfiltration guard).
336pub(crate) struct SecurityState {
337 pub(crate) sanitizer: ContentSanitizer,
338 pub(crate) quarantine_summarizer: Option<QuarantinedSummarizer>,
339 /// Whether this agent session is serving an ACP client.
340 /// When `true` and `mcp_to_acp_boundary` is enabled, MCP tool results
341 /// receive unconditional quarantine and cross-boundary audit logging.
342 pub(crate) is_acp_session: bool,
343 pub(crate) exfiltration_guard: zeph_sanitizer::exfiltration::ExfiltrationGuard,
344 pub(crate) flagged_urls: HashSet<String>,
345 /// URLs explicitly provided by the user across all turns in this session.
346 /// Populated from raw user message text; cleared on `/clear`.
347 /// Shared with `UrlGroundingVerifier` to check `fetch`/`web_scrape` calls at dispatch time.
348 pub(crate) user_provided_urls: Arc<RwLock<HashSet<String>>>,
349 pub(crate) pii_filter: zeph_sanitizer::pii::PiiFilter,
350 /// NER classifier for PII detection (`classifiers.ner_model`). When `Some`, the PII path
351 /// runs both regex (`pii_filter`) and NER, then merges spans before redaction.
352 /// `None` when `classifiers` feature is disabled or `classifiers.enabled = false`.
353 #[cfg(feature = "classifiers")]
354 pub(crate) pii_ner_backend: Option<std::sync::Arc<dyn zeph_llm::classifier::ClassifierBackend>>,
355 /// Per-call timeout for the NER PII classifier in milliseconds.
356 #[cfg(feature = "classifiers")]
357 pub(crate) pii_ner_timeout_ms: u64,
358 /// Maximum number of bytes passed to the NER PII classifier per call.
359 ///
360 /// Large tool outputs (e.g. `search_code`) can produce 150+ `DeBERTa` chunks and exceed
361 /// the per-call timeout. Input is truncated at a valid UTF-8 boundary before classification.
362 #[cfg(feature = "classifiers")]
363 pub(crate) pii_ner_max_chars: usize,
364 /// Circuit-breaker threshold: number of consecutive timeouts before NER is disabled.
365 /// `0` means the circuit breaker is disabled (NER is always attempted).
366 #[cfg(feature = "classifiers")]
367 pub(crate) pii_ner_circuit_breaker_threshold: u32,
368 /// Number of consecutive NER timeouts observed since the last successful call.
369 #[cfg(feature = "classifiers")]
370 pub(crate) pii_ner_consecutive_timeouts: u32,
371 /// Set to `true` when the circuit breaker trips. NER is skipped for the rest of the session.
372 #[cfg(feature = "classifiers")]
373 pub(crate) pii_ner_tripped: bool,
374 pub(crate) memory_validator: zeph_sanitizer::memory_validation::MemoryWriteValidator,
375 /// LLM-based prompt injection pre-screener (opt-in).
376 pub(crate) guardrail: Option<zeph_sanitizer::guardrail::GuardrailFilter>,
377 /// SONAR NLI entailment-based injection detection stage (opt-in, observe-only).
378 pub(crate) nli_sanitizer: Option<zeph_sanitizer::nli::NliSanitizer>,
379 /// PAAC secret placeholder masking registry (opt-in). Shared with the bootstrap layer so
380 /// vault-resolved secrets registered during config load are masked at the LLM boundary.
381 pub(crate) secret_registry: Option<Arc<zeph_sanitizer::secret_mask::SecretMaskRegistry>>,
382 /// Post-LLM response verification layer.
383 pub(crate) response_verifier: zeph_sanitizer::response_verifier::ResponseVerifier,
384 /// Temporal causal IPI analyzer (opt-in, disabled when `None`).
385 pub(crate) causal_analyzer: Option<zeph_sanitizer::causal_ipi::TurnCausalAnalyzer>,
386 /// VIGIL pre-sanitizer gate. `None` for subagent sessions (subagents are exempt).
387 /// Set at agent build time for top-level agents; skipped for subagents (high FP rate).
388 pub(crate) vigil: Option<crate::agent::vigil::VigilGate>,
389 /// Cross-turn risk accumulator (spec 050 Phase 1).
390 ///
391 /// `advance_turn()` MUST be called once per turn, before `PolicyGateExecutor::check_policy`.
392 /// Never expose score, level, or alerts to any LLM-callable surface.
393 pub(crate) trajectory: crate::agent::trajectory::TrajectorySentinel,
394 /// Shared risk-level slot for `PolicyGateExecutor` (spec 050).
395 ///
396 /// Written by the agent loop after each turn's `sentinel.current_risk()` call.
397 /// `PolicyGateExecutor::check_policy` reads it to downgrade `Allow` at `Critical`.
398 /// `u8` encoding: 0=Calm, 1=Elevated, 2=High, 3=Critical.
399 pub(crate) trajectory_risk_slot: zeph_tools::TrajectoryRiskSlot,
400 /// Pending risk signals from executor layers (spec 050 §2).
401 ///
402 /// `PolicyGateExecutor` and `ScopedToolExecutor` push signal codes here.
403 /// `begin_turn()` drains this queue into `trajectory.record()`.
404 pub(crate) trajectory_signal_queue: zeph_tools::RiskSignalQueue,
405 /// Persistent safety stream + LLM pre-execution probe (spec 050 Phase 2).
406 ///
407 /// `None` when `security.shadow_sentinel.enabled = false` (default).
408 /// When `Some`, `begin_turn()` calls `advance_turn()` to reset the per-turn probe counter.
409 pub(crate) shadow_sentinel:
410 Option<std::sync::Arc<crate::agent::shadow_sentinel::ShadowSentinel>>,
411 /// Per-turn multi-step attack chain accumulator.
412 ///
413 /// `None` by default. When `Some`, `begin_turn()` calls `reset()` to clear per-turn state.
414 /// The same `Arc` must be passed to `ShellExecutor::with_risk_chain` at build time.
415 pub(crate) risk_chain_accumulator: Option<std::sync::Arc<zeph_tools::RiskChainAccumulator>>,
416 /// MAGE trajectory risk accumulator (spec 004-16).
417 ///
418 /// Per-session in-memory accumulator that ingests sanitizer audit signals with exponential
419 /// temporal decay and gates tool execution when cumulative risk exceeds `risk_threshold`.
420 /// Initialized as noop when `memory.shadow_memory.enabled = false` (default).
421 /// `begin_turn()` calls `advance_turn()` then ingests pending signal codes.
422 pub(crate) mage_accumulator: zeph_memory::shadow::TrajectoryRiskAccumulator,
423 /// Per-session append-only shadow memory for cross-turn goal-drift detection (spec 010-7).
424 ///
425 /// `None` when `security.causal_ipi.shadow_memory.enabled = false` (default).
426 /// When `Some`, `process_tool_result_batch` records a `ShadowEvent` after each tool batch,
427 /// then calls `goal_drift_score()` and emits a `GoalDrift` security event when alerted.
428 pub(crate) shadow_memory: Option<zeph_sanitizer::ShadowMemory>,
429 /// Handle into `TrustGateExecutor`'s MCP tool-id registry
430 /// (`crates/zeph-tools/src/trust_gate.rs`), used to force-deny all MCP-sourced tools when
431 /// the active skill trust is Quarantined.
432 ///
433 /// `None` when the caller didn't attach a handle (e.g. tests, or an executor tree built
434 /// without `apply_common_tool_gating`). When `Some`, `check_tool_refresh` keeps it in sync
435 /// with `self.services.mcp.tools` so MCP servers connected after startup (`/mcp add`,
436 /// `tools/list_changed`) are folded into the Quarantine-deny set — the handle is otherwise
437 /// only ever populated once, at startup, and goes stale (#5747).
438 pub(crate) mcp_tool_ids: Option<Arc<RwLock<HashSet<String>>>>,
439}
440
441/// Groups debug/diagnostics subsystems (dumper, trace collector, anomaly detector, logging config).
442pub(crate) struct DebugState {
443 pub(crate) debug_dumper: Option<crate::debug_dump::DebugDumper>,
444 pub(crate) dump_format: crate::debug_dump::DumpFormat,
445 pub(crate) trace_collector: Option<crate::debug_dump::trace::TracingCollector>,
446 /// Monotonically increasing counter for `process_user_message` calls.
447 /// Used to key spans in `trace_collector.active_iterations`.
448 pub(crate) iteration_counter: usize,
449 pub(crate) anomaly_detector: Option<zeph_tools::AnomalyDetector>,
450 /// Whether to emit `reasoning_amplification` warnings for quality failures from reasoning
451 /// models. Mirrors `AnomalyConfig::reasoning_model_warning`. Default: `true`.
452 pub(crate) reasoning_model_warning: bool,
453 pub(crate) logging_config: crate::config::LoggingConfig,
454 /// Base dump directory — stored so `/dump-format trace` can create a `TracingCollector` (CR-04).
455 pub(crate) dump_dir: Option<PathBuf>,
456 /// Service name for `TracingCollector` created via runtime format switch (CR-04).
457 pub(crate) trace_service_name: String,
458 /// Whether to redact in `TracingCollector` created via runtime format switch (CR-04).
459 pub(crate) trace_redact: bool,
460 /// User-defined resource attributes forwarded to `TracingCollector` (from `telemetry.trace_metadata`).
461 pub(crate) trace_metadata: std::collections::HashMap<String, String>,
462 /// Span ID of the currently executing iteration — used by LLM/tool span wiring (CR-01).
463 /// Set to `Some` at the start of `process_user_message`, cleared at end.
464 pub(crate) current_iteration_span_id: Option<[u8; 8]>,
465}
466
467/// Snapshot of the shell-level overlay baked in at startup.
468///
469/// Used in `reload_config` to detect when a hot-reload would produce a different shell
470/// restriction set than the one baked into the live `ShellExecutor` (M4 warn-on-divergence).
471#[derive(Debug, Clone, Default, PartialEq, Eq)]
472pub struct ShellOverlaySnapshot {
473 /// Sorted `blocked_commands` contributed by plugins.
474 pub blocked: Vec<String>,
475 /// Sorted `allowed_commands` after plugin intersection (empty if base was empty).
476 pub allowed: Vec<String>,
477}
478
479/// Runtime state for an active `/loop` session.
480///
481/// At most one loop is active at a time; `LifecycleState::user_loop` holds `Some` while
482/// the loop is running and `None` otherwise.
483pub(crate) struct LoopState {
484 /// The prompt text injected on each tick.
485 pub(crate) prompt: String,
486 /// Number of ticks fired so far.
487 pub(crate) iteration: u64,
488 /// Tick interval. `MissedTickBehavior::Skip` prevents burst catch-up.
489 pub(crate) interval: Interval,
490 /// Cancel handle. Dropped (and token cancelled) when loop is stopped.
491 pub(crate) cancel_tx: CancellationToken,
492}
493
494/// Groups agent lifecycle state: shutdown signaling, timing, and I/O notification channels.
495pub(crate) struct LifecycleState {
496 pub(crate) shutdown: watch::Receiver<bool>,
497 pub(crate) start_time: Instant,
498 pub(crate) cancel_signal: Arc<Notify>,
499 pub(crate) cancel_token: CancellationToken,
500 /// Handle to the cancel bridge task spawned each turn. Aborted before a new one is created
501 /// to prevent unbounded task accumulation across turns.
502 pub(crate) cancel_bridge_handle: Option<zeph_common::task_supervisor::BlockingHandle<()>>,
503 pub(crate) config_path: Option<PathBuf>,
504 pub(crate) config_reload_rx: Option<mpsc::Receiver<ConfigEvent>>,
505 /// Path to the plugins directory; used to re-apply overlays on hot-reload.
506 pub(crate) plugins_dir: PathBuf,
507 /// Shell overlay snapshot baked in at startup. Used to detect divergence on hot-reload.
508 pub(crate) startup_shell_overlay: ShellOverlaySnapshot,
509 /// Handle for live-rebuilding the `ShellExecutor`'s `blocked_commands` policy on hot-reload.
510 /// `None` when no `ShellExecutor` is in the executor chain (test harnesses, daemon-only modes).
511 pub(crate) shell_policy_handle: Option<zeph_tools::ShellPolicyHandle>,
512 pub(crate) warmup_ready: Option<watch::Receiver<bool>>,
513 pub(crate) update_notify_rx: Option<mpsc::Receiver<String>>,
514 pub(crate) custom_task_rx: Option<mpsc::Receiver<String>>,
515 /// Active `/loop` state. `None` when no loop is running.
516 pub(crate) user_loop: Option<LoopState>,
517 /// Last known process cwd. Compared after each tool call to detect changes.
518 pub(crate) last_known_cwd: PathBuf,
519 /// Receiver for file-change events from `FileChangeWatcher`. `None` when no paths configured.
520 pub(crate) file_changed_rx: Option<mpsc::Receiver<FileChangedEvent>>,
521 /// Keeps the `FileChangeWatcher` alive for the agent's lifetime. Dropping it aborts the watcher task.
522 pub(crate) file_watcher: Option<crate::file_watcher::FileChangeWatcher>,
523 /// Supervised background task manager. Owned by the agent; call `reap()` between turns
524 /// and `abort_all()` on shutdown.
525 pub(crate) supervisor: super::agent_supervisor::BackgroundSupervisor,
526 /// Per-turn completion notifier. `None` when `notifications.enabled = false`.
527 pub(crate) notifier: Option<crate::notifications::Notifier>,
528 /// Per-turn LLM request counter. Incremented by `process_response`; reset at turn start.
529 pub(crate) turn_llm_requests: u32,
530 /// Timestamp of the last turn that ended with `LlmError::NoProviders`.
531 ///
532 /// Used to gate `advance_context_lifecycle`: when all providers are down, context preparation
533 /// is skipped (degraded mode) until `no_providers_backoff_secs` has elapsed.
534 pub(crate) last_no_providers_at: Option<Instant>,
535 /// Completions from background shell runs waiting to be injected into the next turn.
536 ///
537 /// Drained at the top of `process_user_message_inner` after `supervisor.reap()`.
538 /// All pending completions and the real user message are merged into a **single**
539 /// user-role block to satisfy strict alternation requirements (Anthropic Messages API).
540 ///
541 /// Capacity is capped at `BACKGROUND_COMPLETION_BUFFER_CAP`. On overflow the oldest
542 /// entry is dropped and a placeholder is substituted so the LLM learns results were lost.
543 pub(crate) pending_background_completions:
544 VecDeque<zeph_tools::shell::background::BackgroundCompletion>,
545 /// Receiver end of the dedicated background-completion channel created alongside the
546 /// `ShellExecutor`. Polled at the top of each turn to drain completions into
547 /// `pending_background_completions`. `None` when no `ShellExecutor` is configured.
548 pub(crate) background_completion_rx:
549 Option<tokio::sync::mpsc::Receiver<zeph_tools::BackgroundCompletion>>,
550 /// Shared reference to the `ShellExecutor` used to query in-flight background run snapshots
551 /// for TUI metrics display. `None` when no `ShellExecutor` is wired (test harnesses, etc.).
552 pub(crate) shell_executor_handle: Option<std::sync::Arc<zeph_tools::ShellExecutor>>,
553 /// Session-level task supervisor, shared with bootstrap and TUI. Used to register
554 /// background agent tasks (cancel bridge, compaction, sidequest eviction) for
555 /// observability and graceful shutdown.
556 ///
557 /// Created with a fresh [`CancellationToken`] in `LifecycleState::new()` for test
558 /// harnesses; production code overwrites it via `Agent::with_task_supervisor`.
559 pub(crate) task_supervisor: Arc<zeph_common::TaskSupervisor>,
560}
561
562/// Minimal config snapshot needed to reconstruct a provider at runtime via `/provider <name>`.
563///
564/// Secrets are stored as plain strings because [`Secret`] intentionally does not implement
565/// `Clone`. They are re-wrapped in `Secret` when passed to `build_provider_for_switch`.
566///
567/// `Clone` so ACP/serve deps structs (built once per process) can hand each session its own
568/// owned copy via [`Agent::with_provider_pool`](crate::agent::Agent::with_provider_pool).
569#[derive(Clone, Default)]
570pub struct ProviderConfigSnapshot {
571 pub claude_api_key: Option<String>,
572 pub openai_api_key: Option<String>,
573 pub gemini_api_key: Option<String>,
574 pub compatible_api_keys: std::collections::HashMap<String, String>,
575 pub llm_request_timeout_secs: u64,
576 pub embedding_model: String,
577 pub gonka_private_key: Option<Zeroizing<String>>,
578 pub gonka_address: Option<String>,
579 pub cocoon_access_hash: Option<String>,
580}
581
582/// Groups provider-related state: alternate providers, runtime switching, and compaction flags.
583pub(crate) struct ProviderState {
584 pub(crate) summary_provider: Option<AnyProvider>,
585 /// Shared slot for runtime model switching; set by external caller (e.g. ACP).
586 pub(crate) provider_override: Option<Arc<RwLock<Option<AnyProvider>>>>,
587 pub(crate) judge_provider: Option<AnyProvider>,
588 /// Dedicated provider for compaction probe LLM calls. Falls back to `summary_provider`
589 /// (or primary) when `None`.
590 pub(crate) probe_provider: Option<AnyProvider>,
591 /// Dedicated provider for `compress_context` LLM calls (#2356).
592 /// Falls back to the primary provider when `None`.
593 pub(crate) compress_provider: Option<AnyProvider>,
594 pub(crate) cached_prompt_tokens: u64,
595 /// Whether the active provider has server-side compaction enabled (Claude compact-2026-01-12).
596 /// When true, client-side compaction is skipped.
597 pub(crate) server_compaction_active: bool,
598 pub(crate) stt: Option<Box<dyn SpeechToText>>,
599 /// Snapshot of `[[llm.providers]]` entries for runtime `/provider` switching.
600 pub(crate) provider_pool: Vec<ProviderEntry>,
601 /// Resolved secrets and timeout settings needed to reconstruct providers at runtime.
602 pub(crate) provider_config_snapshot: Option<ProviderConfigSnapshot>,
603}
604
605/// Groups metrics and cost tracking state.
606pub(crate) struct MetricsState {
607 pub(crate) metrics_tx: Option<watch::Sender<MetricsSnapshot>>,
608 pub(crate) cost_tracker: Option<CostTracker>,
609 pub(crate) token_counter: Arc<TokenCounter>,
610 /// Set to `true` when Claude extended context (`enable_extended_context = true`) is active.
611 /// Read from config at build time, not derived from provider internals.
612 pub(crate) extended_context: bool,
613 /// Shared classifier latency ring buffer. Populated by `ContentSanitizer` (injection, PII)
614 /// and `LlmClassifier` (feedback). `None` when classifiers are not configured.
615 pub(crate) classifier_metrics: Option<Arc<zeph_llm::ClassifierMetrics>>,
616 /// Rolling window of per-turn latency samples (last 10 turns).
617 pub(crate) timing_window: std::collections::VecDeque<crate::metrics::TurnTimings>,
618 /// Accumulator for the current turn's timings. Flushed at turn end via `flush_turn_timings`.
619 pub(crate) pending_timings: crate::metrics::TurnTimings,
620 /// Optional histogram recorder for per-event Prometheus observations.
621 /// `None` when the `prometheus` feature is disabled or metrics are not enabled.
622 pub(crate) histogram_recorder: Option<std::sync::Arc<dyn crate::metrics::HistogramRecorder>>,
623}
624
625/// Groups task orchestration and subagent state.
626#[derive(Default)]
627pub(crate) struct OrchestrationState {
628 /// Lookahead tool hints snapshot taken after the most recent scheduler tick.
629 ///
630 /// Populated by `run_scheduler_loop` after each `scheduler.tick()` call via
631 /// `zeph_orchestration::lookahead_tools`. Cleared when the scheduler loop exits.
632 /// Read by `prepare_context` in `assembly.rs` to pass PAACE hints to `FidelityScorer`.
633 pub(crate) cached_lookahead: Vec<zeph_common::PlannedToolHint>,
634 /// On `OrchestrationState` (not `ProviderState`) because this provider is used exclusively
635 /// by `LlmPlanner` during orchestration, not shared across subsystems.
636 pub(crate) planner_provider: Option<AnyProvider>,
637 /// Provider for `PlanVerifier` LLM calls. `None` falls back to `orchestrator_provider`
638 /// then the primary provider.
639 pub(crate) verify_provider: Option<AnyProvider>,
640 /// Provider for scheduling-tier LLM calls (aggregation, predicate evaluation, verification
641 /// fallback). `None` falls back to the primary provider.
642 /// Set from `config.orchestration.orchestrator_provider` at startup.
643 pub(crate) orchestrator_provider: Option<AnyProvider>,
644 /// Provider for predicate gate evaluation. `None` falls back to `orchestrator_provider`
645 /// then `verify_provider` then primary.
646 pub(crate) predicate_provider: Option<AnyProvider>,
647 /// Graph waiting for `/plan confirm` before execution starts.
648 pub(crate) pending_graph: Option<zeph_orchestration::TaskGraph>,
649 /// Cancellation token for the currently executing plan. `None` when no plan is running.
650 /// Created fresh in `handle_plan_confirm()`, cancelled in `handle_plan_cancel()`.
651 ///
652 /// # Known limitation
653 ///
654 /// Token plumbing is ready; the delivery path requires the agent message loop to be
655 /// restructured so `/plan cancel` can be received while `run_scheduler_loop` holds
656 /// `&mut self`. See follow-up issue #1603 (SEC-M34-002).
657 pub(crate) plan_cancel_token: Option<CancellationToken>,
658 /// Manages spawned sub-agents.
659 pub(crate) subagent_manager: Option<zeph_subagent::SubAgentManager>,
660 pub(crate) subagent_config: crate::config::SubAgentConfig,
661 pub(crate) orchestration_config: crate::config::OrchestrationConfig,
662 /// Lazily initialized plan template cache. `None` until first use or when
663 /// memory (`SQLite`) is unavailable.
664 #[allow(dead_code)]
665 pub(crate) plan_cache: Option<zeph_orchestration::PlanCache>,
666 /// Goal embedding from the most recent `plan_with_cache()` call. Consumed by
667 /// `finalize_plan_execution()` to cache the completed plan template.
668 pub(crate) pending_goal_embedding: Option<Vec<f32>>,
669 /// `AdaptOrch` topology advisor — `None` when `[orchestration.adaptorch]` is disabled.
670 pub(crate) topology_advisor: Option<std::sync::Arc<zeph_orchestration::TopologyAdvisor>>,
671 /// Last `AdaptOrch` verdict; carried from `handle_plan_goal_as_string` to scheduler loop
672 /// for `record_outcome`.
673 #[allow(dead_code)] // read via .take() in plan.rs; clippy false positive
674 pub(crate) last_advisor_verdict: Option<zeph_orchestration::AdvisorVerdict>,
675 /// Task graph persistence handle. `None` when no `SemanticMemory` was
676 /// attached via `with_memory`, or when
677 /// `OrchestrationConfig::persistence_enabled` is `false`. When `Some`, the
678 /// scheduler loop snapshots the graph once per tick and `/plan resume <id>`
679 /// rehydrates from disk.
680 pub(crate) graph_persistence: Option<
681 zeph_orchestration::GraphPersistence<zeph_memory::store::graph_store::TaskGraphStore>,
682 >,
683 /// Named execution environment for the current orchestration task.
684 ///
685 /// Set by the scheduler when dispatching a `TaskNode` that has
686 /// `execution_environment: Some(name)`. Cleared between tasks. When `Some`,
687 /// `prepare_tool_dispatch` injects an [`ExecutionContext`] named `name` into
688 /// every `ToolCall` so that `ShellExecutor::resolve_context` uses the right env.
689 pub(crate) task_execution_env: Option<String>,
690
691 // ── P2 durable adapter (spec-064) ─────────────────────────────────────────
692 /// Durable config snapshot used by the P2 adapter in `plan.rs`.
693 ///
694 /// `None` when durable execution is disabled or the agent was built without a durable config
695 /// (e.g. unit tests). When `Some` and `durable.orchestration = true`, `/plan resume` restores
696 /// the replan budget from the journal instead of zeroing it.
697 pub(crate) durable_config: Option<zeph_config::DurableConfig>,
698 /// Resolved path to `durable.db` (the dedicated journal file for `LocalBackend`).
699 ///
700 /// Derived at build time from `memory.sqlite_path` sibling directory. `None` when the durable
701 /// adapter is not configured.
702 pub(crate) durable_db_url: Option<String>,
703 /// Shared durable backend for P2 budget snapshots.
704 ///
705 /// Lazily initialised by `plan.rs` on first journal call; shared across pause/resume cycles
706 /// for the same process lifetime.
707 // Accessed exclusively through ensure_durable_backend() in plan.rs; rustc's cross-module
708 // dead_code analysis does not follow the indirect Option method chains.
709 #[allow(dead_code)]
710 pub(crate) durable_backend: Option<std::sync::Arc<zeph_durable::DurableBackendEnum>>,
711 /// Writer handle for the shared P2 durable backend.
712 // Same as durable_backend: accessed through plan.rs ensure_durable_backend().
713 #[allow(dead_code)]
714 pub(crate) durable_writer: Option<zeph_durable::JournalWriterHandle>,
715 /// [`BlockingHandle`] for the background `JournalWriter` actor task, tracked by `TaskSupervisor`.
716 ///
717 /// Kept so the agent can abort the writer on shutdown rather than relying on process exit.
718 /// `None` until `ensure_durable_backend()` initialises the backend for the first time.
719 pub(crate) durable_writer_task: Option<zeph_common::task_supervisor::BlockingHandle<()>>,
720 /// Cipher for encrypting P2 budget snapshots. `None` when `encrypt_payload = false`.
721 pub(crate) durable_cipher: Option<std::sync::Arc<dyn zeph_durable::PayloadCipher>>,
722}
723
724/// Groups instruction hot-reload state.
725#[derive(Default)]
726pub(crate) struct InstructionState {
727 pub(crate) blocks: Vec<InstructionBlock>,
728 pub(crate) reload_rx: Option<mpsc::Receiver<InstructionEvent>>,
729 pub(crate) reload_state: Option<InstructionReloadState>,
730}
731
732/// Groups experiment feature state (gated behind `experiments` feature flag).
733pub(crate) struct ExperimentState {
734 pub(crate) config: crate::config::ExperimentConfig,
735 /// Cancellation token for a running experiment session. `Some` means an experiment is active.
736 pub(crate) cancel: Option<tokio_util::sync::CancellationToken>,
737 /// Handle for the background experiment task. Stored so shutdown can abort it if the
738 /// `CancellationToken` signal is not observed in time (e.g. the task is blocked on I/O).
739 pub(crate) handle: Option<zeph_common::task_supervisor::BlockingHandle<()>>,
740 /// Pre-built config snapshot used as the experiment baseline (agent path).
741 pub(crate) baseline: zeph_experiments::ConfigSnapshot,
742 /// Dedicated judge provider for evaluation. When `Some`, the evaluator uses this provider
743 /// instead of the agent's primary provider, eliminating self-judge bias.
744 pub(crate) eval_provider: Option<AnyProvider>,
745 /// Receives completion/error messages from the background experiment engine task.
746 /// Always present so the select! branch compiles unconditionally.
747 pub(crate) notify_rx: Option<tokio::sync::mpsc::Receiver<String>>,
748 /// Sender end paired with `experiment_notify_rx`. Cloned into the background task.
749 pub(crate) notify_tx: tokio::sync::mpsc::Sender<String>,
750}
751
752/// Groups context-compression feature state (gated behind `context-compression` feature flag).
753#[derive(Default)]
754pub(crate) struct CompressionState {
755 /// Cached task goal for TaskAware/MIG pruning. Set by `maybe_compact()`,
756 /// invalidated when the last user message hash changes.
757 pub(crate) current_task_goal: Option<String>,
758 /// Hash of the last user message when `current_task_goal` was populated.
759 pub(crate) task_goal_user_msg_hash: Option<u64>,
760 /// Pending background task for goal extraction. Spawned when the user message hash changes;
761 /// result applied at the start of the next Soft compaction (#1909).
762 pub(crate) pending_task_goal:
763 Option<zeph_common::task_supervisor::BlockingHandle<Option<String>>>,
764 /// Pending `SideQuest` eviction result from the background LLM call spawned last turn.
765 /// Applied at the START of the next turn before compaction (PERF-1 fix).
766 pub(crate) pending_sidequest_result:
767 Option<zeph_common::task_supervisor::BlockingHandle<Option<Vec<usize>>>>,
768 /// In-memory subgoal registry for `Subgoal`/`SubgoalMig` pruning strategies (#2022).
769 pub(crate) subgoal_registry: zeph_agent_context::SubgoalRegistry,
770 /// Pending background subgoal extraction task.
771 pub(crate) pending_subgoal: Option<
772 zeph_common::task_supervisor::BlockingHandle<
773 Option<zeph_agent_context::SubgoalExtractionResult>,
774 >,
775 >,
776 /// Hash of the last user message when subgoal extraction was scheduled.
777 pub(crate) subgoal_user_msg_hash: Option<u64>,
778 /// Shared typed-page state (#3630). `None` when `typed_pages.enabled = false`.
779 pub(crate) typed_pages_state: Option<Arc<zeph_context::typed_page::TypedPagesState>>,
780}
781
782/// Groups runtime tool filtering, dependency tracking, and iteration bookkeeping.
783#[derive(Default)]
784pub(crate) struct ToolState {
785 /// Dynamic tool schema filter: pre-computed tool embeddings for per-turn filtering (#2020).
786 pub(crate) tool_schema_filter: Option<zeph_tools::ToolSchemaFilter>,
787 /// Cached filtered tool IDs for the current user turn.
788 pub(crate) cached_filtered_tool_ids: Option<HashSet<String>>,
789 /// Tool dependency graph for sequential tool availability (#2024).
790 pub(crate) dependency_graph: Option<zeph_tools::ToolDependencyGraph>,
791 /// Always-on tool IDs, mirrored from the tool schema filter for dependency gate bypass.
792 pub(crate) dependency_always_on: HashSet<String>,
793 /// Tool IDs that completed successfully in the current session.
794 pub(crate) completed_tool_ids: HashSet<String>,
795 /// Current tool loop iteration index within the active user turn.
796 pub(crate) current_tool_iteration: usize,
797 /// PASTE pattern store for tool invocation history and prediction (#3642).
798 ///
799 /// `Some` only when `config.tools.speculative.mode` is `Pattern` or `Both`.
800 pub(crate) pattern_store: Option<Arc<crate::agent::speculative::paste::PatternStore>>,
801 /// Per-turn mapping from tool name to `(skill_name, skill_hash)`, populated at skill
802 /// activation and used by `observe()` to attribute tool completions to their owning skill.
803 pub(crate) tool_to_skill: HashMap<String, (String, String)>,
804 /// Last tool executed per skill in the current turn, keyed by skill name.
805 /// Used as `prev_tool` for PASTE pattern transition recording.
806 pub(crate) last_tool_per_skill: HashMap<String, String>,
807}
808
809/// Groups per-session I/O and policy state.
810#[allow(clippy::struct_excessive_bools)] // runtime state — boolean flags are idiomatic here
811pub(crate) struct SessionState {
812 pub(crate) env_context: EnvironmentContext,
813 /// Timestamp of the last assistant message appended to context.
814 /// Used by time-based microcompact to compute session idle gap (#2699).
815 /// `None` before the first assistant response.
816 pub(crate) last_assistant_at: Option<Instant>,
817 pub(crate) response_cache: Option<std::sync::Arc<zeph_memory::ResponseCache>>,
818 /// Parent tool call ID when this agent runs as a subagent inside another agent session.
819 /// Propagated into every `LoopbackEvent::ToolStart` / `ToolOutput` so the IDE can build
820 /// a subagent hierarchy.
821 pub(crate) parent_tool_use_id: Option<String>,
822 /// Current-turn intent snapshot for VIGIL. `None` between turns.
823 ///
824 /// Set at the top of `process_user_message` (before any tool call) to the first 1024 chars
825 /// of the user message. Cleared at `end_turn`, on `/clear`, and on any turn-abort path.
826 /// Never shared across turns or propagated into subagents.
827 pub(crate) current_turn_intent: Option<String>,
828 /// Optional status channel for sending spinner/status messages to TUI or stderr.
829 pub(crate) status_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
830 /// LSP context injection hooks. Fires after native tool execution, injects
831 /// diagnostics/hover notes as `Role::System` messages before the next LLM call.
832 pub(crate) lsp_hooks: Option<crate::lsp_hooks::LspHookRunner>,
833 /// Snapshot of the policy config for `/policy` command inspection.
834 pub(crate) policy_config: Option<zeph_tools::PolicyConfig>,
835 /// `CwdChanged` hook definitions extracted from `[hooks]` config.
836 pub(crate) hooks_config: HooksConfigSnapshot,
837 /// Whether the current turn originates from a Telegram guest query (`guest_message` update).
838 ///
839 /// When `true`, the agent prompt includes a brief guest-context annotation, and the response
840 /// is delivered via `answerGuestQuery` instead of `sendMessage`.
841 pub(crate) is_guest_context: bool,
842 /// Active durable execution context for the P1 agent-loop adapter (spec-064 §P1, #5452).
843 ///
844 /// `Some` when `[durable] enabled = true` and `agent_turns = true`. The context is opened
845 /// lazily by [`Agent::ensure_session_durable_ctx`](crate::agent::Agent::ensure_session_durable_ctx)
846 /// the first time a durable-gated call site runs (not eagerly in the builder chain, since the
847 /// real `TaskSupervisor` is only attached later via `with_task_supervisor`), keyed on the
848 /// session's `ConversationId` so every turn replays under the same execution. `None` when
849 /// durable execution is disabled (or construction failed and degraded) — in which case the
850 /// loop runs unmodified.
851 pub(crate) durable_ctx: Option<std::sync::Arc<zeph_durable::DurableContext>>,
852 /// Mirror of `[durable] subagent` config flag (spec-064 §P4, #5452), set unconditionally at
853 /// bootstrap via `AgentBuilder::with_durable_subagent` from `config.durable.subagent`.
854 ///
855 /// When `true` and `durable_ctx` is `Some`, sub-agent spawns are wrapped in a durable
856 /// promise so a resumed parent can replay the child result without re-running the child.
857 pub(crate) durable_subagent: bool,
858 /// Set to `true` for the duration of a turn whose LLM step was replayed from the journal.
859 ///
860 /// Used by `process_single_native_turn` to suppress re-printing already-emitted assistant
861 /// output (spec-064 §INV-001 §15 `RuntimeLayer` double-print suppression). Cleared at the
862 /// start of each turn.
863 pub(crate) durable_turn_replayed: bool,
864 /// `DurableConfig`/db url/cipher stashed cheaply (no I/O) by
865 /// `AgentBuilder::with_durable_agent_turns` when `[durable] enabled = true` and
866 /// `agent_turns = true`. Consumed by `ensure_session_durable_ctx` to lazily open the backend
867 /// and construct `durable_ctx` on the first durable-gated call. `None` when the P1 adapter is
868 /// not configured, in which case `durable_ctx` stays `None` forever (#5452 FR-002).
869 pub(crate) durable_agent_turns_config: Option<zeph_config::DurableConfig>,
870 /// Sibling companion to [`Self::durable_agent_turns_config`]: the `durable.db` connection
871 /// string resolved at bootstrap.
872 pub(crate) durable_agent_turns_db_url: Option<String>,
873 /// Sibling companion to [`Self::durable_agent_turns_config`]: `config.memory.sqlite_path`,
874 /// folded into the P1 `ExecutionId` derivation alongside `ConversationId` so distinct memory
875 /// databases never collide on execution identity even if they ever shared a journal
876 /// `db_url` (#5553).
877 pub(crate) durable_agent_turns_sqlite_path: Option<String>,
878 /// Sibling companion to [`Self::durable_agent_turns_config`]: the AEAD cipher to attach to
879 /// the backend, `None` when `encrypt_payload = false` (development mode only).
880 pub(crate) durable_agent_turns_cipher: Option<std::sync::Arc<dyn zeph_durable::PayloadCipher>>,
881 /// Set to `true` the first time `ensure_session_durable_ctx` runs (success or failure) so a
882 /// failed backend construction (missing vault key, disk error) is not retried on every turn.
883 /// Reset to `false` by `reset_durable_ctx_for_conversation_switch` (`/new`, `/conv resume`,
884 /// `/conv fork` — #5452 critic finding S1) so a conversation switch re-derives a fresh
885 /// execution keyed on the new `ConversationId` instead of leaving this latched forever.
886 pub(crate) durable_ctx_init_attempted: bool,
887 /// Writer handle for the P1 adapter's durable backend, flushed on shutdown by
888 /// `flush_durable_writer` (mirrors `services.orchestration.durable_writer` for the P2 adapter).
889 pub(crate) durable_writer: Option<zeph_durable::JournalWriterHandle>,
890 /// [`BlockingHandle`] for the P1 adapter's background `JournalWriter` actor task, aborted on
891 /// shutdown by `flush_durable_writer` (mirrors `services.orchestration.durable_writer_task`).
892 pub(crate) durable_writer_task: Option<zeph_common::task_supervisor::BlockingHandle<()>>,
893 /// When `true`, the system prompt volatile block includes the `CAVEMAN_DIRECTIVE` on every
894 /// turn, instructing the LLM to use ultra-compressed telegraphic output.
895 ///
896 /// Initialized from `config.caveman.default_on` in `builder.rs`. Toggled at runtime by
897 /// `/caveman [on|off]`. Preserved across `/new` (session resets do not clear style flags —
898 /// only process restart returns to `default_on`).
899 pub(crate) caveman_active: bool,
900 /// Durable JSONL event-log dual-writer for this conversation-session (spec-068, #5343).
901 ///
902 /// `Some` when `[session] enabled = true`; the session has minted a
903 /// [`zeph_common::SessionId`](zeph_common::SessionId) and opened its event log. `None` when
904 /// session persistence is disabled — in which case only the `SQLite` `messages` projection
905 /// is written (pre-#5343 behavior).
906 pub(crate) session_sink: Option<std::sync::Arc<zeph_agent_persistence::SessionSink>>,
907 /// `[session]` config snapshot (spec-068, #5343, D-9) — retained (not just consumed at
908 /// construction) so a mid-session `/conv resume`/`/conv fork` swap can locate `data_dir` to
909 /// replay a different session's event log and re-point [`Self::session_sink`] to it.
910 /// `None` when session persistence is disabled.
911 pub(crate) session_persistence_config: Option<zeph_config::SessionConfig>,
912}
913
914/// Extracted hook lists from `[hooks]` config, stored in `SessionState`.
915#[derive(Default)]
916pub(crate) struct HooksConfigSnapshot {
917 /// Hooks fired when working directory changes.
918 pub(crate) cwd_changed: Vec<zeph_config::HookDef>,
919 /// Hooks fired when a watched file changes.
920 pub(crate) file_changed_hooks: Vec<zeph_config::HookDef>,
921 /// Hooks fired when a tool execution is blocked by a `RuntimeLayer::before_tool` check.
922 pub(crate) permission_denied: Vec<zeph_config::HookDef>,
923 /// Hooks fired after each agent turn completes (#3327).
924 ///
925 /// Populated from `HooksConfig::turn_complete` at session construction. Shares the
926 /// `Notifier::should_fire` gate when a notifier is configured; fires on every completion
927 /// when no notifier is present.
928 pub(crate) turn_complete: Vec<zeph_config::HookDef>,
929 /// Hooks fired before each tool execution, matched by tool name pattern.
930 pub(crate) pre_tool_use: Vec<zeph_config::HookMatcher>,
931 /// Hooks fired after each tool execution completes, matched by tool name pattern.
932 pub(crate) post_tool_use: Vec<zeph_config::HookMatcher>,
933}
934
935// Groups message buffering and image staging state.
936pub(crate) struct MessageState {
937 pub(crate) messages: Vec<Message>,
938 // QueuedMessage is pub(super) in message_queue — same visibility as this struct; lint suppressed.
939 #[allow(private_interfaces)]
940 pub(crate) message_queue: VecDeque<QueuedMessage>,
941 /// Image parts staged by `/image` commands, attached to the next user message.
942 pub(crate) pending_image_parts: Vec<zeph_llm::provider::MessagePart>,
943 /// DB row ID of the most recently persisted message. Set by `persist_message`;
944 /// consumed by `push_message` call sites to populate `metadata.db_id` on in-memory messages.
945 pub(crate) last_persisted_message_id: Option<i64>,
946 /// DB message IDs pending hide after deferred tool pair summarization.
947 pub(crate) deferred_db_hide_ids: Vec<i64>,
948 /// Summary texts pending insertion after deferred tool pair summarization.
949 pub(crate) deferred_db_summaries: Vec<String>,
950 /// Set by `AgentBuilder::with_preloaded_messages` (spec-068, #5343) when `messages` was
951 /// seeded from a durable event-log replay rather than the default single system-prompt
952 /// message `Agent::new` always seeds. Makes [`super::super::Agent::load_history`]'s
953 /// `SQLite`-skip guard precise — `messages.is_empty()` is never true at that point in the
954 /// normal flow (the system prompt is always present), so a plain emptiness check cannot
955 /// distinguish "already hydrated from the log" from "not yet loaded."
956 pub(crate) history_preloaded: bool,
957}
958
959impl McpState {
960 /// Write the **full** `self.tools` set to the shared executor `RwLock`.
961 ///
962 /// This is the first of two writers to `shared_tools`. Within a turn this method must run
963 /// **before** `apply_pruned_tools`, which writes the pruned subset. The normal call order
964 /// guarantees this: tool-list change events call this method, and pruning runs later inside
965 /// `rebuild_system_prompt`. See also: `apply_pruned_tools`.
966 pub(crate) fn sync_executor_tools(&self) {
967 if let Some(ref shared) = self.shared_tools {
968 shared.write().clone_from(&self.tools);
969 }
970 }
971
972 /// Write the **pruned** tool subset to the shared executor `RwLock`.
973 ///
974 /// Must only be called **after** `sync_executor_tools` has established the full tool set for
975 /// the current turn. `self.tools` (the full set) is intentionally **not** modified.
976 ///
977 /// This method must **NOT** call `sync_executor_tools` internally — doing so would overwrite
978 /// the pruned subset with the full set. See also: `sync_executor_tools`.
979 pub(crate) fn apply_pruned_tools(&self, pruned: Vec<zeph_mcp::McpTool>) {
980 debug_assert!(
981 pruned.iter().all(|p| self
982 .tools
983 .iter()
984 .any(|t| t.server_id == p.server_id && t.name == p.name)),
985 "pruned set must be a subset of self.tools"
986 );
987 if let Some(ref shared) = self.shared_tools {
988 *shared.write() = pruned;
989 }
990 }
991
992 #[cfg(test)]
993 pub(crate) fn tool_count(&self) -> usize {
994 self.tools.len()
995 }
996}
997
998impl IndexState {
999 #[tracing::instrument(name = "core.index.fetch_code_rag", skip(self), fields(%query, token_budget))]
1000 pub(crate) async fn fetch_code_rag(
1001 &self,
1002 query: &str,
1003 token_budget: usize,
1004 ) -> Result<Option<String>, crate::agent::error::AgentError> {
1005 let Some(retriever) = &self.retriever else {
1006 return Ok(None);
1007 };
1008 if token_budget == 0 {
1009 return Ok(None);
1010 }
1011
1012 let result = retriever
1013 .retrieve(query, token_budget)
1014 .await
1015 .map_err(|e| crate::agent::error::AgentError::ContextError(format!("{e:#}")))?;
1016 let context_text = zeph_index::retriever::format_as_context(&result);
1017
1018 if context_text.is_empty() {
1019 Ok(None)
1020 } else {
1021 tracing::debug!(
1022 strategy = ?result.strategy,
1023 chunks = result.chunks.len(),
1024 tokens = result.total_tokens,
1025 "code context fetched"
1026 );
1027 Ok(Some(context_text))
1028 }
1029 }
1030}
1031
1032impl DebugState {
1033 pub(crate) fn start_iteration_span(&mut self, iteration_index: usize, text: &str) {
1034 if let Some(ref mut tc) = self.trace_collector {
1035 tc.begin_iteration(iteration_index, text);
1036 self.current_iteration_span_id = tc.current_iteration_span_id(iteration_index);
1037 }
1038 }
1039
1040 pub(crate) fn end_iteration_span(
1041 &mut self,
1042 iteration_index: usize,
1043 status: crate::debug_dump::trace::SpanStatus,
1044 ) {
1045 if let Some(ref mut tc) = self.trace_collector {
1046 tc.end_iteration(iteration_index, status);
1047 }
1048 self.current_iteration_span_id = None;
1049 }
1050
1051 pub(crate) fn switch_format(&mut self, new_format: crate::debug_dump::DumpFormat) {
1052 let was_trace = self.dump_format == crate::debug_dump::DumpFormat::Trace;
1053 let now_trace = new_format == crate::debug_dump::DumpFormat::Trace;
1054
1055 if now_trace
1056 && !was_trace
1057 && let Some(ref dump_dir) = self.dump_dir.clone()
1058 {
1059 let service_name = self.trace_service_name.clone();
1060 let redact = self.trace_redact;
1061 let trace_metadata = self.trace_metadata.clone();
1062 match crate::debug_dump::trace::TracingCollector::new(
1063 dump_dir.as_path(),
1064 &service_name,
1065 trace_metadata,
1066 redact,
1067 None,
1068 ) {
1069 Ok(collector) => {
1070 self.trace_collector = Some(collector);
1071 }
1072 Err(e) => {
1073 tracing::warn!(error = %e, "failed to create TracingCollector on format switch");
1074 }
1075 }
1076 }
1077 if was_trace
1078 && !now_trace
1079 && let Some(mut tc) = self.trace_collector.take()
1080 {
1081 tc.finish();
1082 }
1083
1084 self.dump_format = new_format;
1085 }
1086
1087 pub(crate) fn write_chat_debug_dump(
1088 &self,
1089 dump_id: Option<u32>,
1090 result: &zeph_llm::provider::ChatResponse,
1091 pii_filter: &zeph_sanitizer::pii::PiiFilter,
1092 ) {
1093 let Some((d, id)) = self.debug_dumper.as_ref().zip(dump_id) else {
1094 return;
1095 };
1096 let raw = match result {
1097 zeph_llm::provider::ChatResponse::Text(t) => t.clone(),
1098 zeph_llm::provider::ChatResponse::ToolUse {
1099 text, tool_calls, ..
1100 } => {
1101 let calls = serde_json::to_string_pretty(tool_calls).unwrap_or_default();
1102 format!(
1103 "{}\n\n---TOOL_CALLS---\n{calls}",
1104 text.as_deref().unwrap_or("")
1105 )
1106 }
1107 _ => String::new(),
1108 };
1109 let text = if pii_filter.is_enabled() {
1110 pii_filter.scrub(&raw).into_owned()
1111 } else {
1112 raw
1113 };
1114 d.dump_response(id, &text);
1115 }
1116}
1117
1118impl Default for McpState {
1119 fn default() -> Self {
1120 Self {
1121 tools: Vec::new(),
1122 registry: None,
1123 manager: None,
1124 allowed_commands: Vec::new(),
1125 max_dynamic: 10,
1126 elicitation_rx: None,
1127 shared_tools: None,
1128 tool_rx: None,
1129 server_outcomes: Vec::new(),
1130 pruning_cache: zeph_mcp::PruningCache::new(),
1131 pruning_provider: None,
1132 pruning_enabled: false,
1133 pruning_params: zeph_mcp::PruningParams::default(),
1134 semantic_index: None,
1135 discovery_strategy: zeph_mcp::ToolDiscoveryStrategy::default(),
1136 discovery_params: zeph_mcp::DiscoveryParams::default(),
1137 discovery_provider: None,
1138 elicitation_warn_sensitive_fields: true,
1139 pending_semantic_rebuild: false,
1140 }
1141 }
1142}
1143
1144impl Default for IndexState {
1145 fn default() -> Self {
1146 Self {
1147 retriever: None,
1148 repo_map_tokens: 0,
1149 cached_repo_map: None,
1150 repo_map_ttl: std::time::Duration::from_mins(5),
1151 }
1152 }
1153}
1154
1155impl Default for DebugState {
1156 fn default() -> Self {
1157 Self {
1158 debug_dumper: None,
1159 dump_format: crate::debug_dump::DumpFormat::default(),
1160 trace_collector: None,
1161 iteration_counter: 0,
1162 anomaly_detector: None,
1163 reasoning_model_warning: true,
1164 logging_config: crate::config::LoggingConfig::default(),
1165 dump_dir: None,
1166 trace_service_name: String::new(),
1167 trace_redact: true,
1168 trace_metadata: std::collections::HashMap::new(),
1169 current_iteration_span_id: None,
1170 }
1171 }
1172}
1173
1174impl Default for FeedbackState {
1175 fn default() -> Self {
1176 Self {
1177 detector: zeph_agent_feedback::FeedbackDetector::new(0.6),
1178 judge: None,
1179 llm_classifier: None,
1180 }
1181 }
1182}
1183
1184/// Goal lifecycle feature configuration stored in `RuntimeConfig`.
1185#[derive(Debug, Clone)]
1186pub(crate) struct GoalRuntimeConfig {
1187 /// Whether goal tracking is enabled.
1188 pub(crate) enabled: bool,
1189 /// Maximum allowed length (in Unicode chars) of goal text at creation.
1190 pub(crate) max_text_chars: usize,
1191 /// Default token budget for new goals (`None` = unlimited).
1192 pub(crate) default_token_budget: Option<u64>,
1193 /// Whether to inject the active goal block into the volatile system prompt region.
1194 pub(crate) inject_into_system_prompt: bool,
1195 /// Whether autonomous multi-turn execution is permitted.
1196 pub(crate) autonomous_enabled: bool,
1197 /// Maximum turns per autonomous session.
1198 pub(crate) autonomous_max_turns: u32,
1199 /// Provider name for the supervisor LLM call (`None` = use main provider).
1200 pub(crate) supervisor_provider: Option<zeph_config::ProviderName>,
1201 /// Turns between supervisor verification checks.
1202 pub(crate) verify_interval: u32,
1203 /// Timeout for a single supervisor call in seconds.
1204 pub(crate) supervisor_timeout_secs: u64,
1205 /// Consecutive stuck-detection threshold before aborting.
1206 pub(crate) max_stuck_count: u32,
1207 /// Wall-clock timeout in seconds for a single autonomous LLM turn.
1208 pub(crate) autonomous_turn_timeout_secs: u64,
1209 /// Maximum consecutive supervisor verification failures before pausing the session.
1210 pub(crate) max_supervisor_fail_count: u32,
1211}
1212
1213impl Default for GoalRuntimeConfig {
1214 fn default() -> Self {
1215 Self {
1216 enabled: false,
1217 max_text_chars: 2000,
1218 default_token_budget: None,
1219 inject_into_system_prompt: true,
1220 autonomous_enabled: false,
1221 autonomous_max_turns: 20,
1222 supervisor_provider: None,
1223 verify_interval: 5,
1224 supervisor_timeout_secs: 30,
1225 max_stuck_count: 3,
1226 autonomous_turn_timeout_secs: 300,
1227 max_supervisor_fail_count: 3,
1228 }
1229 }
1230}
1231
1232impl Default for RuntimeConfig {
1233 fn default() -> Self {
1234 Self {
1235 security: SecurityConfig::default(),
1236 timeouts: TimeoutConfig::default(),
1237 model_name: String::new(),
1238 active_provider_name: String::new(),
1239 permission_policy: zeph_tools::PermissionPolicy::default(),
1240 redact_credentials: true,
1241 rate_limiter: super::rate_limiter::ToolRateLimiter::new(
1242 super::rate_limiter::RateLimitConfig::default(),
1243 ),
1244 semantic_cache_enabled: false,
1245 semantic_cache_threshold: 0.95,
1246 semantic_cache_max_candidates: 10,
1247 dependency_config: zeph_tools::DependencyConfig::default(),
1248 adversarial_policy_info: None,
1249 spawn_depth: 0,
1250 budget_hint_enabled: true,
1251 channel_skills: zeph_config::ChannelSkillsConfig::default(),
1252 channel_tool_allowlist: None,
1253 loop_min_interval_secs: 5,
1254 layers: Vec::new(),
1255 supervisor_config: crate::config::TaskSupervisorConfig::default(),
1256 recap_config: zeph_config::RecapConfig::default(),
1257 acp_config: zeph_config::AcpConfig::default(),
1258 auto_recap_shown: false,
1259 msg_count_at_resume: 0,
1260 acp_subagent_spawn_fn: None,
1261 channel_type: String::new(),
1262 provider_persistence_enabled: true,
1263 persist_provider_overrides_enabled: true,
1264 restoring_provider: false,
1265 goals: GoalRuntimeConfig::default(),
1266 bare: false,
1267 }
1268 }
1269}
1270
1271impl SessionState {
1272 pub(crate) fn new() -> Self {
1273 Self {
1274 env_context: EnvironmentContext::gather(""),
1275 last_assistant_at: None,
1276 response_cache: None,
1277 parent_tool_use_id: None,
1278 current_turn_intent: None,
1279 status_tx: None,
1280 lsp_hooks: None,
1281 policy_config: None,
1282 hooks_config: HooksConfigSnapshot::default(),
1283 is_guest_context: false,
1284 durable_ctx: None,
1285 durable_subagent: false,
1286 durable_turn_replayed: false,
1287 durable_agent_turns_config: None,
1288 durable_agent_turns_db_url: None,
1289 durable_agent_turns_sqlite_path: None,
1290 durable_agent_turns_cipher: None,
1291 durable_ctx_init_attempted: false,
1292 durable_writer: None,
1293 durable_writer_task: None,
1294 caveman_active: false,
1295 session_sink: None,
1296 session_persistence_config: None,
1297 }
1298 }
1299}
1300
1301impl SkillState {
1302 pub(crate) fn new(
1303 registry: Arc<RwLock<SkillRegistry>>,
1304 matcher: Option<SkillMatcherBackend>,
1305 max_active_skills: usize,
1306 last_skills_prompt: String,
1307 ) -> Self {
1308 Self {
1309 registry,
1310 trust_snapshot: Arc::new(RwLock::new(HashMap::new())),
1311 skill_paths: Vec::new(),
1312 managed_dir: None,
1313 trust_config: crate::config::TrustConfig::default(),
1314 matcher,
1315 max_active_skills,
1316 disambiguation_threshold: 0.20,
1317 min_injection_score: 0.20,
1318 embedding_model: String::new(),
1319 skill_reload_rx: None,
1320 plugin_dirs_supplier: None,
1321 active_skill_names: Vec::new(),
1322 last_skills_prompt,
1323 prompt_mode: crate::config::SkillPromptMode::Auto,
1324 available_custom_secrets: HashMap::new(),
1325 cosine_weight: 0.7,
1326 hybrid_search: true,
1327 bm25_alpha: 0.7,
1328 bm25_index: None,
1329 two_stage_matching: false,
1330 confusability_threshold: 0.0,
1331 rl_head: None,
1332 rl_weight: 0.3,
1333 rl_warmup_updates: 50,
1334 generation_output_dir: None,
1335 query_rewrite_provider_name: String::new(),
1336 generation_provider_name: String::new(),
1337 disambiguate_provider_name: String::new(),
1338 generation_timeout_ms: 60_000,
1339 skill_evaluator: None,
1340 eval_weights: zeph_skills::evaluator::EvaluationWeights::default(),
1341 eval_threshold: 0.60,
1342 group_structured: false,
1343 support_similarity_threshold: 0.50,
1344 semantic_scan: false,
1345 semantic_scan_provider: String::new(),
1346 }
1347 }
1348}
1349
1350impl LifecycleState {
1351 pub(crate) fn new() -> Self {
1352 let (_tx, rx) = watch::channel(false);
1353 Self {
1354 shutdown: rx,
1355 start_time: Instant::now(),
1356 cancel_signal: Arc::new(tokio::sync::Notify::new()),
1357 cancel_token: tokio_util::sync::CancellationToken::new(),
1358 cancel_bridge_handle: None,
1359 config_path: None,
1360 config_reload_rx: None,
1361 plugins_dir: PathBuf::new(),
1362 startup_shell_overlay: ShellOverlaySnapshot::default(),
1363 shell_policy_handle: None,
1364 warmup_ready: None,
1365 update_notify_rx: None,
1366 custom_task_rx: None,
1367 user_loop: None,
1368 last_known_cwd: std::env::current_dir().unwrap_or_default(),
1369 file_changed_rx: None,
1370 file_watcher: None,
1371 supervisor: super::agent_supervisor::BackgroundSupervisor::new(
1372 &crate::config::TaskSupervisorConfig::default(),
1373 None,
1374 ),
1375 notifier: None,
1376 turn_llm_requests: 0,
1377 last_no_providers_at: None,
1378 pending_background_completions: VecDeque::new(),
1379 background_completion_rx: None,
1380 shell_executor_handle: None,
1381 task_supervisor: Arc::new(zeph_common::TaskSupervisor::new(
1382 tokio_util::sync::CancellationToken::new(),
1383 )),
1384 }
1385 }
1386}
1387
1388impl ProviderState {
1389 pub(crate) fn new(initial_prompt_tokens: u64) -> Self {
1390 Self {
1391 summary_provider: None,
1392 provider_override: None,
1393 judge_provider: None,
1394 probe_provider: None,
1395 compress_provider: None,
1396 cached_prompt_tokens: initial_prompt_tokens,
1397 server_compaction_active: false,
1398 stt: None,
1399 provider_pool: Vec::new(),
1400 provider_config_snapshot: None,
1401 }
1402 }
1403}
1404
1405impl MetricsState {
1406 pub(crate) fn new(token_counter: Arc<zeph_memory::TokenCounter>) -> Self {
1407 Self {
1408 metrics_tx: None,
1409 cost_tracker: None,
1410 token_counter,
1411 extended_context: false,
1412 classifier_metrics: None,
1413 timing_window: std::collections::VecDeque::new(),
1414 pending_timings: crate::metrics::TurnTimings::default(),
1415 histogram_recorder: None,
1416 }
1417 }
1418}
1419
1420impl ExperimentState {
1421 pub(crate) fn new() -> Self {
1422 let (notify_tx, notify_rx) = tokio::sync::mpsc::channel::<String>(4);
1423 Self {
1424 config: crate::config::ExperimentConfig::default(),
1425 cancel: None,
1426 handle: None,
1427 baseline: zeph_experiments::ConfigSnapshot::default(),
1428 eval_provider: None,
1429 notify_rx: Some(notify_rx),
1430 notify_tx,
1431 }
1432 }
1433}
1434
1435pub(super) mod security;
1436pub(super) mod skill;
1437
1438#[cfg(test)]
1439mod tests;