zeph-core 0.20.1

Core agent loop, configuration, context builder, metrics, and vault for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Adapter types that bridge `Agent<C>` internals to the callback traits declared in
//! `zeph-agent-context`.
//!
//! [`CompactionAdapters`] is a bundle struct that owns all four adapters and exposes
//! a single `populate` method so the `compact_context` shim stays at ≤10 statements.

use std::pin::Pin;
use std::sync::Arc;

use zeph_agent_context::state::{
    CompactionPersistence, CompactionProbeCallback, MetricsCallback, ProbeOutcome,
    QdrantPersistFuture, ToolOutputArchive,
};
use zeph_llm::any::AnyProvider;
use zeph_llm::provider::Message;
use zeph_memory::{CategoryScore, CompactionProbeConfig};

use crate::agent::Agent;
use crate::channel::Channel;
use crate::metrics::MetricsSnapshot;

// ── MetricsCollectorCallback ──────────────────────────────────────────────────

/// Implements [`MetricsCallback`] by delegating to the agent's `watch::Sender<MetricsSnapshot>`.
///
/// Constructed from a clone of `self.runtime.metrics.metrics_tx` — cheap, does not retain
/// a borrow on `Agent<C>`.
pub(in crate::agent) struct MetricsCollectorCallback {
    tx: Option<tokio::sync::watch::Sender<MetricsSnapshot>>,
}

impl MetricsCollectorCallback {
    /// Create a new callback wrapping the given metrics sender.
    pub(in crate::agent) fn new(tx: Option<tokio::sync::watch::Sender<MetricsSnapshot>>) -> Self {
        Self { tx }
    }

    fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
        if let Some(ref tx) = self.tx {
            tx.send_modify(f);
        }
    }
}

impl MetricsCallback for MetricsCollectorCallback {
    fn record_hard_compaction(&self, turns_since_last: Option<u32>) {
        self.update(|m| {
            m.compaction_hard_count += 1;
            if let Some(turns) = turns_since_last {
                m.compaction_turns_after_hard.push(u64::from(turns));
            }
        });
    }

    fn record_tool_output_prune(&self, count: usize) {
        self.update(|m| {
            m.tool_output_prunes = m.tool_output_prunes.saturating_add(count as u64);
        });
    }

    fn record_compaction_probe_pass(
        &self,
        score: f32,
        category_scores: Vec<CategoryScore>,
        threshold: f32,
        hard_fail_threshold: f32,
    ) {
        self.update(|m| {
            m.compaction_probe_passes += 1;
            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::Pass);
            m.last_probe_score = Some(score);
            m.last_probe_category_scores = Some(category_scores);
            m.compaction_probe_threshold = threshold;
            m.compaction_probe_hard_fail_threshold = hard_fail_threshold;
        });
    }

    fn record_compaction_probe_soft_fail(
        &self,
        score: f32,
        category_scores: Vec<CategoryScore>,
        threshold: f32,
        hard_fail_threshold: f32,
    ) {
        self.update(|m| {
            m.compaction_probe_soft_failures += 1;
            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::SoftFail);
            m.last_probe_score = Some(score);
            m.last_probe_category_scores = Some(category_scores);
            m.compaction_probe_threshold = threshold;
            m.compaction_probe_hard_fail_threshold = hard_fail_threshold;
        });
    }

    fn record_compaction_probe_hard_fail(
        &self,
        score: f32,
        category_scores: Vec<CategoryScore>,
        threshold: f32,
        hard_fail_threshold: f32,
    ) {
        self.update(|m| {
            m.compaction_probe_failures += 1;
            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::HardFail);
            m.last_probe_score = Some(score);
            m.last_probe_category_scores = Some(category_scores);
            m.compaction_probe_threshold = threshold;
            m.compaction_probe_hard_fail_threshold = hard_fail_threshold;
        });
    }

    fn record_compaction_probe_error(&self) {
        self.update(|m| {
            m.compaction_probe_errors += 1;
            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::Error);
            m.last_probe_score = None;
            m.last_probe_category_scores = None;
        });
    }
}

// ── AgentProbe ────────────────────────────────────────────────────────────────

/// Implements [`CompactionProbeCallback`] using `zeph_memory::validate_compaction`.
///
/// Owns cloned `Arc`s so it does not retain a borrow on `Agent<C>` after construction.
/// Per the probe contract: calls `dump_compaction_probe`, updates all four metric counters,
/// and returns only the routing verdict.
pub(in crate::agent) struct AgentProbe {
    probe_cfg: CompactionProbeConfig,
    probe_provider: AnyProvider,
    metrics: MetricsCollectorCallback,
    debug_dumper: Option<crate::debug_dump::DebugDumper>,
}

