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
//! Harness-side compaction *triggers*: manual `/compact`-style forced compaction and the
//! auto-threshold compaction that runs before each prompt. Lives with the rest of the
//! compaction layer (`algorithm.rs` / `compaction.rs` / `branch_summarization.rs`) because
//! it is the agent-runtime integration of that layer; the impl block extends
//! [`crate::agent::assembly::AgentHarness`] but Rust impl blocks may live in any module.
//! Split out of `assembly/mod.rs` by domain.
use crate::agent::AgentRunError;
use crate::agent::assembly::SessionEvent;
use crate::agent::compaction::algorithm::SummarizeRequest;
use crate::agent::compaction::compaction::{
SummarizeError, compact_with_model_context, estimate_context_tokens, project_summary_messages,
};
use crate::agent::messages::compaction_summary;
use crate::agent::session::session::SessionTreeEntry;
use crate::observability::{
ErrorCategory, OperationDetail, OperationOutcome, OperationScope, RuntimeMeasurements,
};
use crate::types::AgentMessage;
impl crate::agent::assembly::AgentHarness {
/// Force a compaction immediately, regardless of token thresholds. Useful for `/compact`-
/// style slash commands.
pub async fn force_compact(
&self,
custom_instructions: Option<String>,
) -> Result<bool, AgentRunError> {
self.start_runtime_extensions().await;
self.do_compact(true, custom_instructions).await
}
/// Summarize the WHOLE session for a collapse (issue #94): bypasses the
/// auto-compaction cut point so even a small session gets a model summary.
/// Runs through the configured algorithm (builtin LLM summarizer or a
/// custom TS algorithm) and returns the summary text.
///
/// Returns `Ok(None)` when there is no model, no material, or the summary
/// came back empty — callers fall back to deterministic material. Nothing
/// is persisted here; the caller owns summary placement.
pub async fn summarize_for_collapse(
&self,
custom_instructions: Option<String>,
) -> Result<Option<String>, AgentRunError> {
self.start_runtime_extensions().await;
let model = match self.agent.state().model.clone() {
Some(model) => model,
None => return Ok(None),
};
let settings = self.compaction_settings.lock().clone();
let algorithm = self.compact_algorithms.algorithm(&settings.algorithm);
let entries = match self.session.branch(None).await {
Ok(entries) => entries,
Err(_) => return Ok(None),
};
// Fold everything: persistent model context plus every session
// message, projected for summarization (issue #101) — tool-output
// bodies, tool-call arguments and thinking are capped per block, the
// projected total is bounded, and custom self-summaries are skipped.
let mut messages = self.runtime_compaction_context_messages();
messages.extend(project_summary_messages(&entries));
if messages.is_empty() {
return Ok(None);
}
let request = SummarizeRequest {
model: &model,
messages: &messages,
custom_instructions: custom_instructions.as_deref(),
settings: &settings,
stream_fn: self.stream_fn.as_ref(),
cancel: &self.agent.active_token().unwrap_or_default(),
};
match algorithm.summarize_prefix(&request).await {
Ok(outcome) if !outcome.summary.trim().is_empty() => Ok(Some(outcome.summary)),
Ok(_) => Ok(None),
Err(SummarizeError::Aborted) => Ok(None),
Err(error) => Err(AgentRunError::Other(format!(
"collapse summarization failed: {error}"
))),
}
}
pub(crate) async fn run_auto_compaction(&self) -> Result<(), AgentRunError> {
let settings = self.compaction_settings.lock().clone();
if !settings.enabled {
return Ok(());
}
let (context_tokens, context_window) = {
let s = self.agent.state();
let model = match &s.model {
Some(m) => m,
None => return Ok(()),
};
let estimate = estimate_context_tokens(&s.messages);
(estimate.tokens, model.context_window)
};
let algorithm = self.compact_algorithms.algorithm(&settings.algorithm);
if !algorithm
.decide_compact(context_tokens, context_window, &settings)
.await
{
return Ok(());
}
let _ = self.do_compact(false, None).await?;
Ok(())
}
/// Shared implementation behind auto + manual compaction. Returns `true` when compaction
/// actually ran.
///
/// Operates on the real session entries (via `self.session.branch(None)`) so the
/// `first_kept_entry_id` we persist on the `Compaction` record is reachable in the session
/// jsonl. The previous implementation synthesized fake `Message` entries from in-memory
/// `state.messages` with fresh uuidv7s — those ids were never written to the session, so
/// `--resume` could not locate them in `build_session_context` and silently dropped all
/// pre-compaction tail. See issue #19.
async fn do_compact(
&self,
from_hook: bool,
custom_instructions: Option<String>,
) -> Result<bool, AgentRunError> {
let model = match self.agent.state().model.clone() {
Some(m) => m,
None => return Ok(false),
};
let settings = self.compaction_settings.lock().clone();
self.before_runtime_compaction(&settings.algorithm, from_hook)
.await?;
let scope = OperationScope::start(
self.agent.runtime_observer(),
self.agent.active_run_operation(),
self.agent.observation_context(),
OperationDetail::Compaction {
algorithm: settings.algorithm.clone(),
provider: model.provider.0.clone(),
model: model.id.clone(),
},
);
// Source of truth: real session entries with their real ids.
let entries = match self.session.branch(None).await {
Ok(es) => es,
Err(e) => {
// Read failure is non-fatal: skip this compaction attempt; the loop will try
// again next time. We do not append a `Compaction` record and do not mutate
// agent state.
self.emit_harness_event(SessionEvent::Compaction {
from_hook,
summary: format!("compaction skipped: session branch read failed: {e}"),
tokens_before: 0,
});
scope.finish(
OperationOutcome::Failed,
Some(ErrorCategory::Persistence),
RuntimeMeasurements::default(),
);
self.runtime_compaction_failed(
serde_json::json!({
"algorithm": settings.algorithm,
"category": "persistence",
"message": e.to_string(),
}),
false,
)
.await;
return Ok(false);
}
};
let algorithm = self.compact_algorithms.algorithm(&settings.algorithm);
let persistent_model_context = self.runtime_compaction_context_messages();
let result = compact_with_model_context(
algorithm.as_ref(),
model,
&entries,
&persistent_model_context,
&settings,
custom_instructions,
self.stream_fn.clone(),
self.agent.active_token().unwrap_or_default(),
)
.await;
let result = match result {
Ok(r) if !r.summary.is_empty() => r,
Ok(r) => {
scope.finish(
OperationOutcome::Skipped,
None,
RuntimeMeasurements {
input_tokens: r.usage.input,
output_tokens: r.usage.output,
cache_read_tokens: r.usage.cache_read,
cache_write_tokens: r.usage.cache_write,
..Default::default()
},
);
self.runtime_compaction_succeeded(serde_json::json!({
"algorithm": settings.algorithm,
"applied": false,
"tokensBefore": r.tokens_before,
}))
.await;
return Ok(false);
}
Err(SummarizeError::Aborted) => {
scope.finish(
OperationOutcome::Cancelled,
Some(ErrorCategory::Cancellation),
RuntimeMeasurements::default(),
);
self.runtime_compaction_failed(
serde_json::json!({
"algorithm": settings.algorithm,
"category": "cancelled",
}),
true,
)
.await;
return Ok(false);
}
Err(e) => {
scope.finish(
OperationOutcome::Failed,
Some(ErrorCategory::Provider),
RuntimeMeasurements::default(),
);
self.runtime_compaction_failed(
serde_json::json!({
"algorithm": settings.algorithm,
"category": "provider",
"message": e.to_string(),
}),
false,
)
.await;
return Err(AgentRunError::Other(format!("compaction failed: {e}")));
}
};
let first_kept_entry_id = result.first_kept_entry_id.clone().unwrap_or_default();
// Persist a compaction entry to the session.
if let Err(e) = self
.session
.append_compaction(
result.summary.clone(),
first_kept_entry_id.clone(),
result.tokens_before,
None,
from_hook,
)
.await
{
scope.finish(
OperationOutcome::Failed,
Some(ErrorCategory::Persistence),
RuntimeMeasurements {
input_tokens: result.usage.input,
output_tokens: result.usage.output,
cache_read_tokens: result.usage.cache_read,
cache_write_tokens: result.usage.cache_write,
..Default::default()
},
);
self.runtime_compaction_failed(
serde_json::json!({
"algorithm": settings.algorithm,
"category": "persistence",
"message": e.to_string(),
}),
false,
)
.await;
return Err(AgentRunError::Other(format!(
"session append compaction: {e}"
)));
}
self.emit_harness_event(SessionEvent::Compaction {
from_hook,
summary: result.summary.clone(),
tokens_before: result.tokens_before,
});
// Replace agent state's prefix with a single compaction-summary message followed by
// the in-memory tail that corresponds to the kept session entries.
//
// `state.messages` is the in-memory mirror of session `Message` entries (the agent loop
// only appends `AgentMessage::Llm` variants there, and `make_session_listener`
// persists each one). So the in-memory index for the first kept entry equals the
// count of `Message` entries strictly before `first_kept_entry_id` in `entries`.
// Non-Message entries (ModelChange, ThinkingLevelChange, Custom{custom_type=trigger},
// BranchSummary, etc.) are not in `state.messages` and are skipped naturally.
{
let mut s = self.agent.state();
let mut new_msgs: Vec<AgentMessage> = vec![compaction_summary(result.summary.clone())];
if !first_kept_entry_id.is_empty() {
if let Some(real_idx) = entries.iter().position(|e| e.id() == first_kept_entry_id) {
let kept_in_memory_start = entries[..real_idx]
.iter()
.filter(|e| matches!(e, SessionTreeEntry::Message { .. }))
.count();
if kept_in_memory_start <= s.messages.len() {
new_msgs.extend(s.messages[kept_in_memory_start..].iter().cloned());
}
// If `kept_in_memory_start` is out of range, the in-memory state has
// diverged from the session (race or external mutation). We keep just the
// summary; the next prompt rehydrates the rest if needed.
}
// If `first_kept_entry_id` is non-empty but not found in `entries`, treat as a
// legacy (pre-fix) bad record: keep just the summary, do not crash. Documented
// in CHANGELOG `### Fixed`.
}
// Empty `first_kept_entry_id` means `entries` was empty pre-compaction — only the
// summary is needed.
s.messages = new_msgs;
}
scope.finish(
OperationOutcome::Succeeded,
None,
RuntimeMeasurements {
input_tokens: result.usage.input,
output_tokens: result.usage.output,
cache_read_tokens: result.usage.cache_read,
cache_write_tokens: result.usage.cache_write,
..Default::default()
},
);
self.runtime_compaction_succeeded(serde_json::json!({
"algorithm": settings.algorithm,
"applied": true,
"tokensBefore": result.tokens_before,
"firstKeptEntryId": first_kept_entry_id,
}))
.await;
Ok(true)
}
}
#[cfg(test)]
tests_bridge_macro::tests_bridge!("agent/compaction/triggers");
#[cfg(test)]
mod triggers_linecov_tests {
tests_bridge_macro::tests_bridge!("agent/compaction/triggers/linecov");
}