Skip to main content

zeph_core/agent/state/
mod.rs

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