impl AgentProbe {
    /// Construct from cloned values extracted from `Agent<C>`.
    pub(in crate::agent) fn new<C: Channel>(agent: &Agent<C>) -> Self {
        let probe_cfg = agent.context_manager.compression.probe.clone();
        let probe_provider = agent.probe_or_summary_provider().clone();
        let metrics = MetricsCollectorCallback::new(agent.runtime.metrics.metrics_tx.clone());
        let debug_dumper = agent.runtime.debug.debug_dumper.clone();
        Self {
            probe_cfg,
            probe_provider,
            metrics,
            debug_dumper,
        }
    }
}

impl CompactionProbeCallback for AgentProbe {
    fn validate<'a>(
        &'a mut self,
        to_compact: &'a [Message],
        summary: &'a str,
    ) -> Pin<Box<dyn std::future::Future<Output = ProbeOutcome> + Send + 'a>> {
        Box::pin(async move {
            if !self.probe_cfg.enabled {
                return ProbeOutcome::Pass;
            }

            let result = zeph_memory::validate_compaction(
                self.probe_provider.clone(),
                to_compact.to_vec(),
                summary.to_owned(),
                &self.probe_cfg,
            )
            .await;

            match result {
                Err(e) => {
                    tracing::warn!("compaction probe error (non-blocking): {e:#}");
                    self.metrics.record_compaction_probe_error();
                    ProbeOutcome::Pass
                }
                Ok(None) => ProbeOutcome::Pass,
                Ok(Some(ref probe_result)) => {
                    if let Some(ref dumper) = self.debug_dumper {
                        dumper.dump_compaction_probe(probe_result);
                    }

                    let score = probe_result.score;
                    let cats = probe_result.category_scores.clone();
                    let threshold = probe_result.threshold;
                    let hard_fail = probe_result.hard_fail_threshold;

                    match probe_result.verdict {
                        zeph_memory::ProbeVerdict::Pass => {
                            tracing::info!(score, "compaction probe passed");
                            self.metrics
                                .record_compaction_probe_pass(score, cats, threshold, hard_fail);
                            ProbeOutcome::Pass
                        }
                        zeph_memory::ProbeVerdict::SoftFail => {
                            tracing::warn!(
                                score,
                                threshold,
                                "compaction probe SOFT FAIL — proceeding with warning"
                            );
                            self.metrics.record_compaction_probe_soft_fail(
                                score, cats, threshold, hard_fail,
                            );
                            ProbeOutcome::SoftFail
                        }
                        zeph_memory::ProbeVerdict::HardFail => {
                            tracing::warn!(
                                score,
                                threshold = hard_fail,
                                "compaction probe HARD FAIL — keeping original messages"
                            );
                            self.metrics.record_compaction_probe_hard_fail(
                                score, cats, threshold, hard_fail,
                            );
                            ProbeOutcome::HardFail
                        }
                        zeph_memory::ProbeVerdict::Error => {
                            // validate_compaction returns Err on errors, not Ok(Error).
                            debug_assert!(false, "ProbeVerdict::Error reached inside Ok path");
                            self.metrics.record_compaction_probe_error();
                            ProbeOutcome::Pass
                        }
                    }
                }
            }
        })
    }
}

// ── AgentArchive ──────────────────────────────────────────────────────────────

/// Implements [`ToolOutputArchive`] using the agent's `SQLite` memory store (Memex #2432).
///
/// Saves non-empty, non-archived tool output bodies to `tool_overflow` and returns
/// reference strings for injection as a postfix after LLM summarization.
pub(in crate::agent) struct AgentArchive {
    archive_enabled: bool,
    memory: Option<Arc<zeph_memory::semantic::SemanticMemory>>,
    conversation_id: Option<zeph_memory::ConversationId>,
}

impl AgentArchive {
    /// Construct from values extracted from `Agent<C>`.
    pub(in crate::agent) fn new<C: Channel>(agent: &Agent<C>) -> Self {
        Self {
            archive_enabled: agent.context_manager.compression.archive_tool_outputs,
            memory: agent.services.memory.persistence.memory.clone(),
            conversation_id: agent.services.memory.persistence.conversation_id,
        }
    }
}

impl ToolOutputArchive for AgentArchive {
    fn archive<'a>(
        &'a self,
        to_compact: &'a [Message],
    ) -> Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send + 'a>> {
        Box::pin(async move {
            if !self.archive_enabled {
                return Vec::new();
            }
            let (Some(memory), Some(cid)) = (&self.memory, self.conversation_id) else {
                return Vec::new();
            };

            let mut refs = Vec::new();
            let sqlite = memory.sqlite().clone();

            for msg in to_compact {
                for part in &msg.parts {
                    if let zeph_llm::provider::MessagePart::ToolOutput {
                        body, tool_name, ..
                    } = part
                    {
                        if body.is_empty()
                            || body.starts_with("[archived:")
                            || body.starts_with("[full output stored")
                            || body.starts_with("[tool output pruned")
                        {
                            continue;
                        }
                        match sqlite.save_archive(cid.0, body.as_bytes()).await {
                            Ok(uuid) => {
                                let bytes = body.len();
                                refs.push(format!(
                                    "[archived:{uuid} — tool: {tool_name}{bytes} bytes]"
                                ));
                            }
                            Err(e) => {
                                tracing::warn!(
                                    error = %e,
                                    "Memex: failed to archive tool output (non-fatal)"
                                );
                            }
                        }
                    }
                }
            }

            if !refs.is_empty() {
                tracing::debug!(
                    archived = refs.len(),
                    "Memex: archived tool outputs before compaction"
                );
            }
            refs
        })
    }
}

