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