// ── AgentPersistence ──────────────────────────────────────────────────────────

/// Implements [`CompactionPersistence`] by persisting to `SQLite` synchronously and
/// returning a `'static` Qdrant future for off-thread dispatch.
///
/// The `SQLite` path runs inline (it is fast and failure is non-fatal).
/// The Qdrant path is returned as a boxed future to be dispatched through
/// `BackgroundSupervisor::spawn_summarization`.
pub(in crate::agent) struct AgentPersistence {
    memory: Option<Arc<zeph_memory::semantic::SemanticMemory>>,
    conversation_id: Option<zeph_memory::ConversationId>,
}

impl AgentPersistence {
    /// Construct from values extracted from `Agent<C>`.
    pub(in crate::agent) fn new<C: Channel>(agent: &Agent<C>) -> Self {
        Self {
            memory: agent.services.memory.persistence.memory.clone(),
            conversation_id: agent.services.memory.persistence.conversation_id,
        }
    }
}

impl CompactionPersistence for AgentPersistence {
    fn after_compaction<'a>(
        &'a self,
        compacted_count: usize,
        summary_content: &'a str,
        summary: &'a str,
    ) -> Pin<Box<dyn std::future::Future<Output = (bool, Option<QdrantPersistFuture>)> + Send + 'a>>
    {
        Box::pin(async move {
            let (Some(memory), Some(cid)) = (&self.memory, self.conversation_id) else {
                return (false, None);
            };

            // Synchronous SQLite persist — clone DbStore so no &SemanticMemory survives .await.
            let sqlite = memory.sqlite().clone();
            let ids = sqlite
                .oldest_message_ids(cid, u32::try_from(compacted_count + 1).unwrap_or(u32::MAX))
                .await;
            let sqlite_failed = match ids {
                Ok(ids) if ids.len() >= 2 => {
                    let start = ids[1];
                    let end = ids[compacted_count.min(ids.len() - 1)];
                    if let Err(e) = sqlite
                        .replace_conversation(cid, start..=end, "system", summary_content)
                        .await
                    {
                        tracing::warn!("failed to persist compaction in sqlite: {e:#}");
                        true
                    } else {
                        false
                    }
                }
                Ok(_) => false,
                Err(e) => {
                    tracing::warn!("failed to get message ids for compaction: {e:#}");
                    true
                }
            };

            // Build the Qdrant future as a 'static boxed future (clone Arc, own String).
            let memory_arc = Arc::clone(memory);
            let summary_owned = summary.to_owned();
            let qdrant_fut: QdrantPersistFuture = Box::pin(async move {
                if let Err(e) = memory_arc.store_session_summary(cid, &summary_owned).await {
                    tracing::warn!("failed to store session summary: {e:#}");
                }
                false
            });

            (sqlite_failed, Some(qdrant_fut))
        })
    }
}

// ── CompactionAdapters bundle ─────────────────────────────────────────────────

/// Bundle of all four compaction adapters for `Agent<C>`.
///
/// Constructed once from `&mut Agent<C>` in the `compact_context` shim, then wired
/// into the [`zeph_agent_context::state::ContextSummarizationView`] via [`Self::populate`].
/// This collapses four separate adapter constructions into one shim statement.
pub(in crate::agent) struct CompactionAdapters {
    probe: AgentProbe,
    archive: AgentArchive,
    persistence: AgentPersistence,
    metrics: MetricsCollectorCallback,
}

impl CompactionAdapters {
    /// Build all four adapters from the agent. Only reads fields — does not retain a borrow.
    pub(in crate::agent) fn new<C: Channel>(agent: &Agent<C>) -> Self {
        let probe = AgentProbe::new(agent);
        let archive = AgentArchive::new(agent);
        let persistence = AgentPersistence::new(agent);
        let metrics = MetricsCollectorCallback::new(agent.runtime.metrics.metrics_tx.clone());
        Self {
            probe,
            archive,
            persistence,
            metrics,
        }
    }

    /// Wire all four adapters into `summ` in a single call.
    ///
    /// The shim calls this immediately after `summarization_view()` and
    /// `with_compression_guidelines`.
    pub(in crate::agent) fn populate<'a>(
        &'a mut self,
        summ: &mut zeph_agent_context::state::ContextSummarizationView<'a>,
    ) {
        summ.probe = Some(&mut self.probe);
        summ.archive = Some(&self.archive);
        summ.persistence = Some(&self.persistence);
        summ.metrics = Some(&self.metrics);
    }
}